我在vb.net上使用itextsharp从pdf文件中获取文本内容。该解决方案适用于某些文件,但不适用于其他文件,甚至不适用于非常简单的文件。问题是令牌字符串值被设置为null (一组空的方框)
token = New iTextSharp.text.pdf.PRTokeniser(pageBytes)
While token.NextToken()
tknType = token.TokenType()
tknValue = token.StringValue
我可以测量内容的长度,但我无法获得实际的字符串内容。
我意识到这种情况的发生取决于pdf的字体。如果我使用Acrobat或PdfCreator with Courier创建pdf (顺便说一句,这是我的visual studio编辑器中的默认字体),我可以获得所有文本内容。如果相同的pdf是使用不同的字体构建的,我得到的是空的方框。
现在的问题是,无论字体设置如何,我如何提取文本?
谢谢
发布于 2011-04-13 16:04:04
作为对Mark的回答的补充,这对我有很大帮助,.iTextSharp实现的命名空间和类与java版本略有不同
public static string GetTextFromAllPages(String pdfPath)
{
PdfReader reader = new PdfReader(pdfPath);
StringWriter output = new StringWriter();
for (int i = 1; i <= reader.NumberOfPages; i++)
output.WriteLine(PdfTextExtractor.GetTextFromPage(reader, i, new SimpleTextExtractionStrategy()));
return output.ToString();
}
发布于 2011-02-04 08:15:03
String pageText =
PdfTextExtractor.getTextFromPage(myReader, pageNum);
或
String pageText =
PdfTextExtractor.getTextFromPage(myReader, pageNum, new LocationTextExtractionStrategy());
两者都需要相当新版本的iTextSharp。实际上,在这一点上,自己解析内容流只是重新发明轮子。让你自己省去一些痛苦,让iText为你做吧。
PdfTextExtractor将为您处理所有不同的字体/编码问题...所有那些无论如何都可以处理的问题。如果您不能从Reader中准确地复制/粘贴,那么PDF中就没有足够的信息从内容流中获取字符信息。
发布于 2012-04-26 04:08:54
如果有人需要的话,这里有一个包含iTextSharp.text.pdf.PdfName.ANNOTS和iTextSharp.text.pdf.PdfName.CONTENT的变体。
string strFile = @"C:\my\path\tothefile.pdf";
iTextSharp.text.pdf.PdfReader pdfRida = new iTextSharp.text.pdf.PdfReader(strFile);
iTextSharp.text.pdf.PRTokeniser prtTokeneiser;
int pageFrom = 1;
int pageTo = pdfRida.NumberOfPages;
iTextSharp.text.pdf.PRTokeniser.TokType tkntype ;
string tknValue;
for (int i = pageFrom; i <= pageTo; i++)
{
iTextSharp.text.pdf.PdfDictionary cpage = pdfRida.GetPageN(i);
iTextSharp.text.pdf.PdfArray cannots = cpage.GetAsArray(iTextSharp.text.pdf.PdfName.ANNOTS);
if(cannots!=null)
foreach (iTextSharp.text.pdf.PdfObject oAnnot in cannots.ArrayList)
{
iTextSharp.text.pdf.PdfDictionary cAnnotationDictironary = (iTextSharp.text.pdf.PdfDictionary)pdfRida.GetPdfObject(((iTextSharp.text.pdf.PRIndirectReference)oAnnot).Number);
iTextSharp.text.pdf.PdfObject moreshit = cAnnotationDictironary.Get(iTextSharp.text.pdf.PdfName.CONTENTS);
if (moreshit != null && moreshit.GetType() == typeof(iTextSharp.text.pdf.PdfString))
{
string cStringVal = ((iTextSharp.text.pdf.PdfString)moreshit).ToString();
if (cStringVal.ToUpper().Contains("LOS 8"))
{ // DO SOMETHING FUN
}
}
}
}
pdfRida.Close();
https://stackoverflow.com/questions/4711134
复制相似问题