Java PDF模板生成PDF

一、 制作PDF模板,使用AdobeAcrobat DC,必须使用这个来制作from域。使用AdobeAcrobat DC将Word导成PDF文档进行文本字段的制作

对模板内容的设置如下:

Java PDF模板生成PDF



二、将需要动态传入模板的值进行业务写入

主要是写入的方法

/**
     * 根据PDF模板生成PDF文件
     * @param sourceFile 原模板文件
     * @param targetFile 动态输入写入的文件
     * @param fieldMap 动态数据值
     */
    public static void toPDFWriteValue(String sourceFile,String fileName,String targetFilePath,Map<String,Object> fieldMap)throws Exception{
        try {
            PdfReader reader = new PdfReader(sourceFile)
            ByteArrayOutputStream bos = new ByteArrayOutputStream()
            PdfStamper ps = new PdfStamper(reader, bos)
            AcroFields s = ps.getAcroFields()
            //解决中文
            com.itextpdf.text.pdf.BaseFont bfChinese = com.itextpdf.text.pdf.BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false)
            s.addSubstitutionFont(bfChinese)
            //判断写入文件是否存在,不存在创建
            File file = new File(targetFilePath)
            if (!file.exists()) {
                file.mkdirs()
            }
            String fileSavePath = targetFilePath + fileName
            File file1 = new File(fileSavePath)
            if (!file1.exists()) {
                file1.createNewFile()
            }


            //将值封装至map中
            for(String key:fieldMap.keySet()){
                //遍历赋值
                s.setField(key,fieldMap.get(key).toString())
            }
            ps.setFormFlattening(true)
            ps.close()
            FileOutputStream fos = new FileOutputStream(fileSavePath)
            fos.write(bos.toByteArray())
        } catch (FileNotFoundException e) {


            logger.error("生成PDF文件异常", e)
        } catch (Exception e) {
            logger.error("生成PDF文件异常", e)
        }
    }