Aspose.Pdf如何快速从PDF文件中提取文本

作者:控件中国网   出处:控件中国网   2015-12-21 14:52:04   阅读:28

Aspose.Pdf是一款功能强大的PDF文档处理控件,可以用于Java和.NET下,使用控件提供的API可以对PDF文件进行各种操作,这篇文章主要介绍怎么利用Aspose.Pdf提供的API对PDF文档进行文本提取,控件提供了多种方法对PDF文件里的文本进行提取,一是通过控件提供的TextAbsorber类,还有一种是使用TextDevice类进行文本提取,当提取文本时可以是对整个PDF文件进行文本提取,也可以是对某页进行文本提取。
 
下面的代码详细阐述了该功能是如何实现的,值得注意的是文本提取功能只有正式版才可以实现,试用版提取出来的文本时空值。
 
1.使用TextDevice类进行PDF文本的提取
//open document
Document pdfDocument = new Document("input.pdf");
System.Text.StringBuilder builder = new System.Text.StringBuilder();
//string to hold extracted text
string extractedText="";
 
foreach (Page pdfPage in pdfDocument.Pages)
{
    using (MemoryStream textStream = new MemoryStream())
    {
        //create text device
        TextDevice textDevice = new TextDevice();
 
        //set text extraction options - set text extraction mode (Raw or Pure)
        TextExtractionOptions textExtOptions = new   
        TextExtractionOptions(TextExtractionOptions.TextFormattingMode.Pure);
        textDevice.ExtractionOptions = textExtOptions;
 
        //convert a particular page and save text to the stream
        textDevice.Process(pdfPage, textStream);
 
        //close memory stream
        textStream.Close();
 
        //get text from memory stream
        extractedText = Encoding.Unicode.GetString(textStream.ToArray());
    }
    builder.Append(extractedText);
}
// save the extracted text in text file
File.WriteAllText("c:/pdftest/input_Text_Extracted.txt", builder.ToString());
2.使用TextAbsorber类进行PDF文件的文本提取
//open document
Document pdfDocument = new Document("input.pdf");
//create TextAbsorber object to extract text
TextAbsorber textAbsorber = new TextAbsorber();
//accept the absorber for all the pages
pdfDocument.Pages.Accept(textAbsorber);
//get the extracted text
string extractedText = textAbsorber.Text;
// create a writer and open the file
TextWriter tw = new StreamWriter("extracted-text.txt");
// write a line of text to the file
tw.WriteLine(extractedText);
// close the stream
tw.Close();
 
在使用时注意PDF文件里是否包含有文本对象,如果是图片,那么只有提取出图片,再使用OCR功能进行文字的识别。
Copyright© 2006-2015 ComponentCN.com all rights reserved.重庆磐岩科技有限公司(控件中国网) 版权所有 渝ICP备12000264号 法律顾问:元炳律师事务所
客服软件
live chat