Apache PDFBox的基本使用

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

Maven依赖添加

 <!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
 <dependency>
       <groupId>org.apache.pdfbox</groupId>
       <artifactId>pdfbox</artifactId>
       <version>2.0.25</version>
</dependency>

常用方法

// 文本
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 官网 显示,已经开源175个项目,下面是项目列表。
    翼徳阅读 4,997评论 0 2
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 132,608评论 18 139
  • 最近项目需要实现PDF下载的功能,由于没有这方面的经验,从网上花了很长时间才找到相关的资料。整理之后,发现有如下几...
    飞虎兄阅读 13,727评论 7 34
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 45,127评论 6 345
  • Apache nifi 开发指南 版本:V 1.6 日期:2018年6月13日 [if !supportLists...
    行走的数据智能阅读 7,531评论 0 1