首页 > 解决方案 > 修复 iTextSharp 的错误(PDF 到文本)?

问题描述

我正在尝试通过以下方式使用 iTextSharp (NuGet) 从 PDF 文件中恢复文本:

this.Cursor = Cursors.WaitCursor;
string LOC_DOC = @"C:\PDF_files";

string[] PDFs = Directory.GetFiles(LOC_DOC, "*.pdf", SearchOption.AllDirectories);

    foreach (string PDF in PDFs)
    {

         PdfReader reader = new PdfReader(@PDF);
             
         for (int page = 1; page <= reader.NumberOfPages; page++)
         {
             string pageText = PdfTextExtractor.GetTextFromPage(reader, page);
         }

    }

 this.Cursor = Cursors.Default;

目标只是检索 PDF 的内容,稍后我将进行处理。它适用于某些 PDF,但对于其他 PDF,我有以下错误:

System.InvalidCastException:'Impossible d'effectuer un cast d'un object de type 'iTextSharp.text.pdf.PdfLiteral' en type 'iTextSharp.text.pdf.PdfNumber'。

System.InvalidCastException:'不可能将'iTextSharp.text.pdf.PdfLiteral'类型的对象转换为'iTextSharp.text.pdf.PdfNumber'。'

有人有想法吗?

标签: c#pdftextitextextract

解决方案


分析

您共享的 PDF 2-30-SL-manual-DE.pdf在第 6 页的内容流中存在错误,导致在这种情况下出现异常:

0.1 -16 TD -3.796 Tw
[ (.)2.943 Tw ( . . . . . . . . . . . . . . .)] TJ
-0.138 -16 TD -3.796 Tw
[ (.)2.943 Tw ( . . . . . . . . . . . . . . .)] TJ
0.112 -16 TD -3.45 Tw
[ (.)3.05 Tw ( . . . . . . . . . .)] TJ 

TJ指令的各个数组参数中的Tws无效,该数组只能包含字符串(在圆括号或尖括号中)和数字,参见规范:

array TJ 显示一个或多个文本字符串,允许单独的字形定位。数组的每个元素应为字符串或数字。如果元素是字符串,则此运算符应显示字符串。如果是数字,则操作员应将文本位置调整该数量。

(ISO 32000-1,表 109 – 文本显示操作符)

如果您的其他文档导致相同的异常(包括类似的堆栈跟踪),它们很可能在某些TJ指令中也包含此类无效的非字符串、非数字文字。

因此,请要求文件来源提供这些文件的固定副本。

解决方法

在您提到的评论中

然而这些都是旧文件,我不可能要求更正版本

如果在示例文件中发现的内容流错误类型是文件中唯一类型的内容错误,并且忽略额外的文字始终是处理错误的适当方法,则可以将iText 文本提取中的IContentOperator处理TJ指令包装在另一个从参数中过滤掉不需要的文字的运算符:

PdfReader reader = new PdfReader(@"d:\Issues\stackoverflow\Fix the error with iTextSharp (PDF to text)\2-30-SL-manual-DE.pdf");
for (int page = 1; page <= reader.NumberOfPages; page++)
{
    Console.Out.WriteLine("Page {0}", page);
    PdfDictionary pageDic = reader.GetPageN(page);
    PdfDictionary resourcesDic = pageDic.GetAsDict(PdfName.RESOURCES);
    ITextExtractionStrategy strategy = new LocationTextExtractionStrategy();
    PdfContentStreamProcessor processor = new PdfContentStreamProcessor(strategy);
    TjArgumentClearingWrapper wrapper = new TjArgumentClearingWrapper();
    wrapper.WrappedOperator = processor.RegisterContentOperator("TJ", wrapper);
    processor.ProcessContent(ContentByteUtils.GetContentBytesForPage(reader, page), resourcesDic);
    string pageText = strategy.GetResultantText();
    Console.Out.WriteLine("******\n{0}\n\n", pageText);
}

与助手类

class TjArgumentClearingWrapper : IContentOperator
{
    public void Invoke(PdfContentStreamProcessor processor, PdfLiteral oper, List<PdfObject> operands)
    {
        PdfObject operand = operands[0];
        if (operand is PdfArray array)
        {
            PdfArray newArray = new PdfArray();
            foreach (PdfObject pdfObject in array)
            {
                if (pdfObject is PdfString || pdfObject is PdfNumber)
                    newArray.Add(pdfObject);
            }
            operands[0] = newArray;
        }
        WrappedOperator.Invoke(processor, oper, operands);
    }

    public IContentOperator WrappedOperator { get; set; }
}


推荐阅读