Apache PDFBox的基本使用

Apache PDFBox是一个处理PDF文档的开源JAVA工具库,此项目允许创建新的PDF文档、操作现有文档以及文档中提取内容。

Maven依赖添加

 
 
       org.apache.pdfbox
       pdfbox
       2.0.25

常用方法

// 文本
public void showTextByLeft(PDPageContentStream overContent, String txt, String def, float x, float y) throws Exception {
    //Begin the Content stream
    overContent.beginText();
    //overContent.setWordSpacing(0.01F);
    if (null == txt) {
        txt = def;
    }

    //Setting the position for the line
    overContent.newLineAtOffset(x, y);

    //Adding text in the form of string
    overContent.showText(txt);

    //Ending the content stream
    overContent.endText();
}

private float FONT_SIZE = 12;
//载入现有的pdf模板 
InputStream in = this.getClass().getClassLoader().getResourceAsStream("pdf/1.pdf");
PDDocument document = PDDocument.load(in);
//加载字体
InputStream inFont = this.getClass().getClassLoader().getResourceAsStream("pdf/simfang.ttf");
PDType0Font font = PDType0Font.load(document, inFont);


// Retrieving the pages of the document, and using PREPEND mode
// 获取第一页
PDPage page = document.getPage(0);
PDRectangle pdRectangle = page.getMediaBox();
//添加新的空白页面
PDPage page2 = new PDPage(pdRectangle);
document.addPage(page2);

//获取某一页的流
PDPageContentStream contentStream = new PDPageContentStream(document, page,
        PDPageContentStream.AppendMode.APPEND, true, false);

contentStream.setFont(font , FONT_SIZE);
contentStream.setNonStrokingColor(Color.black);
contentStream.setStrokingColor(Color.black);
//添加文本
showTextByLeft(contentStream, MessageUtil.getMessage("report.label.date") + DateUtil.formatDate(date), "", 30, 720);

//添加矩形并填充背景色
contentStream.addRect(30, 690, 535, 20);
contentStream.setNonStrokingColor(new Color(236, 238, 242));
contentStream.fill();
//添加图片
InputStream stream = getClass().getClassLoader().getResourceAsStream("pdf/football.png");
BufferedImage bi = ImageIO.read(stream);
pdImage = LosslessFactory.createFromImage(document, bi);
//x y ,w,h 
contentStream.drawImage(pdImage, 400, 460, 150, 95);

//保存pdf 
document.save(new File(filePath));
// Closing the document
 document.close();

你可能感兴趣的:(Apache PDFBox的基本使用)