1. 程式人生 > >PDF文件解析:PDFBox和iText例項

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