PDFBox(一个BSD许可下的源码开放项目)是一个为开发人员读取和创建PDF文档而准备的纯Java类库。
主要功能:
提取文本,包括Unicode字符
和Jakarta Lucene等文本搜索引擎的整合过程十分简单
加密/解密PDF文档
从PDF和XFDF格式中导入或导出表单数据
向已有PDF文档中追加内容
将一个PDF文档切分为多个文档
覆盖PDF文档
示例代码使用的jar
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.14</version>
</dependency>
1.读取PDF内容
PDDocument helloDocument = null;
try {
helloDocument = PDDocument.load(new File("XXX.pdf"));
PDFTextStripper textStripper = new PDFTextStripper();
System.out.println(textStripper.getText(helloDocument));
helloDocument.close();
} catch (IOException e) {
e.printStackTrace();
}
2.读取PDF内容,与位置
public class GetWordsAndPositionFromPDF extends PDFTextStripper{
//用来记录,PDF中读到的词
static List<String> words = new ArrayList<String>();
public GetWordsAndPositionFromPDF() throws IOException {
super();
}
/**
* 解析PDF文档
* 从PDF中读取文字以及文字的位置
*/
public static void main( String[] args ) throws IOException {
PDDocument document = null;
String fileName = "XXX.pdf"; // replace with your PDF file name
try {
document = PDDocument.load( new File(fileName) );
PDFTextStripper stripper = new GetWordsAndPositionFromPDF();
stripper.setSortByPosition( true );
stripper.setStartPage( 0 );
stripper.setEndPage( document.getNumberOfPages() );
Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream());
stripper.writeText(document, dummy);
// print words
for(String word:words){
System.out.println(word);
}
}
finally {
if( document != null ) {
document.close();
}
}
}
@Override
protected void writeString(String text) throws IOException{
String[] wordsInStream = text.split(getWordSeparator());
if(wordsInStream!=null){
for(String word :wordsInStream){
words.add(word);
}
}
}
@Override
protected void writeString(String text, List<TextPosition> textPositions) throws IOException{
//读到的词,以及位置
for (int i = 0; i < textPositions.size(); i++) {
String str = textPositions.get(i).getUnicode();
String x = "x=" + textPositions.get(i).getX();
String y = "y=" + textPositions.get(i).getY();
System.out.println(" textPositions.get(i) = " + str + " x="+x + " y="+y);
}
writeString(text);
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。