【第012篇】通过将数据填充到PDF模板中来生成PDF文件工具类

package io.renren.common.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.*;
import io.renren.modules.util.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

@Component
public class PdfUtils {

    public static String downloadFilePath;

    /**
     * 获取文件下载路径
     *
     * @param downloadFilePath
     */
    @Value("${downloadFilePath}")
    public void setDownloadFilePath(String downloadFilePath) {
        PdfUtils.downloadFilePath = downloadFilePath;
    }

    /**
     * 填充模板
     *
     * @param templateName 模板名称(相对路径)
     * @param newPdfPath   生成文件路径
     * @param dataMap      待填充的数据
     * @return
     * @throws Exception
     */
    public static String fillDataToTemplate(String templateName, String newPdfPath, Map<String, Object> dataMap) throws Exception {
        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
            // 输出流
            out = new FileOutputStream(newPdfPath);
            // 读取pdf模板
            reader = new PdfReader(getTemplatePath(templateName));
            int pageCount = reader.getNumberOfPages();
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            // 使用中文字体
            String fontPath = getFontPath("");
            BaseFont bfChinese = BaseFont.createFont(fontPath + ",1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            // 文字类的内容处理
            form.addSubstitutionFont(bfChinese);
            // 遍历data 给pdf表单表格赋值
            for (String key : dataMap.keySet()) {
                String value = StringUtils.checkObj2Str(dataMap.get(key));
                // form.setFieldProperty("fill_1","testfont",bfChinese,null);
                form.setField(key, value);
            }
            stamper.setFormFlattening(true);//如果为false那么生成的PDF文件还能编辑,一定要设为true
            stamper.close();
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = null;
            for (int j = 1; j <= pageCount; j++) {
                importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), j);
                copy.addPage(importPage);
            }
            doc.close();
        } catch (Exception e) {
            throw e;
        }
        return newPdfPath;
    }

    /**
     * 获取字体
     *
     * @param font
     * @return
     */
    private static String getFontPath(String font) {
        font = StringUtils.isNotEmpty(font) ? font : "simsun.ttc";
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        File file = new File(path);
        String absolutePath = file.getAbsolutePath().replace("\\", "/");
        String fontPath = absolutePath + "/font/" + font;
        return fontPath;
    }

    /**
     * 获取模板路径
     *
     * @param filePath
     * @return
     */
    private static String getTemplatePath(String filePath) {
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        File file = new File(path);
        String absolutePath = file.getAbsolutePath().replace("\\", "/");
        String templatePath = absolutePath + "/public/template/" + filePath;
        return templatePath;
    }

    public static void main(String[] args) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("xue_hao", "2009232425009abcdefg");
        dataMap.put("xing_ming", "小三a");
        dataMap.put("xing_bie", "男");
        dataMap.put("chu_sheng_ri_qi", "1989年9月5日");
        dataMap.put("shen_fen_zheng_hao", "130525198909051234");
        dataMap.put("jia_ting_zhu_zhi", "河北省邢台市");
        try {
            String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
            File file = new File(path);
            String absolutePath = file.getAbsolutePath().replace("\\", "/");
            String templatePath = absolutePath + "/public/template/student.pdf";
            String newPdfPath = "D:/student.pdf";
            fillDataToTemplate(templatePath, newPdfPath, dataMap);
            System.out.println("生成文件成功!");
        } catch (Exception e) {
            System.err.println("生成文件出错!");
            e.printStackTrace();
        }
    }
}

在这里插入图片描述
制作模板过程:
在这里插入图片描述
在这里插入图片描述在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

嘉&年华

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

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

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

打赏作者

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

抵扣说明:

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

余额充值