【问题标题】:PdfTextExtractor.GetTextFromPage is not returning correct textPdfTextExtractor.GetTextFromPage 没有返回正确的文本
【发布时间】:2014-10-28 23:43:09
【问题描述】:

使用 iTextSharp,我有以下代码,它成功地提取了我正在尝试阅读的大多数 PDF 的 PDF 文本...

PdfReader reader = new PdfReader(fileName);
for (int i = 1; i <= reader.NumberOfPages; i++)
{
    text += PdfTextExtractor.GetTextFromPage(reader, i);
}
reader.Close();

但是,我的一些 PDF 具有 XFA 表单(已填写),这会导致“文本”字段被以下垃圾填充...

"Please wait... \n  \nIf this message is not eventually replaced by the proper contents of the document, your PDF \nviewer may not be able to display this type of document. \n  \nYou can upgrade to the latest version of Adobe Reader for Windows®, Mac, or Linux® by \nvisiting  http://www.adobe.com/products/acrobat/readstep2.html. \n  \nFor more assistance with Adobe Reader visit  http://www.adobe.com/support/products/\nacrreader.html. \n  \nWindows is either a registered trademark or a trademark of Microsoft Corporation in the United States and/or other countries. Mac is a trademark \nof Apple Inc., registered in the United States and other countries. Linux is the registered trademark of Linus Torvalds in the U.S. and other \ncountries."

我该如何解决这个问题?我尝试使用 iTextSharp 中的 PdfStamper[1] 来展平 PDF,但这不起作用 - 生成的流具有相同的垃圾文本。

[1]How to flatten already filled out PDF form using iTextSharp

【问题讨论】:

    标签: pdf itextsharp


    【解决方案1】:

    您遇到了一个充当 XML 流容器的 PDF。此 XML 流基于 XML 表单体系结构 (XFA)。您看到的消息不是垃圾!它是包含在 PDF 页面中的消息,当在查看器中打开文档时会显示该消息,就像读取普通 PDF 文件一样。

    例如:如果您在 Apple Preview 中打开文档,您将看到完全相同的消息,因为 Apple Preview 无法呈现 XFA 表单。在使用 iText 解析文件中包含的 PDF 时收到此消息,您应该不会感到惊讶。这正是您文件中存在的 PDF 内容。您在 Adob​​e Reader 中打开文档时看到的内容不是以 PDF 语法存储的,而是以 XML 流的形式存储的。

    您说您已尝试按照问题 How to flatten already filled out PDF form using iTextSharp 的答案中所述将 PDF 展平。 然而,这个问题是关于基于 AcroForm 技术展平表单。它不应该与 XFA 表单一起使用。如果要展平 XFA 表单,则需要在 iText 之上使用XFA Worker

    [JAVA]

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
    XFAFlattener xfaf = new XFAFlattener(document, writer);
    xfaf.flatten(new PdfReader(baos.toByteArray()));
    document.close();
    

    [C#]

    Document document = new Document();
    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(dest, FileMode.Create));
    XFAFlattener xfaf = new XFAFlattener(document, writer);
    ms.Position = 0;
    xfaf.Flatten(new PdfReader(ms));
    document.Close();
    

    这个拼合过程的结果是一个普通的 PDF,可以由您的原始代码解析。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多