0

In order to duplicate a form in a PDF, I'm doing the following (used this code as reference):

Dim pdfDocumentR As PdfDocument
Dim writer As PdfWriter = New PdfWriter(DEST)
writer.SetSmartMode(True)
Dim pdfDocumentW As New PdfDocument(writer)
Dim tmp As ByteArrayOutputStream
Dim form As PdfAcroForm
Dim fields As IDictionary(Of String, PdfFormField)
Dim tf As PdfFormField

For Each documento As Documento In documentos
    tmp = New ByteArrayOutputStream()
    pdfDocumentR = New PdfDocument(New PdfReader(SRC), New PdfWriter(tmp))
    form = PdfAcroForm.GetAcroForm(pdfDocumentR, False)
    fields = form.GetFormFields()

    documento.campos.remove("templateID")
    Dim keys As Dictionary(Of String, String).KeyCollection = documento.campos.Keys
    For Each key As String In keys
        Dim value As String
        documento.campos.TryGetValue(key, value)
        fields.TryGetValue(key, tf)
        tf.SetValue(value)
    Next

    form.FlattenFields()
    pdfDocumentR.Close()

    pdfDocumentR = New PdfDocument(New PdfReader(New MemoryStream(tmp.GetBuffer())))
    pdfDocumentR.CopyPagesTo(1, pdfDocumentR.GetNumberOfPages(), pdfDocumentW, New PdfPageFormCopier())
    pdfDocumentR.Close()
Next
pdfDocumentW.Close()

I'm getting 'System.NullReferenceException' when it tries to flatten the form - form.FlattenFields().

Could someone help me?

  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Blackwood Apr 17 '18 at 21:59
  • Either `form` is `Nothing` or the exception is being thrown inside `FlattenFields`. The former seems unlikely, given that you call `form.GetFormFields` earlier but that's easy to check, so do that. If it's the latter (which the exception stack trace will tell you) then you need to do some reading about that `FlattenFields` method and what it expects. – jmcilhinney Apr 18 '18 at 01:24
  • I get the exception also, when `pdfDocument.Close()` is called after `FlattenFields()` is called. My exception comes from deep inside iText, in `iText.Kernel.Pdf.PdfNumber.GenerateValue()`, which apparently is called when the `PdfWriter` is flushed. Did you ever find the cause of the error? – Steve Schmitt Jul 18 '18 at 06:35
  • FYI my exception went away when I upgraded to iText 7.1.3 – Steve Schmitt Aug 31 '18 at 07:26

0 Answers0