SpringBoot集成 itextpdf 根据模板动态生成PDF

本文介绍了如何在SpringBoot项目中集成iTextPDF库,处理PDF模板并动态填充数据,包括添加依赖、构建工具类PDFUtils用于生成和编辑PDF,以及处理MultipartFile以便于文件上传和返回URL。
摘要由CSDN通过智能技术生成

需求说明

根据合同模板,将动态的合同标签,合同方以及合同签约时间等动态的生成PDF,供用户下载打印。

前期准备

安装 Adobe Acrobat DC
链接:https://pan.baidu.com/s/1xkIioIBDG4uLBGP20SZJEA
提取码:yn8g

Spring Boot 集成

添加依赖

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.9</version>
            <scope>compile</scope>
        </dependency>
        <!--中文问题解决-->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
       

构建工具类

public class PDFUtils {
    private static final Logger log = LoggerFactory.getLogger(PDFUtils.class);

    /**
     * 根据pdf模板输出流
     * @param templateFileName 模板文件名
     * @param resultMap 包含文件字段名和值的map
     * @return 生成的文件字节流
     */
    public static ByteArrayOutputStream createPdfStream(String templateFileName,
                                                        Map<String, String> resultMap){

        ByteArrayOutputStream ba = new ByteArrayOutputStream();
        PdfStamper stamp =null;
        PdfReader reader = null;
        try {


            reader = new PdfReader(templateFileName);
            stamp = new PdfStamper(reader, ba);

            //使用字体
            BaseFont bf = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            /* 获取模版中的字段 */
            AcroFields form = stamp.getAcroFields();

            //填充表单
            if (resultMap != null) {
                for (Map.Entry<String, String> entry : resultMap.entrySet()) {

                    form.setFieldProperty(entry.getKey(), "textfont", bf, null);
                    form.setField(entry.getKey(), entry.getValue()!=null?entry.getValue():"");
                }
            }
            //不能编辑
            stamp.setFormFlattening(true);

        } catch (IOException e) {
            log.error("文档构建I/O异常",e);
        } catch (DocumentException e) {
            log.error("文档构建异常",e);
        }
        finally {
            if(stamp!=null){
                try {
                    stamp.close();
                } catch (DocumentException e) {
                    log.error("流关闭错误",e);
                } catch (IOException e) {
                    log.error("流关闭错误",e);
                }
            }
            if(reader!=null){
                reader.close();
            }
        }
        return ba;
    }
}

构建MultipartFile

方便之后上传OSS返回url

public UploadFileModel createUrl(String filePath, ByteArrayOutputStream byteArrayOutputStream) throws URISyntaxException {
        try{

            byte[] pdfBytes = byteArrayOutputStream.toByteArray();
            MultipartFile multipartFile = new MockMultipartFile(
                    "file",
                    filePath,
                    "application/pdf",
                    pdfBytes
            );

            return uploadFileUtil.upload(multipartFile);
        } catch (Exception e) {
            log.error("创建Url时出错:" + e.getMessage());
        }
        return null;
    }

编辑PDF模板

在这里插入图片描述
在这里插入图片描述

Java代码设置对应form的key-value

pdf模板放在springboot 项目目录resources/static 目录下

 public String createContract(CreateContractRequest request) {
        HashMap<String, String> map = new HashMap<>();
        map.put("companyName",request.getCompanyName());
        map.put("phone",request.getPhone());
        UploadFileModel url = null;
        ByteArrayOutputStream pdfStream = PDFUtils.createPdfStream(UserApplication.class.getResource("/").getPath() + "static/contract.pdf", map);
        try {
            url = createUrl("合同.pdf", pdfStream);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        return url.getUrl();
    }
  • 10
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

二进制诗人

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

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

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

打赏作者

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

抵扣说明:

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

余额充值