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;
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