try {
String path = "F:\\杂七杂八\\合同.pdf";
PdfDocument pdf = new PdfDocument();
pdf.loadFromFile(path);
Map<String, String> map = new HashMap<>();
map.put("\\$\\{" + "relateSceneNumber" + "}", "20220722084347399341000000");
map.put("\\$\\{" + "targetNamePath" + "}", "2022二建管理-教材精讲");
map.put("\\$\\{" + "amountShouldPay" + "}", "¥0.1");
map.put("\\$\\{" + "amountActualPay" + "}", "¥0.1");
map.put("\\$\\{" + "partARealName" + "}", "胖虎");
map.put("\\$\\{" + "partACertTypeName" + "}", "身份证");
map.put("\\$\\{" + "partACertNumber" + "}", "412223198006195517");
map.put("\\$\\{" + "partAContactNumber" + "}", "15225465336");
PdfSolidBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.black));
Font font = new Font("宋体", Font.PLAIN, 9);
PdfTrueTypeFont pdfTrueTypeFont = new PdfTrueTypeFont(font, true);
PdfTextFindCollection textFindCollection;
Rectangle2D rec;
for (Map.Entry<String, String> entry : map.entrySet()) {
for (int i=0;i<pdf.getPages().getCount(); i++) {
PdfPageBase page = pdf.getPages().get(i);
textFindCollection = page.findText(entry.getKey(), false);
for (PdfTextFind find : textFindCollection.getFinds()) {
rec = find.getBounds();
page.getCanvas().drawRectangle(PdfBrushes.getWhite(), rec);
page.getCanvas().drawString(entry.getValue(), pdfTrueTypeFont, brush, rec);
}
}
}
pdf.saveToFile("F:\\杂七杂八\\测试.pdf");
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
}