PDF文档解析:PDFBox和iText实例

PDFBox和IText是解析PDF文档最常用的两种java API。
1、 使用PDFBox时,需要添加:pdfbox-2.0.0.jar、fontbox-2.0.0.jar、commons-logging-1.2.jar;
2、 使用iText时,需要添加:itextpdf-5.5.9.jar;

话不多说,直接看具体代码。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;
import com.itextpdf.text.pdf.parser.TextExtractionStrategy;

public class PdfPaser {
	/**
	 * 使用IText API解析
	 * @param filePath 待解析pdf文档路径
	 * @return 解析得到的pdf文本字符串
	 * @throws Exception
	 */
	public String paserPDFFileByIText(String filePath) throws Exception {
		TextExtractionStrategy strategy = null;
		
		PdfReader reader = new PdfReader(filePath);
		PdfReaderContentParser parser = new PdfReaderContentParser(reader);
		StringBuffer buffer = new StringBuffer();
		
		for (int i = 1; i <= reader.getNumberOfPages(); i++) {
			strategy = parser.processContent(i, new SimpleTextExtractionStrategy());
			buffer.append(strategy.getResultantText());
		}

		return buffer.toString();
	}

	/**
	 * 使用PdfBox API解析
	 * @param filePath 待解析pdf文档路径
	 * @return 解析得到的pdf文本字符串
	 * @throws Exception
	 */
	public String paserPDFFileByPdfBox(String filePath) throws Exception {
		File file = new File(filePath);
		
		PDDocument document = PDDocument.load(file);
		PDFTextStripper stripper = new PDFTextStripper();
		String result = stripper.getText(document);
		
		if(document != null){
			document.close();
		}
		return result;
	}
}
附PDFBox和IText jar包下载地址:
http://download.csdn.net/detail/u013405574/9483775
http://download.csdn.net/detail/u013405574/9483780

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值