转载请注明来源:http://blog.csdn.net/loongshawn/article/details/51542309
相关文章:
1、介绍
Apache PDFbox是一个开源的、基于Java的、支持PDF文档生成的工具库,它可以用于创建新的PDF文档,修改现有的PDF文档,还可以从PDF文档中提取所需的内容。Apache PDFBox还包含了数个命令行工具。
Apache PDFbox于2016年4月26日发布了最新的2.0.1版。
官网地址:https://pdfbox.apache.org/index.html
PDFBox 2.0.1 API在线文档:https://pdfbox.apache.org/docs/2.0.1/javadocs/
2、特征
Apache PDFBox主要有以下特征:
PDF读取、创建、打印、转换、验证、合并分割等特征。
3、开发实战
3.1、场景说明
读取PDF文本内容,样例中为读取体检报告文本内容。
3.2、所需jar包
pdfbox-2.0.1.jar下载地址
fontbox-2.0.1.jar下载地址
将上述两jar包添加到工程库中,如下:
3.3、代码编写
创建PdfReader类,编写下述功能函数。
package com.loongshaw;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.pdfbox.io.RandomAccessBuffer;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
public class PdfReader {
public static void main(String[] args){
File pdfFile = new File("/Users/dddd/Downloads/0571888890423433356rrrr_182-93201510313223336-2.pdf");
PDDocument document = null;
try
{
// 方式一:
/** InputStream input = null; input = new FileInputStream( pdfFile ); //加载 pdf 文档 PDFParser parser = new PDFParser(new RandomAccessBuffer(input)); parser.parse(); document = parser.getPDDocument(); **/
// 方式二:
document=PDDocument.load(pdfFile);
// 获取页码
int pages = document.getNumberOfPages();
// 读文本内容
PDFTextStripper stripper=new PDFTextStripper();
// 设置按顺序输出
stripper.setSortByPosition(true);
stripper.setStartPage(1);
stripper.setEndPage(pages);
String content = stripper.getText(document);
System.out.println(content);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
3.4、过程说明
PDF文件加载有两种方式,无明显差异,方式二代码较简洁:
// 方式一:
InputStream input = null;
input = new FileInputStream( pdfFile );
//加载 pdf 文档
PDFParser parser = new PDFParser(new RandomAccessBuffer(input));
parser.parse();
document = parser.getPDDocument();
// 方式二:
document=PDDocument.load(pdfFile);
3.5、执行结果
4、小结
本文仅介绍了利用Apache PDFbox相关开发包读取PDF文本,其他复杂功能暂未涉及,需要大家自己线下探索、尝试。