SpringBoot 基于iText 根据PDF模板动态生成文件

SpringBoot 基于iText 根据PDF模板动态生成文件, 需要使用 adobe acrobat pro DC这个工具来自定义模板
支持根据PDF模板生成单页或多页PDF文件

adobe acrobat pro DC 自定义模板

下载地址

链接:https://pan.baidu.com/s/1Vn3bIQ5_D17sEZnkF2t7gg?pwd=n6o1 
提取码:n6o1

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

添加依赖

 <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.4.2</version>
        </dependency>

代码集成


import cn.hutool.core.io.resource.ClassPathResource;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wang
 */
@Slf4j
public class PdfUtil {

    private PdfUtil() {

    }

    /**
     * generatePdf
     * @param params    params
     * @param outputPath    outputPath
     * @return  String
     */
    public static String generatePdf(Map<String, String> params, String outputPath) {
        ClassPathResource resource = new ClassPathResource("templates/test_certificate_temp.pdf");
        InputStream inputStream = resource.getStream();
        ByteArrayOutputStream bos = null;
        PdfReader reader = null;
        FileOutputStream fos = null;
        try {
            reader = new PdfReader(inputStream);
            bos = new ByteArrayOutputStream();
            writePdf(params, bos, reader);
            fos = new FileOutputStream(outputPath);
            bos.writeTo(fos);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        } finally {
            try {
                assert bos != null;
                bos.close();
                reader.close();
                assert fos != null;
                fos.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        return outputPath;
    }

    /**
     * generateMultiPagePdf
     *
     * @param paramsList paramsList
     * @param outputPath outputPath
     * @return String
     */
    public static String generateMultiPagePdf(List<Map<String, String>> paramsList, String outputPath) {
        FileOutputStream fos = null;
        PdfCopy copy = null;
        Document document = null;

        try {
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            InputStream inputStream = classLoader.getResourceAsStream("templates/test_certificate_temp.pdf");

            // 将模板读取到字节数组中
            assert inputStream != null;
            byte[] templateBytes = inputStream.readAllBytes();
            inputStream.close();

            fos = new FileOutputStream(outputPath);
            document = new Document();
            copy = new PdfCopy(document, fos);
            document.open();

            for (Map<String, String> params : paramsList) {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                InputStream templateStream = new ByteArrayInputStream(templateBytes);
                PdfReader reader = new PdfReader(templateStream);
                writePdf(params, bos, reader);
                reader.close();
                templateStream.close();

                PdfReader pageReader = new PdfReader(new ByteArrayInputStream(bos.toByteArray()));
                copy.addPage(copy.getImportedPage(pageReader, 1));
                pageReader.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (document != null) {
                    document.close();
                }
                if (copy != null) {
                    copy.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return outputPath;
    }

    private static void writePdf(Map<String, String> params, ByteArrayOutputStream bos, PdfReader reader) throws DocumentException, IOException {
        PdfStamper pdfStamper = new PdfStamper(reader, bos);
        AcroFields acroFields = pdfStamper.getAcroFields();
        BaseFont font = BaseFont.createFont();
        for (Map.Entry<String, String> param : params.entrySet()) {
            acroFields.setFieldProperty(param.getKey(), "textfont", font, null);
            acroFields.setField(param.getKey(), param.getValue());
        }
        pdfStamper.setFormFlattening(true);
        pdfStamper.close();
    }

    public static void main(String[] args) throws IOException {
        List<Map<String, String>> paramsList = new ArrayList<>();
        Map<String, String> params = new HashMap<>(16);
        params.put("hullId", "hullId_001");
        params.put("boatYear", "boatYear_001");
        params.put("boatBrand", "boatBrand_001");
        params.put("boatModel", "boatModel_001");
        paramsList.add(params);

        params = new HashMap<>(16);
        params.put("hullId", "hullId_002");
        params.put("boatYear", "boatYear_002");
        params.put("boatBrand", "boatBrand_002");
        params.put("boatModel", "boatModel_002");
        paramsList.add(params);

        String outputPath = "D:\\opt\\file_encode_zip\\target\\test_Certificate_8-20-24_target.pdf";
        String path = generateMultiPagePdf(paramsList, outputPath);
//        String path = generatePdf(params, outputPath);
        System.out.println(path);

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

宁漂打工仔

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

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

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

打赏作者

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

抵扣说明:

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

余额充值