赞
踩
需要引用如下包
- <dependency>
- <groupId>com.itextpdf</groupId>
- <artifactId>itext-core</artifactId>
- <version>8.0.3</version>
- <type>pom</type>
- </dependency>
1、预先准备一个pdf模板,并在指定位置添加表单域。如果不知道如何添加表单域自行百度搜索。将制作好的pdf文件保存在指定目录下。图片中需要填充的地方颜色不一样就是添加了"表单域"。每一个表单域都一个名字,图片上是看不出来的。在编辑pdf添加表单域的时候就会有让修改,默认text1。
例如:
2、上代码
- //windows 系统字体路径
- private static final String FONT_PATH = "C:\\Windows\\Fonts\\simsun.ttc,0";
- //制作好的pdf模板文件存放路径
- private static final String TEMP_PATH = "template.pdf";
- // 文件输出路径
- private static final String DEST = "D:\\pdf\\after.pdf";
-
- public static void main(String[] args) throws IOException {
-
- fillPdfFile();
- }
-
- /**
- * 使用pdf表单域填充内容到指定位置
- */
- public static void fillPdfFile() {
- try {
- Map<String, String> map = new HashMap<>(10);
- map.put("text1", "中华人民共和国");
-
- PdfDocument pdfDocument = new PdfDocument(new PdfReader(TEMP_PATH), new PdfWriter(DEST));
- // 获取pdf表单
- PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDocument, false);
- //设置字体
- PdfFont font = PdfFontFactory.createFont(FONT_PATH);
- //背景色
- DeviceRgb color = new DeviceRgb(0, 0, 0);
- //遍历获取所有表单域,给对应的key上设置值
- for (Map.Entry<String, String> entry : map.entrySet()) {
- form.getAllFormFields().get(entry.getKey()).setValue(entry.getValue()).setColor(color).setFont(font);
- }
- //清除表单域
- form.flattenFields();
-
- pdfDocument.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。