使用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();
        }

 

上一篇:Idea导入eclipse项目需要做什么


下一篇:Java利用IText导出PDF(更新)