利用html模版生成PDF文件

一、准备

1、准备好html文件,在需要填充数据的地方用#name#标识,如图:

二、代码示例

1、依赖

        <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>
        <dependency>
            <groupId>com.itextpdf.tool</groupId>
            <artifactId>xmlworker</artifactId>
            <version>5.5.9</version>
        </dependency>
        <dependency>
            <groupId>org.xhtmlrenderer</groupId>
            <artifactId>flying-saucer-pdf-itext5</artifactId>
            <version>9.0.3</version>
        </dependency>

2、代码示例

//生成PDF报告,返回总页数
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int reportPDFOut(PDFInfoVO params) throws Exception{
        File directory = new File("");
        //pdf输出路径
        String filePath = directory.getCanonicalPath() + File.separator + "fileout";
        if(!new File(filePath).exists()){
            new File(filePath).mkdir();
        }
        //字体格式
        String FONT = directory.getCanonicalPath() + File.separator + "file/simsun.ttc";
        //html模版
        String HtmlFilePath = directory.getCanonicalPath() + File.separator + "file/report.html";

        try {
            //读取html文件模版
            FileInputStream fileInputStream = new FileInputStream(HtmlFilePath);
            StringBuilder stringBuilder = new StringBuilder();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream,"utf8"));
            String line;
            while((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            String htmlInfo = stringBuilder.toString();
            
            //替换参数、多个参数多次替换
            htmlInfo = htmlInfo.replace("#customerList#",buffer.toString());

            //生成临时文件
            String htmlFileName =  UUID.randomUUID().toString().replace("-","") + ".html";
            String htmlFilePath = filePath + File.separator + htmlFileName;

            File file = new File(htmlFilePath);
            FileOutputStream fop = new FileOutputStream(file);
            if (!file.exists()) {
                file.createNewFile();
            }
            byte[] contentInBytes = htmlInfo.getBytes();
            fop.write(contentInBytes);
            fop.flush();
            fop.close();

            //生成pdf
            String fileName =  UUID.randomUUID().toString().replace("-","") + ".pdf";
            String pdfFilePath = filePath + File.separator + fileName;

            String url = new File(htmlFilePath).toURI().toURL().toString();
            OutputStream os = new FileOutputStream(pdfFilePath);
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocument(url);
            ITextFontResolver fontResolver = renderer.getFontResolver();
            fontResolver.addFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            renderer.layout();
            renderer.createPDF(os);
            os.close();

            //获取总页数
            PdfReader pdfReader = new PdfReader(new FileInputStream(pdfFilePath));
            int pages = pdfReader.getNumberOfPages();

            //上传阿里云,获取文件路径
            
            //删除临时文件
            File delFile = new File(pdfFilePath);
            if(delFile.exists()){
                delFile.delete();
            }
            File delHtmlFile = new File(htmlFilePath);
            if(delHtmlFile.exists()){
                delHtmlFile.delete();
            }

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

三、总结

该方法适用于数据不确定性的pdf文件生成,比如pdf包含动态表格的情况。

如果模版数据pdf文件数据格式不变,可参考利用PDF模版生成PDF文件_奕安的博客-CSDN博客,使用pdf模版,当然也可以使用html的方式生成。

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值