PDFBOX详解
自从Adobe公司1993年第一次发布公共PDF参考以来,支持各种语言和平台的PDF工具和类库就如雨后春笋般涌现。然而,Java应用开发中Adobe技术的支持相对滞后了。这是个奇怪的现象,因为PDF文档是企业信息系统存储和交换信息的大势所趋,而Java技术特别适合这种应用。然而,Java开发人员似乎直到最近才获得成熟可用的PDF支持。
PDFBox(一个BSD许可下的源码开放项目)是一个为开发人员读取和创建PDF文档而准备的纯Java类库。它提供如下特性:
于是,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" );
注意:PDDocument对象使用完毕时需要调用其close()方法来释放创建时使用的资源。
- /Helv 12 Tf
- 0 13.0847 Td
- (Hello World) Tj
Lucene是Apache Jakarta项目的子项目,它是一个流行的源代码开放的搜索引擎库。开发人员可以使用Lucene来创建索引,并基于该索引对大量的文本内容进行复杂的检索。Lucene只支持文本内容的检索,所以开发人员需要将其他形式的数据转换为文本形式才能使用Lucene。例如,Microsoft Word和StarOffice文档都必须先转换为文本形式才能添加到Lucene索引中。
PDF文件也不例外,但PDFBox提供一个特殊的整合对象,这让在Lucene索引中包含PDF文档变得非常容易。将一个基本PDF文档转换为Lucene文档只需要一条语句:
Document doc = LucenePDFDocument.getDocument( file );
这种整合使得开发人员可以轻松地使用Lucene来支持PDF文档的检索和索引。当然,有些应用程序要求更成熟的文本提取方法。此时可以直接使用PDFTextStripper类,或继承该类来满足这种复杂的需求。
通过继承PDFTextStripper并覆盖showCharacter()方法,你可以从许多方面对文本提取进行控制。例如,使用x、y位置信息进行限制以提取特定文本块。你可以有效地忽略所有的y坐标大于某个值的文本,这样文档头部内容就会被排除。
另一个例子。常常有这种情况:从表单创建了一组PDF文档,但这些原始数据被丢失了。也就是说,这些文档都包含一些你感兴趣的文本,而且这些文本都在相似的位置上,但填充文档的表单数据丢失了。例如,你有一些信封,在相同的位置上都有名字和地址信息。这时,你就可以使用PDFTextStripper的派生类来提取期望的字段,这个类就像一种截取屏幕区域的设备。
PDF规范允许PDF文档的创建者对用户使用Acrobat阅读器查看文档时的某些操作进行限制。这些限制包括:
加密文档时必须先指定一个安全处理器,然后使用一个主密码和用户密码进行加密。在下面的代码中,文档被加密,用户不需要敲入就可以在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");
许多应用程序可以生成PDF文档,但不支持控制文档的安全选项。这时PDFBox就可以用来在发送给用户之前截获并加密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
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() );
PDDocument pdf =
PDDocument.load( "i-9.pdf");
PDDocumentCatalog docCatalog =
pdf.getDocumentCatalog();
PDAcroForm acroForm =
docCatalog.getAcroForm();
FDFDocument fdf = acroForm.exportFDF();
fdf.save( "exportedData.fdf" );
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 }
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 }
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
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 }
1 public void toImage() {2 try {3 PDDocument doc = PDDocument4 .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 }
1 /**2 * create the second sample document from the PDF file format specification.3 * 4 * @param file5 * The file to write the PDF to.6 * @param image7 * 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 }
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
PDFBox的下一个版本将支持新的PDF 1.5 对象流和交叉引用流。然后将提供内嵌字体和图像的支持。在PDFBox的努力下,Java应用程序中的PDF技术有望得到充分的支持。
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
