apache PDFbox 入门

来源:互联网 发布:mac照片导入ipad 编辑:程序博客网 时间:2024/05/20 12:48

PDFBox下载地址:http://pdfbox.apache.org/download.html

PDFBox的主要功能:

1.抽取PDF中的文本内容

2.合并PDF文档

3.对PDF文档进行加密/解密

4.集成Lucene搜索索引

5.填充表单数据FDF和XFDF

6.通过文本文件创建PDF文档

7.创建PDF页面中的图像

8.打印PDF

下面是一个通过PDFBox创建PDF文档的一个小例子

/**
 *  使用 PDFbox 操作PDF
 * 
 *
 */
public class CreatePDFDocument {

   public static void createBlankPDF(){
      PDDocument doc=null;
try {
//创建PDF文档
doc=new PDDocument();
//创建页面
PDPage blankPage=new PDPage();
//将页面添加到 文档中
doc.addPage(blankPage);
//保存文档
doc.save("d:/pdfboxtest/blank.pdf");
} catch (IOException e) {
e.printStackTrace();
} catch (COSVisitorException e) {
e.printStackTrace();
}finally{
try {
if(doc!=null){
doc.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}

}

public static void createHelloPDF(){
PDDocument pdfDoc=null;
PDPageContentStream contentStream=null;
try {
//创建PDF文档
pdfDoc=new PDDocument();
//
PDPage pdPage=new PDPage();
//
pdfDoc.addPage(pdPage);
//PDF字体
PDFont font=PDType1Font.HELVETICA_BOLD;
// PDPageContentStream
contentStream=new PDPageContentStream(pdfDoc, pdPage);
//开始向PDF page中写入文本内容
contentStream.beginText();
//设置内容字体
contentStream.setFont(font, 12);
//将文本内容 移动到 Page中的指定位置
contentStream.moveTextPositionByAmount(100,700);
//写入字符串
contentStream.drawString("Hello world");
//写入结束
contentStream.endText();
//
contentStream.close();
//保存PDF文档
pdfDoc.save("d:/pdfboxtest/hello.pdf");

} catch (IOException e) {
e.printStackTrace();
} catch (COSVisitorException e) {
e.printStackTrace();
}finally{
if(pdfDoc!=null){
try {
pdfDoc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

public static void main(String[] args) {
createBlankPDF();
createHelloPDF();
}

}

COS和PD的模型设计图