添加依赖
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.22</version>
</dependency>
编写程序入口
try {
// 打开 PDF 文件
File file = new File("文件地址");
PDDocument document = PDDocument.load(file);
// 修改pdf的页数
PDPage page = document.getPage(0);
// 在页面上添加文字
addText(document, page);
// addText(document, page, result);
// 保存修改后的 PDF 文件
document.save("文件地址");
// 关闭文档
document.close();
} catch (IOException e) {
e.printStackTrace();
}
单次添加
private static PDPageContentStream addText(PDDocument document, PDPage page) throws IOException {
// 创建一个新的页面内容流
PDPageContentStream contentStream = new PDPageContentStream(document, page,true, true, true);
// 设置字体和文字大小
contentStream.setFont(PDType1Font.HELVETICA, 12);
// 设置文字颜色
contentStream.setNonStrokingColor(Color.BLACK);
// 在指定位置添加文字
contentStream.beginText();
//此坐标为从下往上
contentStream.newLineAtOffset(230, 620);
//中文会报错
contentStream.showText("2023/10/25");
contentStream.endText();
// 关闭页面内容流
contentStream.close();
return contentStream;
}
批量添加
private static PDPageContentStream addText(PDDocument document, PDPage page, List<Map<String, Object>> result) throws IOException {
// 创建一个新的页面内容流
PDPageContentStream contentStream = new PDPageContentStream(document, page, true, true, true);
// 设置字体和文字大小
contentStream.setFont(PDType1Font.HELVETICA, 12);
// 设置文字颜色
contentStream.setNonStrokingColor(Color.BLACK);
//加粗
// contentStream.setRenderingMode(RenderingMode.FILL);
// 在指定位置添加文字
for (Map<String, Object> map : result) {
contentStream.beginText();
if (ObjectUtils.isNotEmpty(map.get("tx")) && ObjectUtils.isNotEmpty(map.get("ty"))) {
contentStream.newLineAtOffset(Float.parseFloat(map.get("tx").toString()), Float.parseFloat(map.get("ty").toString()));
}
if (ObjectUtils.isNotEmpty(map.get("time"))) {
contentStream.showText(map.get("time").toString());
}
contentStream.endText();
}
// 关闭页面内容流
contentStream.close();
return contentStream;
}