您的位置:首页 > 其它

PDF文件操作API之PDFBox<一> PDFBox入门

2009-12-23 01:40 525 查看
PDFBox是Java实现的PDF文档API库,提供PDF文档的一系列操作。例如创建、处理以及文档内容提取等功能,也包含了一些命令行实用工具。

主要有以下特性:

PDF格式的文本抽取
合并PDF文档
PDF文档的加密与解密
Lucene搜索引擎集成
填充表单数据
创建一个文本文件的PDF
创建PDF页面图象
打印PDF文档

PDFBox jar包下载

请到官方网站上下载(http://pdfbox.apache.org/download.html),目前的版本是0.8.



构建PDFBox项目工程



在com.nick.pdfbox package 下新建一个类PDFParse.

PDFParse.java

1 package com.nick.pdfbox;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.util.List;
8
9 import org.apache.pdfbox.exceptions.CryptographyException;
10 import org.apache.pdfbox.exceptions.InvalidPasswordException;
11 import org.apache.pdfbox.pdmodel.PDDocument;
12 import org.apache.pdfbox.util.PDFTextStripper;
13
14 public class PDFParse {
15
16 public static void main(String[] args) throws IOException{
17 String file = "D:/test/test.pdf";
18 PDFParse parse = new PDFParse();
19 parse.openPDFFile(file);
20 }
21
22 public void openPDFFile(String file) throws IOException{
23
24 InputStream is = null;
25 File f = new File(file);
26 is = new FileInputStream(f);
27 this.document = this.parseDocument(is);
28 List pages = this.document.getDocumentCatalog().getAllPages();
29 int pageSize = pages.size();
30 System.out.println("PDF Document Total page count:"+pageSize);
31 this.showPage(1, 1);
32
33 }
34
35 /**
36 * This will parse a document.
37 *
38 * @param input The input stream for the document.
39 *
40 * @return The document.
41 * @throws IOException
42 *
43 * @throws IOException If there is an error parsing the document.
44 */
45 public PDDocument parseDocument(InputStream input) throws IOException{
46 PDDocument document = PDDocument.load(input);
47 if (document.isEncrypted()){
48 try {
49 document.decrypt("");
50 } catch (CryptographyException e) {
51 // TODO Auto-generated catch block
52 e.printStackTrace();
53 } catch (InvalidPasswordException e) {
54 // TODO Auto-generated catch block
55 e.printStackTrace();
56 }
57 }
58 return document;
59 }
60
61
62 public void showPage(int start,int end) throws IOException{
63
64 PDFTextStripper stripper = new PDFTextStripper();
65 stripper.setStartPage(start);
66 stripper.setEndPage(end);
67 String context = stripper.getText(this.document);
68 System.out.println("Parse PDF Document Context: "+context);
69 }
70
71 private PDDocument document = null;
72 }
73

运行该程序,将pdf文档的内容的输出到控制台上。

test.pdf



输出信息



程序所用到的pdf文件

/Files/nick001/test.pdf
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: