效果
@Test
public void test07() {
//创建PdfDocument对象,加载PDF测试文档
PdfDocument doc = new PdfDocument();
doc.loadFromFile("D:\\InstallSoftWare\\IntelliJ2021.3.2\\ideaWorkSpace\\fangshui\\cloud\\src\\main\\webapp\\WEB-INF\\template\\152359527692647693729022820965.pdf");
// 本地给pdf添加电子印章,并去掉第一页左上角的红色字体 开始
PdfPageBase page = doc.getPages().add();
doc.getPages().remove(page);
page = doc.getPages().get(0);
// 本地给pdf添加电子印章,并去掉第一页左上角的红色字体 结束
PdfTextBoxField textBox;
try {
textBox = new PdfTextBoxField(page, "remove");//创建文本框对象
doc.getForm().getFields().add(textBox);//添加文本框到PDF域的集合
} catch (Exception e) {
e.printStackTrace();
}
//加载印章图片
PdfImage image = PdfImage.fromFile("D:\\InstallSoftWare\\IntelliJ2021.3.2\\ideaWorkSpace\\fangshui\\cloud\\src\\main\\webapp\\WEB-INF\\template\\logo.png");
//获取印章图片的宽度和高度
int width = image.getWidth();
int height = image.getHeight();
//创建PdfTemplate对象
PdfTemplate template = new PdfTemplate(width, height);
//将图片绘制到模板
template.getGraphics().drawImage(image, 0, 0, width, height);
//创建PdfRubebrStampAnnotation对象,指定大小和位置
Rectangle2D rect = new Rectangle2D.Float((float) (page.getActualSize().getWidth() - width - 170), (float) (page.getActualSize().getHeight() - height - 410), width, height);
PdfRubberStampAnnotation stamp = new PdfRubberStampAnnotation(rect);
//创建PdfAppearance对象
PdfAppearance pdfAppearance = new PdfAppearance(stamp);
//将模板应用为PdfAppearance的一般状态
pdfAppearance.setNormal(template);
//将PdfAppearance 应用为图章的样式
stamp.setAppearance(pdfAppearance);
//添加图章到PDF
page.getAnnotationsWidget().add(stamp);
//保存文档
doc.saveToFile("保存的目标路径", FileFormat.PDF);
Map<String, Object> rootMap = new HashMap<>();
rootMap.put("zhibao", "zhibao-" + DateUtil.format(DateUtil.currentDate(), "yyyy-MM-dd"));
List<Object> list = ItextPdfUtil.fillData(rootMap, dir + "",
dir + "LISHU.TTF");
System.out.println("https://pub.fsgo365.cn/" + list.get(0).toString());
}