【问题标题】:Itextsharp creates a corrupted pdf after stamping some textItextsharp 在标记一些文本后创建损坏的 pdf
【发布时间】:2016-10-26 15:33:24
【问题描述】:

只需将一些文本标记为 pdf,itextsharp 就会创建一个损坏的文件。当试图阅读 pdf 时,它会抛出如下错误

“iTextSharp.text.exceptions.InvalidPdfException”类型的异常 附加信息:文档没有页面根(意思是:它是无效的 PDF)。

以下代码用于编辑pdf并标记文本内容

using (PdfReader pdfReader = new PdfReader(System.IO.File.ReadAllBytes(pdfPath)))
           using (Stream pdfStream = new FileStream(pdfPath, FileMode.Open, FileAccess.ReadWrite))
           {
               PdfReaderContentParser parserReason = new PdfReaderContentParser(pdfReader);
               PdfStamper pdfStamper = new PdfStamper(pdfReader, pdfStream);
               PdfContentByte pdfContentByte = pdfStamper.GetOverContent(pdfReader.NumberOfPages);
               BaseFont baseFont = BaseFont.CreateFont(BaseFont.COURIER_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
               pdfContentByte.SetColorFill(BaseColor.BLACK);
               pdfContentByte.SetFontAndSize(baseFont, 12);
               pdfContentByte.BeginText();
               TextMarginFinder finderReason = parserReason.ProcessContent(pdfReader.NumberOfPages, new iTextSharp.text.pdf.parser.TextMarginFinder());
               pdfContentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Some text  : " + annotation, finderReason.GetLlx(), finderReason.GetLly() - 20f, 0);
               pdfContentByte.EndText();
               pdfStamper.Close();

           }

pdf 文件是使用 apache fop 1.1 创建的,并且 itextsharp 用于编辑文件。问题并非发生在所有 pdf 中,而仅发生在某些文件中。 You can find the PDF which creates the issue here

【问题讨论】:

  • 发布有问题的 PDF 也可能有助于检查它是否有/没有页面根目录。
  • 感谢@confusedandamused。我已经上传了一个文件并使用链接更新了我的问题。

标签: c# pdf itext


【解决方案1】:

问题是您正在像这样打开文件流:

using (Stream pdfStream = new FileStream(pdfPath, FileMode.Open, FileAccess.ReadWrite))

FileMode.Open 保留旧内容,写入它只会覆盖它。特别是,如果新文档比原始文档短,则保留原始文档的旧尾部。由于 PDF 交叉引用在其末尾,这导致旧的交叉引用被应用到新文档。这显然不匹配。

如果您改用FileMode.Create,则不会发生此问题。


顺便说一句,您提供的示例文件的代码完全失败,因为该示例文件在最后一页上没有文本。因此,finderReason 确定没有边距矩形,您对finderReason.GetLlx() 的访问尝试访问null 矩形成员,因此它失败了。您应该添加一些适当的检查。

【讨论】:

  • 所以这意味着我需要创建一个新文档,复制第一个文档,然后正确书写/标记文本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-12
  • 2016-01-25
  • 2016-10-02
  • 2011-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多