使用 iText 在 VB.Net 中进行 PDFGeneration:找不到预告片 (iText.Kernel.PdfException)

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

提问人:Jay Weber 提问时间:7/13/2023 最后编辑:Jay Weber 更新时间:7/18/2023 访问量:71

问:

我继承了以下代码来生成 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()

它在指示的行中引发异常

我在这里阅读了与此问题相关的几个线程,但到目前为止,没有一个解决方案对我有用。

如何修复此错误?

这是完整的 StackTrace

如果我之前调用 oPDF_Document_Form_Filled_Out.Close()(正如 mkl 和其他帖子所建议的那样,我会得到以下异常:“System.ObjectDisposedException:'无法访问关闭的文件。(堆栈跟踪)

vb.net 例外 pdf itext pdf-generation

评论

0赞 mkl 7/14/2023
你忘了关闭前者.oPDF_Document_Form_Filled_Out
1赞 Tu deschizi eu inchid 7/15/2023
不幸的是,我们陷入了僵局。如果您无法提供代表您正在使用的文件的示例 PDF,那么就无法测试解决方案,这意味着这里的任何人都不太可能为您提供帮助。
1赞 mkl 7/15/2023
我不确定我明白你的意思,我在导致异常的行之前关闭了它'' - 你甚至在之前必须关闭它.已打开与该.因此,在关闭过程中,它可能需要该读者。oPDF_Reader_Form_With_Fields.Close()PdfDocumentPdfReader
1赞 Jay Weber 7/17/2023
按照@mkl的建议在关闭 PdfReader (oPDF_Reader_Form_With_Fields) 之前关闭 PdfDocument (oPDF_Document_Form_Filled_Out) 解决了问题,非常感谢!
2赞 Jay Weber 7/18/2023
你加,我接受:)

答:

1赞 mkl 7/18/2023 #1

在代码中,首先创建一个 in,然后使用其输出进行进一步处理。PdfDocumentoPDF_Document_Form_Filled_Out

但是,要使用第一个的输出,必须关闭它。否则它是不完整的。你在代码中忘记了这一点。PdfDocument

您确实关闭了已构建的。关闭 时,它可能需要访问其 .因此,您必须在关闭 之前关闭 。PdfReaderPdfDocumentPdfDocumentPdfReaderPdfDocumentPdfReader