根据模板PDF动态插入数据(合同等)

1 篇文章 0 订阅

准备工作:

Adobe Acrobat DC PDF编辑器

准备一个PDF文件

1,编辑PDF,点击左上角得下拉框,选择准备表单

2,右键选择文本域

3,双击文本域,弹出文本域属性弹出框,可编辑文本域Key

4,编辑好,点击关闭即可(其他得文本域同理设置即可)

5,全部设置完后点击保存

 

JAVA代码段:

package com.bscc.modules.econtract.util;

import com.alibaba.fastjson.JSONObject;
import com.itextpdf.text.pdf.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;


import java.io.*;
import java.util.*;


/**
 * Description: PdfUtils <br>
 * 依赖的包:itextpdf    itext-asian
 * commons-io,commons-codec
 * @author mk
 * @Date 2018-11-2 14:32 <br>
 * @Param
 * @return
 */
public class PdfUtils {
    public static void main(String[] args) throws IOException {
        HashMap map = new HashMap<String, String>();
        map.put("ent_name","杨杰");
        map.put("legal_name","男");
        map.put("address","27");
        map.put("tel","15521331");
        map.put("agreement_id","812406fdf@qq.com");
        map.put("idCard","4305223243434332");
        map.put("hobby","跑步");
        map.put("time","2019年5月22日");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("ent_name","杨杰");
        jsonObject.put("legal_name","男");
        jsonObject.put("address","27");
        jsonObject.put("tel","15521331");
        jsonObject.put("agreement_id","812406fdf@qq.com");
        jsonObject.put("idCard","4305223243434332");
        jsonObject.put("hobby","跑步");
        jsonObject.put("time","2019年5月22日");
        String sourceFile = "C:\\Users\\zhanghuanhuan\\Desktop\\保证合同-人才贷.pdf";
        String targetFile = "C:\\Users\\zhanghuanhuan\\Desktop\\new1.pdf";
        createPDF(map,sourceFile,targetFile);
    }

    /**
     * Description : 通过Map形式传入动态参数
     * @param map
     * @param sourceFile
     * @param targetFile
     * @throws IOException
     */
    public static void createPDF(HashMap map, String sourceFile, String targetFile) throws IOException {
        File templateFile = new File(sourceFile);
        fillParam(map, FileUtils.readFileToByteArray(templateFile), targetFile);
    }

    /**
     * Description: 使用Map中的参数填充pdf,Map中的key和pdf表单中的field对应 <br>
     * @Param
     * @return
     */
    public static void fillParam(Map<String, String> fieldValueMap, byte[] file, String contractFileName) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(contractFileName);
            PdfReader reader = null;
            PdfStamper stamper = null;
            BaseFont base = null;
            try {
                reader = new PdfReader(file);
                stamper = new PdfStamper(reader, fos);
                stamper.setFormFlattening(true);
                base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                AcroFields acroFields = stamper.getAcroFields();
                for (String key : acroFields.getFields().keySet()) {
                    acroFields.setFieldProperty(key, "textfont", base, null);
                    acroFields.setFieldProperty(key, "textsize", new Float(15), null);
                }
                if (fieldValueMap != null) {
                    for (String fieldName : fieldValueMap.keySet()) {
                        acroFields.setField(fieldName, fieldValueMap.get(fieldName));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (stamper != null) {
                    try {
                        stamper.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (reader != null) {
                    reader.close();
                }
            }
        } catch (Exception e) {
            System.out.println("填充参数异常");
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(fos);
        }
    }

    /**
     * Description 通过JSON形式传入动态参数
     * @param jsonObject
     * @param sourceFile
     * @param targetFile
     * @throws IOException
     */
    public static void createPDF(JSONObject  jsonObject, String sourceFile, String targetFile) throws IOException {
        File templateFile = new File(sourceFile);
        fillParam(jsonObject, FileUtils.readFileToByteArray(templateFile), targetFile);
    }

    /**
     * Description: 使用Map中的参数填充pdf,Map中的key和pdf表单中的field对应 <br>
     * @param fieldValueMap
     * @param file
     * @param contractFileName
     */
    public static void fillParam(JSONObject fieldValueMap, byte[] file, String contractFileName) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(contractFileName);
            PdfReader reader = null;
            PdfStamper stamper = null;
            BaseFont base = null;
            try {
                reader = new PdfReader(file);
                stamper = new PdfStamper(reader, fos);
                stamper.setFormFlattening(true);
                base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                AcroFields acroFields = stamper.getAcroFields();
                for (String key : acroFields.getFields().keySet()) {
                    acroFields.setFieldProperty(key, "textfont", base, null);
                    acroFields.setFieldProperty(key, "textsize", new Float(15), null);
                }
                if (fieldValueMap != null) {
                    for (String fieldName : fieldValueMap.keySet()) {
                        acroFields.setField(fieldName, fieldValueMap.get(fieldName).toString());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (stamper != null) {
                    try {
                        stamper.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (reader != null) {
                    reader.close();
                }
            }
        } catch (Exception e) {
            System.out.println("填充参数异常");
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(fos);
        }
    }

    /**
     * 将File转成FileItem
     * @param file
     * @return
     */
    public static FileItem createFileItem(File file) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem("textField", "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhh1996075

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值