53

是否有可能使用 PdfSharp 从 PDF 文件中提取纯文本?由于它的许可证,我不想使用 iTextSharp。

4

3 回答 3

45

拿了塞尔吉奥的回答,做了一些扩展方法。我还将字符串的累积更改为迭代器。

public static class PdfSharpExtensions
{
    public static IEnumerable<string> ExtractText(this PdfPage page)
    {       
        var content = ContentReader.ReadContent(page);      
        var text = content.ExtractText();
        return text;
    }   

    public static IEnumerable<string> ExtractText(this CObject cObject)
    {   
        if (cObject is COperator)
        {
            var cOperator = cObject as COperator;
            if (cOperator.OpCode.Name== OpCodeName.Tj.ToString() ||
                cOperator.OpCode.Name == OpCodeName.TJ.ToString())
            {
                foreach (var cOperand in cOperator.Operands)
                    foreach (var txt in ExtractText(cOperand))
                        yield return txt;   
            }
        }
        else if (cObject is CSequence)
        {
            var cSequence = cObject as CSequence;
            foreach (var element in cSequence)
                foreach (var txt in ExtractText(element))
                    yield return txt;
        }
        else if (cObject is CString)
        {
            var cString = cObject as CString;
            yield return cString.Value;
        }
    }
}
于 2014-06-04T19:37:48.237 回答
21

我实现它的方式与 David 的做法类似。这是我的代码:

    {
        // ....
        var page = document.Pages[1];
        CObject content = ContentReader.ReadContent(page);
        var extractedText = ExtractText(content);
        // ...
    }

    private IEnumerable<string> ExtractText(CObject cObject )
    {
        var textList = new List<string>();
        if (cObject is COperator)
        {
            var cOperator = cObject as COperator;
            if (cOperator.OpCode.Name== OpCodeName.Tj.ToString() ||
                cOperator.OpCode.Name == OpCodeName.TJ.ToString())
            {
                foreach (var cOperand in cOperator.Operands)
                {
                    textList.AddRange(ExtractText(cOperand));
                }
            }
        }
        else if (cObject is CSequence)
        {
            var cSequence = cObject as CSequence;
            foreach (var element in cSequence)
            {
                textList.AddRange(ExtractText(element));
            }
        }
        else if (cObject is CString)
        {
            var cString = cObject as CString;
            textList.Add(cString.Value);
        }
        return textList;
    }
于 2014-05-15T01:02:08.460 回答
12

PDFSharp 提供了从 PDF 中提取文本的所有工具。使用ContentReader该类访问每个页面中的命令并从 TJ/Tj 运算符中提取字符串。

我已经将一个简单的实现上传到github

于 2013-08-01T08:36:28.873 回答