我正在尝试为我们的PDF生成例程编写验证代码,并且我很难从pdfsharp中提取从使用Migradoc创建的文件中提取文本。Extracttext代码可与其他PDF一起使用,但与我使用Migradoc生成的PDF(请参阅下面的代码(
。关于我做错了什么的任何技巧?
//Create the Doc
var doc = new MigraDoc.DocumentObjectModel.Document();
doc.Info.Title = "VerifyReadWrite";
var section = doc.AddSection();
section.AddParagraph("ABCDEF abcdef");
//Render the PDF
var renderer = new PdfDocumentRenderer(true);
var pdf = new PdfDocument();
renderer.PdfDocument = pdf;
renderer.Document = doc;
renderer.RenderDocument();
var msOut = new MemoryStream();
pdf.Save(msOut, true);
var pdfBytes = msOut.ToArray();
//Read the PDF into PdfSharp
var ms = new MemoryStream(pdfBytes);
var pdfRead = PdfSharp.Pdf.IO.PdfReader.Open(ms, PdfDocumentOpenMode.ReadOnly);
var segments = pdfRead.Pages[0].ExtractText().ToList();
导致以下结果:
段[0] =" 0 $ 0% 0& 0' 0( 0("
段[1] =" 0d 0e 0f 0g 0g 0H 0i"
我希望看到:
段[0] =" abcdef"
段[1] =" abcdef"
我正在此处使用ExtractText代码:C#使用PDFSHARP
从PDF提取文本,除了使用Migradoc生成的PDF以外,它都非常有效。
public static IEnumerable<string> ExtractText(this PdfPage page)
{
var content = ContentReader.ReadContent(page);
var text = content.ExtractText();
return text.Select(x => x.Trim());
}
public static IEnumerable<string> ExtractText(this CObject cObject)
{
if (cObject is COperator)
{
var cOperator = (COperator) cObject;
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
{
var sequence = cObject as CSequence;
if (sequence != null)
{
var cSequence = sequence;
foreach (var element in cSequence)
foreach (var txt in ExtractText(element))
yield return txt;
}
else if (cObject is CString)
{
var cString = (CString) cObject;
yield return cString.Value;
}
}
}
看来用于提取文本的代码不支持所有情况。
尝试new PdfDocumentRenderer(false)
(而不是'true'(。afaik这将导致不同的编码,并且文本提取可能起作用。