在adobe生成pdf模板后,用代码填充pdf内容(添加图片与表格等)(一)

282 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第十五天,点击查看活动详情


由于公司需要生成PDF文件,研究了一下在adobe生成pdf模板后,用代码填充pdf内容(添加图片与表格等)功能。

  1. 首先需要在adobe工具中导入没有数据的基础PDF模型,在需要赋值的地方,加入文本域,并填上字段名。

  2. 代码中导入生成好的PDF模型地址,创建PDF对象,对象中字段名是模型中定义的名称,赋值之后,将值放入名称对应的模型数据中。

//横版pdf模板地址
private static String horiPdfTemp = PropertiesLoader.getString("hori.pdf.temp");
//下方图片
private static String downImg = PropertiesLoader.getString("hori.down.img");
 
public static InputStream templetreq(HoriPdfModel horiPdfModel) throws Exception {
    Map<String, Object> map = new HashMap<>();
    map = beanToMap(horiPdfModel);
    PdfReader reader = new PdfReader(horiPdfTemp);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    PdfStamper ps = new PdfStamper(reader, bos);
    AcroFields s = ps.getAcroFields();
    s = setFieldHori(s, map, ps);
    ps.setFormFlattening(true);
    ps.close();
    InputStream inputStream = new ByteArrayInputStream(bos.toByteArray());
    return inputStream;
}

下面的方法是循环字段Map中所有的key,根据key对应模板的名称,赋对应的Value,在赋值的同时对特殊格式的数据做特殊处理,比如日期格式的数据,数字格式的数据等。

/**
 * 对模板中字段设置对应的value
 *
 * @param form
 * @param hashMap
 * @return
 * @Description (详细说明)
 * @Date 2017329日 下午1:48:25
 */
@SuppressWarnings("unchecked")
public static AcroFields setFieldHori(AcroFields form, Map<String, Object> hashMap, PdfStamper pdfStamper) {
    Set<String> it = hashMap.keySet();
    Iterator<String> itr = it.iterator();
    while (itr.hasNext()) {
        try {
            Object temp = itr.next();
            Object tempValue = hashMap.get(temp);
            if (hashMap.get(temp.toString()) != null && !hashMap.get(temp.toString()).equals("null")) {
                if (tempValue instanceof ProjectListModel) {
                    insertTable(form, tempValue, pdfStamper);
                } else {
                    setPdfFont(form, temp.toString(), (String) hashMap.get(temp.toString()), 8, 0);
                   
                    String sj = hashMap.get("billDate").toString();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(sdf.parse(sj));
                    setPdfFont(form, "n", String.valueOf(cal.get(Calendar.YEAR)), 8, 0);
                    setPdfFont(form, "y", String.valueOf(cal.get(Calendar.MONTH) + 1), 8, 0);
                    setPdfFont(form, "r", String.valueOf(cal.get(Calendar.DATE)), 8, 0);
                }
            }
        } catch (Exception e) {
            logger.error("设置模板字段失败", e);
            throw new ServiceException("设置模板字段失败");
        }
    }
    return form;
}