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

需求说明

根据合同模板,将动态的合同标签,合同方以及合同签约时间等动态的生成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();
    }

相关推荐

  1. springboot 动态导出pdf

    2024-03-28 11:02:02       52 阅读
  2. NetCore iText7 根据PDF模板 导出PDF

    2024-03-28 11:02:02       59 阅读
  3. itextpdf 之 html 转 pdf 问题处理

    2024-03-28 11:02:02       55 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-28 11:02:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-28 11:02:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-28 11:02:02       82 阅读
  4. Python语言-面向对象

    2024-03-28 11:02:02       91 阅读

热门阅读

  1. 3月26日,每日信息差

    2024-03-28 11:02:02       43 阅读
  2. C++|char*大小端转换

    2024-03-28 11:02:02       44 阅读
  3. 【力扣】210 课程表(c++)解析

    2024-03-28 11:02:02       46 阅读
  4. flutter 修改app名字

    2024-03-28 11:02:02       39 阅读
  5. 设计模式,装饰模式

    2024-03-28 11:02:02       45 阅读
  6. 设计模式(5):原型模式

    2024-03-28 11:02:02       35 阅读