itextpdf给模板pdf写入值

pdf模板文件需要使用工具(Adobe Acrobat DC)创建表单,key对应pdf模板表单的属性
jar:


    com.itextpdf
    itextpdf
    5.5.6


    com.itextpdf
    itext-asian
    5.2.0


代码:
public class PdfUtils {
    // 利用模板生成pdf
    public static void pdfout(String templatePath, String newPDFPath, List> paramList) {
        FileOutputStream out;
        try {
            List list = new ArrayList();
            for (Map map : paramList) {
                PdfReader reader;
                ByteArrayOutputStream bos;
                PdfStamper stamper;
                reader = new PdfReader(templatePath);// 读取pdf模板
                bos = new ByteArrayOutputStream();
                stamper = new PdfStamper(reader, bos);
                AcroFields form = stamper.getAcroFields();
                //文字类的内容处理
                Map datemap = (Map) map.get("datemap");
                for (String key : datemap.keySet()) {
                    String value = datemap.get(key);
                    form.setField(key, value);
                }
                stamper.setFormFlattening(true);// 如果为false,生成的PDF文件可以编辑,如果为true,生成的PDF文件不可以编辑
                stamper.close();
                Document doc = new Document();
                doc.open();
                reader = new PdfReader(bos.toByteArray());
                list.add(reader);
            }
            out = new FileOutputStream(newPDFPath);// 输出流
            //上面已经获得了pdf的每一页,这里我只需要合并成为一个pdf,然后返回
            Document document = new Document();
            PdfCopy copy = new PdfCopy(document, out);
            document.open();
            for (int k = 0; k < list.size(); k++) {
                PdfReader pdfReader = list.get(k);
                document.newPage();
                copy.addDocument(pdfReader);
            }
            copy.close();
        } catch (IOException e) {
            System.out.println(e);
        } catch (DocumentException e) {
            System.out.println(e);
        }
    }


    public static void main(String[] args) {
        // 模板路径
        String templatePath = "E:\\work_order.pdf";
        // 生成的新文件路径
        String newPDFPath = "E:\\new_work_order.pdf";
        List> list = new ArrayList<>();
        Map map = new HashMap();
        map.put("name", "张三1");
        map.put("gender", "男");
        map.put("birthTime", "2019-01-01");
        map.put("workingLife", "2年");
        Map map2 = new HashMap();
        map2.put("name", "李四2");
        map2.put("gender", "男");
        map2.put("birthTime", "2019-01-01");
        map2.put("workingLife", "2年");
        Map paramMmap = new HashMap();
        paramMmap.put("datemap", map);
        list.add(paramMmap);
        Map paramMmap2 = new HashMap();
        paramMmap2.put("datemap", map2);
        list.add(paramMmap2);
        pdfout(templatePath, newPDFPath, list);
    }
}

你可能感兴趣的:(itextpdf给模板pdf写入值)