C#使用PdfSharp从PDF中提取文本

时间:2012-04-13 12:48:57

标签: c# text text-extraction pdfsharp

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

3 个答案:

答案 0 :(得分:25)

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

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;
        }
    }
}

答案 1 :(得分:13)

我已经以类似于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;
    }

答案 2 :(得分:9)

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

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