使用pdf文本域模板生成对应的pdf

第一步:

下载jar包

<!-- itext的pdf的依赖-->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.10</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-pdfa</artifactId>
            <version>5.5.10</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-xtra</artifactId>
            <version>5.5.10</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf.tool</groupId>
            <artifactId>xmlworker</artifactId>
            <version>5.5.10</version>
        </dependency>
<!--itext的语言包-->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>

第二步,写工具类

public static void fillPdf(String filePath, Map<String, String> params, String outPath) {
        try {
            PdfReader reader = new PdfReader(filePath);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            PdfStamper ps = new PdfStamper(reader, bos);
            AcroFields s = ps.getAcroFields();
            // 给表单添加中文字体 这里采用系统字体。不设置的话,中文可能无法显示,这里全是英文,所以不用改成中文适应
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
            s.addSubstitutionFont(bf);
            // 遍历data 给pdf表单表格赋值
            for (String key : params.keySet()) {
                    s.setField(key,params.get(key));
            }
            ps.setFormFlattening(true);
            ps.close();
            FileOutputStream fos = new FileOutputStream(outPath);
            fos.write(bos.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

第三步:使用

 Map root = new HashMap();
        root.put("realName", paper.get("realName"));
        root.put("sn", paper.get("sn"));
        root.put("title", paper.get("title"));
        root.put("acceptResult", paper.get("acceptResult"));
        String path = PathUtil.getClasspath() + "yqh";
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        ItextPDFUtil.fillPdf(PathUtil.getClassResources() + "pdf/paperCnInvatation.pdf", root, PathUtil.getClasspath() + "yqh/" + id + ".pdf");
        try {
            FileUtil.fileDownload(response, PathUtil.getClasspath() + "yqh/" + id + ".pdf", "稿件邀请函.pdf");
        } catch (Exception e) {
            e.printStackTrace();
        }

 

转载于:https://www.cnblogs.com/dhrwawa/p/11287275.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值