PDFBOX詳解
摘要
自從Adobe公司1993年第一次發布公共PDF參考以來,支持各種語言和平台的PDF工具和類庫就如雨后春筍般涌現。然而,Java應用開發中Adobe技術的支持相對滯后了。
自從Adobe公司1993年第一次發布公共PDF參考以來,支持各種語言和平台的PDF工具和類庫就如雨后春筍般涌現。然而,Java應用開發中Adobe技術的支持相對滯后了。這是個奇怪的現象,因為PDF文檔是企業信息系統存儲和交換信息的大勢所趨,而Java技術特別適合這種應用。然而,Java開發人員似乎直到最近才獲得成熟可用的PDF支持。
PDFBox(一個BSD許可下的源碼開放項目)是一個為開發人員讀取和創建PDF文檔而准備的純Java類庫。它提供如下特性:
- 提取文本,包括Unicode字符。
- 和Jakarta Lucene等文本搜索引擎的整合過程十分簡單。
- 加密/解密PDF文檔。
- 從PDF和XFDF格式中導入或導出表單數據。
- 向已有PDF文檔中追加內容。
- 將一個PDF文檔切分為多個文檔。
- 覆蓋PDF文檔。
PDFBox API
PDFBox設計時采用面向對象的方式來描述PDF文檔。PDF文檔的數據是一系列基本對象的集合:數組,布爾型,字典,數字,字符串和二進制流。PDFBox在org.pdfbox.cos包(COS模型)中定義這些基本對象類型。你可以使用這些對象與PDF文檔進行任何交互,但你應該先對PDF文檔內部結構以及高層概念作一些深入的了解。例如,頁面和字體都是帶有特殊屬性的字典對象;PDF參考手冊提供這些特殊屬性的含義和類型的說明,但這是一個枯燥的文檔查閱過程。
於是,org.pdfbox.pdfmodel包(PD模型)應運而生,它的基礎是COS模型,但提供了以一種熟悉的方式訪問PDF文檔對象的高層API(如圖1)。對底層COS模型進行了封裝的PDPage和PDFont等類就在這個包中。
注意,雖然PD模型提供了一些優秀的功能,但它依然是一個開發中的模型。在有些實例中,你可能需要借助於COS模型才能訪問PDF的特定功能性。所有的PD模型對象都提供返回相應的COS模型對象的方法。所以,在一般情況下,你都會使用PD模型,但PD模型鞭長莫及時你可以直接操作底層的COS模型。
上文對PDFBox作了大體上的介紹,現在是舉一些例子的時候了。我們從如何讀已存在的PDF文檔開始:
PDDocument document = PDDocument.load( "./test.pdf" );
上面的語句解析指定的PDF文件並在內存中創建其文檔對象。考慮到處理大文檔時的效率問題,PDFBox只在內存中存儲文檔結構,圖像、內嵌字體和頁面內容等對象將被緩存在一個臨時文件中。
注意:PDDocument對象使用完畢時需要調用其close()方法來釋放創建時使用的資源。
文本提取和Lucene整合
這是一個信息展現時代(an information retrieval age),不管信息存放在哪種媒體中,應用程序都應該支持檢索和索引。對信息進行組織和分類從而形成可檢索的格式是很關鍵的。這對於文本文檔和HTML文檔來說是很簡單的,但PDF文檔包含大量的結構和元信息,提取文檔內容決不是一件簡單的事情。PDF語言和Postscript相似,二者中的對象都是作為矢量繪制在頁面的某些位置。例如:
- /Helv 12 Tf
- 0 13.0847 Td
- (Hello World) Tj
上面的指令將字體設為12號的Helvetica,移到下一行然后打印“Hello World”。這些命令流通常是經過壓縮的,文字在屏幕上的顯示順序並不一定是文件中的字符出現順序。因此,你有時無法直接從原始PDF文檔中提取字符串。然而,PDFBox成熟的文本提取算法使得開發人員可以提取文檔內容,就像在閱讀器中呈現的那樣。
Lucene是Apache Jakarta項目的子項目,它是一個流行的源代碼開放的搜索引擎庫。開發人員可以使用Lucene來創建索引,並基於該索引對大量的文本內容進行復雜的檢索。Lucene只支持文本內容的檢索,所以開發人員需要將其他形式的數據轉換為文本形式才能使用Lucene。例如,Microsoft Word和StarOffice文檔都必須先轉換為文本形式才能添加到Lucene索引中。
PDF文件也不例外,但PDFBox提供一個特殊的整合對象,這讓在Lucene索引中包含PDF文檔變得非常容易。將一個基本PDF文檔轉換為Lucene文檔只需要一條語句:
Document doc = LucenePDFDocument.getDocument( file );
這條語句解析指定的PDF文檔,提取其內容並創建一個Lucene文檔對象。然后你就可以將該對象添加到Lucene索引中了。如上文所述,PDF文檔中也包含作者信息和關鍵詞等元數據,在索引PDF文檔時對這些元數據進行跟蹤時很重要的。表1列出了創建Lucene文檔時PDFBox將填寫(populate)的字段。
這種整合使得開發人員可以輕松地使用Lucene來支持PDF文檔的檢索和索引。當然,有些應用程序要求更成熟的文本提取方法。此時可以直接使用PDFTextStripper類,或繼承該類來滿足這種復雜的需求。
通過繼承PDFTextStripper並覆蓋showCharacter()方法,你可以從許多方面對文本提取進行控制。例如,使用x、y位置信息進行限制以提取特定文本塊。你可以有效地忽略所有的y坐標大於某個值的文本,這樣文檔頭部內容就會被排除。
另一個例子。常常有這種情況:從表單創建了一組PDF文檔,但這些原始數據被丟失了。也就是說,這些文檔都包含一些你感興趣的文本,而且這些文本都在相似的位置上,但填充文檔的表單數據丟失了。例如,你有一些信封,在相同的位置上都有名字和地址信息。這時,你就可以使用PDFTextStripper的派生類來提取期望的字段,這個類就像一種截取屏幕區域的設備。
加密/解密
PDF的一個流行特性是允許對文檔內容進行加密、對訪問進行控制,限制只能閱讀未加密文檔。PDF文檔加密時采用一個主密碼和一個可選的用戶密碼。如果設定了用戶密碼,那么PDF閱讀器(如Acrobat)將在顯示文檔之前提示輸入密碼。而主密碼則用於授權修改文檔內容。
PDF規范允許PDF文檔的創建者對用戶使用Acrobat閱讀器查看文檔時的某些操作進行限制。這些限制包括:
- 打印
- 修改內容
- 提取內容
PDF文檔安全的討論不在本文范疇之內,有興趣的讀者可以參考PDF規范的相關部分。PDF文檔的安全模型是可插拔式的(pluggable),你可以在加密文檔時使用不同的安全處理器(security handler)。對本文而言,PDFBox支持標准的安全處理器,它是大多數PDF文檔所使用的。
加密文檔時必須先指定一個安全處理器,然后使用一個主密碼和用戶密碼進行加密。在下面的代碼中,文檔被加密,用戶不需要敲入就可以在Acrobat中打開它(沒有設置用戶密碼),但是該文檔不可被打印。
//load the document PDDocument pdf = PDDocument.load( "test.pdf"); //create the encryption options PDStandardEncryption encryptionOptions = new PDStandardEncryption(); encryptionOptions.setCanPrint( false); pdf.setEncryptionDictionary( encryptionOptions ); //encrypt the document pdf.encrypt( "master", null); //save the encrypted document //to the file system pdf.save( "test-output.pdf");
更詳細的示例參見PDFBox發布版中包含的加密工具類源代碼:org.pdfbox.Encrypt。
許多應用程序可以生成PDF文檔,但不支持控制文檔的安全選項。這時PDFBox就可以用來在發送給用戶之前截獲並加密PDF文檔。
表單整合
當應用程序的輸出是一系列表單域的值時,提供將表單保存成文件的功能是很必要的。這時PDF技術將是一個很好的選擇。開發人員可以手動編寫PDF指令來繪制圖形、表格和文本。或者將數據存成XML形式並使用XSL-FO模版來創建PDF文檔。然而,這些辦法都是比較耗時,容易出錯,而且靈活性也比較差。對於簡單的表單而言,一個更好的辦法是創建模版,然后將給定的輸入數據填入該模版,從而生成文檔。
Employment Eligibility Verification是一個大多數人都熟悉的表單,它又叫做“I-9表單”,參見:http://uscis.gov/graphics/formsfee/forms/files/i-9.pdf
你可以使用PDFBox發布版中的一個示例程序列出表單域名單:
- java org.pdfbox.examples.fdf.PrintFields i-9.pdf
還有一個示例程序用於向指定的域中插入文本形式的數據:
- java org.pdfbox.examples.fdf.SetField i-9.pdf NAME1 Smith
在Acrobat中打開這個PDF文檔你就會看到"Last Name"域已被填寫了。你也可以使用以下代碼來完成相同的操作:
PDDocument pdf = PDDocument.load( "i-9.pdf"); PDDocumentCatalog docCatalog = pdf.getDocumentCatalog(); PDAcroForm acroForm = docCatalog.getAcroForm(); PDField field = acroForm.getField( "NAME1"); field.setValue( "Smith"); pdf.save( "i-9-copy.pdf" );
下面的代碼可用於提取剛才填寫的表單域的值:
PDField field = acroForm.getField( "NAME1"); System .out.println( "First Name=" field.getValue() );
Acrobat支持將表單數據導入或導出到一個特定的文件格式“表單數據格式”(Forms Data Format)。這種文件有兩類:FDF和XFDF。FDF文件存放表單數據的格式與PDF相同,而XFDF則以XML格式存放表單數據。PDFBox在一個類中處理FDF和XFDF:FDFDocument。下面的代碼片斷演示了如何從上面的I-9表單導出FDF數據:
PDDocument pdf = PDDocument.load( "i-9.pdf"); PDDocumentCatalog docCatalog = pdf.getDocumentCatalog(); PDAcroForm acroForm = docCatalog.getAcroForm(); FDFDocument fdf = acroForm.exportFDF(); fdf.save( "exportedData.fdf" );
PDFBox表單整合步驟:
- 使用Acrobat或其他可視化工具創建PDF表單模版
- 記下每個需要的(desirable)表單域的名稱
- 將模版存放在應用程序可以訪問到的地方
- 當PDF被請求時,使用PDFBox解析PDF模版
- 填充指定的表單域
- 將填充結果(PDF)返回給用戶
demo
1、創建PDF文件
1 public void createHelloPDF() {
2 PDDocument doc = null;
3 PDPage page = null;
4
5 try {
6 doc = new PDDocument();
7 page = new PDPage();
8 doc.addPage(page);
9 PDFont font = PDType1Font.HELVETICA_BOLD;
10 PDPageContentStream content = new PDPageContentStream(doc, page);
11 content.beginText();
12 content.setFont(font, 12);
13 content.moveTextPositionByAmount(100, 700);
14 content.drawString("hello");
15
16 content.endText();
17 content.close();
18 doc.save("F:\\java56班\\eclipse-SDK-4.2-win32\\pdfwithText.pdf");
19 doc.close();
20 } catch (Exception e) {
21 System.out.println(e);
22 }
23 }
2、讀取PDF文件:
1 public void readPDF() {
2 PDDocument helloDocument = null;
3 try {
4 helloDocument = PDDocument.load(new File(
5 "F:\\java56班\\eclipse-SDK-4.2-win32\\pdfwithText.pdf"));
6 PDFTextStripper textStripper = new PDFTextStripper("GBK");
7 System.out.println(textStripper.getText(helloDocument));
8
9 helloDocument.close();
10 } catch (IOException e) {
11 // TODO Auto-generated catch block
12 e.printStackTrace();
13 }
14 }
3、修改PDF文件(處理中文亂碼,我可以搞定的):
1 /**
2 * Locate a string in a PDF and replace it with a new string.
3 *
4 * @param inputFile The PDF to open.
5 * @param outputFile The PDF to write to.
6 * @param strToFind The string to find in the PDF document.
7 * @param message The message to write in the file.
8 *
9 * @throws IOException If there is an error writing the data.
10 * @throws COSVisitorException If there is an error writing the PDF.
11 */
12 public void doIt( String inputFile, String outputFile, String strToFind, String message)
13 throws IOException, COSVisitorException
14 {
15 // the document
16 PDDocument doc = null;
17 try
18 {
19 doc = PDDocument.load( inputFile );
20 // PDFTextStripper stripper=new PDFTextStripper("ISO-8859-1");
21 List pages = doc.getDocumentCatalog().getAllPages();
22 for( int i=0; i<pages.size(); i++ )
23 {
24 PDPage page = (PDPage)pages.get( i );
25 PDStream contents = page.getContents();
26 PDFStreamParser parser = new PDFStreamParser(contents.getStream() );
27 parser.parse();
28 List tokens = parser.getTokens();
29 for( int j=0; j<tokens.size(); j++ )
30 {
31 Object next = tokens.get( j );
32 if( next instanceof PDFOperator )
33 {
34 PDFOperator op = (PDFOperator)next;
35 //Tj and TJ are the two operators that display
36 //strings in a PDF
37 if( op.getOperation().equals( "Tj" ) )
38 {
39 //Tj takes one operator and that is the string
40 //to display so lets update that operator
41 COSString previous = (COSString)tokens.get( j-1 );
42 String string = previous.getString();
43 string = string.replaceFirst( strToFind, message );
44 System.out.println(string);
45 System.out.println(string.getBytes("GBK"));
46 previous.reset();
47 previous.append( string.getBytes("GBK") );
48 }
49 else if( op.getOperation().equals( "TJ" ) )
50 {
51 COSArray previous = (COSArray)tokens.get( j-1 );
52 for( int k=0; k<previous.size(); k++ )
53 {
54 Object arrElement = previous.getObject( k );
55 if( arrElement instanceof COSString )
56 {
57 COSString cosString = (COSString)arrElement;
58 String string = cosString.getString();
59 string = string.replaceFirst( strToFind, message );
60 cosString.reset();
61 cosString.append( string.getBytes("GBK") );
62 }
63 }
64 }
65 }
66 }
67 //now that the tokens are updated we will replace the
68 //page content stream.
69 PDStream updatedStream = new PDStream(doc);
70 OutputStream out = updatedStream.createOutputStream();
71 ContentStreamWriter tokenWriter = new ContentStreamWriter(out);
72 tokenWriter.writeTokens( tokens );
73 page.setContents( updatedStream );
74 }
75 doc.save( outputFile );
76 }
77 finally
78 {
79 if( doc != null )
80 {
81 doc.close();
82 }
83 }
84 }
4、在PDF中加入圖片:
1 /**
2 * Add an image to an existing PDF document.
3 *
4 * @param inputFile The input PDF to add the image to.
5 * @param image The filename of the image to put in the PDF.
6 * @param outputFile The file to write to the pdf to.
7 *
8 * @throws IOException If there is an error writing the data.
9 * @throws COSVisitorException If there is an error writing the PDF.
10 */
11 public void createPDFFromImage( String inputFile, String image, String outputFile )
12 throws IOException, COSVisitorException
13 {
14 // the document
15 PDDocument doc = null;
16 try
17 {
18 doc = PDDocument.load( inputFile );
19
20 //we will add the image to the first page.
21 PDPage page = (PDPage)doc.getDocumentCatalog().getAllPages().get( 0 );
22
23 PDXObjectImage ximage = null;
24 if( image.toLowerCase().endsWith( ".jpg" ) )
25 {
26 ximage = new PDJpeg(doc, new FileInputStream( image ) );
27 }
28 else if (image.toLowerCase().endsWith(".tif") || image.toLowerCase().endsWith(".tiff"))
29 {
30 ximage = new PDCcitt(doc, new RandomAccessFile(new File(image),"r"));
31 }
32 else
33 {
34 BufferedImage awtImage = ImageIO.read( new File( image ) );
35 ximage = new PDPixelMap(doc, awtImage);
36 }
37 PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);
38
39 //contentStream.drawImage(ximage, 20, 20 );
40 // better method inspired by http://stackoverflow.com/a/22318681/535646
41 float scale = 0.5f; // reduce this value if the image is too large
42 System.out.println(ximage.getHeight());
43 System.out.println(ximage.getWidth());
44 // ximage.setHeight(ximage.getHeight()/5);
45 // ximage.setWidth(ximage.getWidth()/5);
46 contentStream.drawXObject(ximage, 20, 200, ximage.getWidth()*scale, ximage.getHeight()*scale);
47
48 contentStream.close();
49 doc.save( outputFile );
50 }
51 finally
52 {
53 if( doc != null )
54 {
55 doc.close();
56 }
57 }
58 }
5、PDF文件轉換為圖片:
1 public void toImage() {
2 try {
3 PDDocument doc = PDDocument
4 .load("F:\\java56班\\eclipse-SDK-4.2-win32\\pdfwithText.pdf");
5 int pageCount = doc.getPageCount();
6 System.out.println(pageCount);
7 List pages = doc.getDocumentCatalog().getAllPages();
8 for (int i = 0; i < pages.size(); i++) {
9 PDPage page = (PDPage) pages.get(i);
10 BufferedImage image = page.convertToImage();
11 Iterator iter = ImageIO.getImageWritersBySuffix("jpg");
12 ImageWriter writer = (ImageWriter) iter.next();
13 File outFile = new File("F:\\java56班\\eclipse-SDK-4.2-win32\\"
14 + i + ".jpg");
15 FileOutputStream out = new FileOutputStream(outFile);
16 ImageOutputStream outImage = ImageIO
17 .createImageOutputStream(out);
18 writer.setOutput(outImage);
19 writer.write(new IIOImage(image, null, null));
20 }
21 doc.close();
22 System.out.println("over");
23 } catch (FileNotFoundException e) {
24 // TODO Auto-generated catch block
25 e.printStackTrace();
26 } catch (IOException e) {
27 // TODO Auto-generated catch block
28 e.printStackTrace();
29 }
30 }
6、圖片轉換為PDF文件(支持多張圖片轉換為PDF文件):
1 /**
2 * create the second sample document from the PDF file format specification.
3 *
4 * @param file
5 * The file to write the PDF to.
6 * @param image
7 * The filename of the image to put in the PDF.
8 *
9 * @throws IOException
10 * If there is an error writing the data.
11 * @throws COSVisitorException
12 * If there is an error writing the PDF.
13 */
14 public void createPDFFromImage(String file, String image)throws IOException, COSVisitorException {
15 // 多張圖片轉換為PDF文件
16 PDDocument doc = null;
17 doc = new PDDocument();
18 PDPage page = null;
19 PDXObjectImage ximage = null;
20 PDPageContentStream contentStream = null;
21
22 File files = new File(image);
23 String[] a = files.list();
24 for (String string : a) {
25 if (string.toLowerCase().endsWith(".jpg")) {
26 String temp = image + "\\" + string;
27 ximage = new PDJpeg(doc, new FileInputStream(temp));
28 page = new PDPage();
29 doc.addPage(page);
30 contentStream = new PDPageContentStream(doc, page);
31 float scale = 0.5f;
32 contentStream.drawXObject(ximage, 20, 400, ximage.getWidth()
33 * scale, ximage.getHeight() * scale);
34
35 PDFont font = PDType1Font.HELVETICA_BOLD;
36 contentStream.beginText();
37 contentStream.setFont(font, 12);
38 contentStream.moveTextPositionByAmount(100, 700);
39 contentStream.drawString("Hello");
40 contentStream.endText();
41
42 contentStream.close();
43 }
44 }
45 doc.save(file);
46 doc.close();
47 }
7、替換PDF文件中的某個字符串:
1 /**
2 * Locate a string in a PDF and replace it with a new string.
3 *
4 * @param inputFile The PDF to open.
5 * @param outputFile The PDF to write to.
6 * @param strToFind The string to find in the PDF document.
7 * @param message The message to write in the file.
8 *
9 * @throws IOException If there is an error writing the data.
10 * @throws COSVisitorException If there is an error writing the PDF.
11 */
12 public void doIt( String inputFile, String outputFile, String strToFind, String message)
13 throws IOException, COSVisitorException
14 {
15 // the document
16 PDDocument doc = null;
17 try
18 {
19 doc = PDDocument.load( inputFile );
20 // PDFTextStripper stripper=new PDFTextStripper("ISO-8859-1");
21 List pages = doc.getDocumentCatalog().getAllPages();
22 for( int i=0; i<pages.size(); i++ )
23 {
24 PDPage page = (PDPage)pages.get( i );
25 PDStream contents = page.getContents();
26 PDFStreamParser parser = new PDFStreamParser(contents.getStream() );
27 parser.parse();
28 List tokens = parser.getTokens();
29 for( int j=0; j<tokens.size(); j++ )
30 {
31 Object next = tokens.get( j );
32 if( next instanceof PDFOperator )
33 {
34 PDFOperator op = (PDFOperator)next;
35 //Tj and TJ are the two operators that display
36 //strings in a PDF
37 if( op.getOperation().equals( "Tj" ) )
38 {
39 //Tj takes one operator and that is the string
40 //to display so lets update that operator
41 COSString previous = (COSString)tokens.get( j-1 );
42 String string = previous.getString();
43 string = string.replaceFirst( strToFind, message );
44 System.out.println(string);
45 System.out.println(string.getBytes("GBK"));
46 previous.reset();
47 previous.append( string.getBytes("GBK") );
48 }
49 else if( op.getOperation().equals( "TJ" ) )
50 {
51 COSArray previous = (COSArray)tokens.get( j-1 );
52 for( int k=0; k<previous.size(); k++ )
53 {
54 Object arrElement = previous.getObject( k );
55 if( arrElement instanceof COSString )
56 {
57 COSString cosString = (COSString)arrElement;
58 String string = cosString.getString();
59 string = string.replaceFirst( strToFind, message );
60 cosString.reset();
61 cosString.append( string.getBytes("GBK") );
62 }
63 }
64 }
65 }
66 }
67 //now that the tokens are updated we will replace the
68 //page content stream.
69 PDStream updatedStream = new PDStream(doc);
70 OutputStream out = updatedStream.createOutputStream();
71 ContentStreamWriter tokenWriter = new ContentStreamWriter(out);
72 tokenWriter.writeTokens( tokens );
73 page.setContents( updatedStream );
74 }
75 doc.save( outputFile );
76 }
77 finally
78 {
79 if( doc != null )
80 {
81 doc.close();
82 }
83 }
84 }
工具
除了上文介紹的API之外,PDFBox還提供一系列命令行工具。表2列出了這些工具類並作簡短介紹。
備注
PDF規范共有1172頁之多,其實現的確是一浩大工程。同樣,PDFBox發布版中說它“正在進行中”,新的功能會慢慢地添加上去。它的主要弱點是從零開始創建PDF文檔。然而,有一些源碼開放的Java項目可用於填補這個缺口。例如,Apache FOP項目支持從特殊的XML文檔生成PDF,這個XML文檔描述了要生成的PDF文檔。此外,iText提供一個高層API用於創建表格和列表。
PDFBox的下一個版本將支持新的PDF 1.5 對象流和交叉引用流。然后將提供內嵌字體和圖像的支持。在PDFBox的努力下,Java應用程序中的PDF技術有望得到充分的支持。
參考資源
PDFBox: www.pdfbox.org Apache FOP: http://xml.apache.org/fop/ iText: www.lowagie.com/iText/ PDF Reference: http://partners.adobe.com/asn/tech/pdf/specifications.jsp Jakarta Lucene: http://jakarta.spache.org/lucene/
