Search code examples
vb.netexceptionpdfitextpdf-generation

PDFGeneration in VB.Net using iText: Trailer not found (iText.Kernel.PdfException)


I have inherited the following code to generate a PDF:

' Generate letter
   
Dim oMemory_Document_Writer As New System.IO.MemoryStream()
Dim oPDF_Document_Writer As PdfWriter = New PdfWriter(oMemory_Document_Writer)

If sLang = "D" Then
    sTemplate_Based_On_Language = cTemplate_D
Else
    sTemplate_Based_On_Language = cTemplate_F
End If
    
Dim oPDF_Reader_Form_With_Fields As PdfReader = New PdfReader(sTemplate_Based_On_Language)
Dim oPDF_Document_Form_Filled_Out As PdfDocument = New PdfDocument(oPDF_Reader_Form_With_Fields, oPDF_Document_Writer)
Dim oForm_Letter As iText.Forms.PdfAcroForm = iText.Forms.PdfAcroForm.GetAcroForm(oPDF_Document_Form_Filled_Out, True)
Dim oForm_Fields As IDictionary(Of String, iText.Forms.Fields.PdfFormField)
    
oForm_Fields = oForm_Letter.GetFormFields()    
oForm_Fields.Item(PDF_Variables.Letter.Nom).SetValue(oClient.Name)
oForm_Fields.Item(PDF_Variables.Letter.Adresse).SetValue(oClient.Adresse)
    
sBarcode = sCode
oForm_Fields.Item(PDF_Variables.Letter.BarCode.Bar).SetValue(GED_Code128b(sBarcode))
oForm_Fields.Item(PDF_Variables.Letter.BarCode.Text).SetValue("Code " & sBarcode )

oForm_Letter.FlattenFields()
oPDF_Reader_Form_With_Fields.Close()
    ' V Exception thrown in next line V
oPDF_Document_Form_Filled_Out = New PdfDocument(New PdfReader(New System.IO.MemoryStream(oMemory_Document_Writer.ToArray()))) 
oPDF_Document_Form_Filled_Out.CopyPagesTo(1, oPDF_Document_Form_Filled_Out.GetNumberOfPages(), oPDF_Document_Result)
oPDF_Document_Form_Filled_Out.Close()

It throws an exception in the indicated line

I read several threads here related to this issue, but none of the solutions have worked for me so far.

How do I fix this error?

Here is the full StackTrace

If I call oPDF_Document_Form_Filled_Out.Close() before (as suggested by mkl and other posts, I get this exception : "System.ObjectDisposedException: 'Cannot access a closed file." (Stacktrace)


Solution

  • In your code you first create a PdfDocument in oPDF_Document_Form_Filled_Out and thereafter you use its output for further processing.

    To use the output of the first PdfDocument, though, it must be closed. Otherwise it's incomplete. You forgot that in your code.

    You do close the PdfReader that PdfDocument has been constructed for. When closing the PdfDocument, it may require access to its PdfReader. Thus, you must close the PdfDocument before closing the PdfReader.