Generate PDF files using PDF templates



foreword

How to use the PDF template to fill data and generate the PDF file we want?


1. Prepare the PDF template

1. Prepare the PDF file that needs to be generated

2. Use an editor (for example: Foxit PhantomPDF) to edit the PDF file, create a new text field, and save it.


2. Code example

1. Dependence

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.9</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>


2. Code

    /**
     * 利用模板生成pdf,入参为设置的文本域替换字段
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void pdfOut(Map<String, String> inputMap) throws Exception {
        // 模板路径
        File directory = new File("");// 参数为空
        String templatePath = directory.getCanonicalPath() + File.separator + "file/contractPDF.pdf";
        // 输出文件夹(临时)
        String newPdfPath = directory.getCanonicalPath() + File.separator + "fileout";
        if(!new File(newPdfPath).exists()){
            new File(newPdfPath).mkdir();
        }
        //字体文件
        String simfangPath = directory.getCanonicalPath() + File.separator + "file/simfang.ttf";

        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
            BaseFont bf = BaseFont.createFont(simfangPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            // 输出流
            String fileName = UUID.randomUUID().toString().replace("-","") + ".pdf";
            String filePath = newPdfPath + File.separator + fileName;
            File outFile = new File(filePath);
            if (!outFile.getParentFile().exists()) {
                outFile.getParentFile().mkdirs();
            }
            out = new FileOutputStream(filePath);
            // 读取pdf模板
            reader = new PdfReader(templatePath);

            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            //文字类的内容处理
            Map<String, String> datemap = inputMap;
            form.addSubstitutionFont(bf);
            for (String key : datemap.keySet()) {
                String value = datemap.get(key);
                form.setField(key, value);
            }
            stamper.setFormFlattening(false);
            stamper.close();
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            for (int i = 1; i < 4; i++) {
                PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), i);
                copy.addPage(importPage);
            }
            doc.close();

            //filePath 为得到的pdf文件

            //上传阿里云,返回pdf路径
            
            //保存阿里云返回的文件路径

            //删除临时文件
            File delFile = new File(filePath);
            if(delFile.exists()){
                delFile.delete();
            }

        } catch (Exception ex) {
            throw new Exception(ex);
        }
    }

3. Summary

This method is suitable for generating pdf files with fixed data.

If the data format of the template data pdf file changes dynamically, for example, if there is a dynamic table, you can refer to Generating PDF Files Using HTML Template_Yian's Blog-CSDN Blog , and use the HTML template to dynamically generate it.

Guess you like

Origin blog.csdn.net/qwerrwqe/article/details/120666389