HTML生成下载PDF文件或ZIP压缩包文件

1.工具类(下载到本地)

public class FreemarkerReportWriter {

    /**
     * 字体文件名称
     */
    private final static String DEFAULT_FONT = "yahei.ttf";

 /** 
   * templateContent ftl模版内容 
   * data ftl模版数据 
   * file 下载本地PDF文件
   * classPath 文件路径
 */
    public static void createPdf(String templateContent, Map<String, Object> data, File file, String classPath) {
        FileOutputStream outputStream = null;
        ITextRenderer renderer = new ITextRenderer();
        try {
            Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
            StringTemplateLoader stringLoader = new StringTemplateLoader();
            stringLoader.putTemplate("myTemplate", templateContent);
            cfg.setTemplateLoader(stringLoader);
            Template template = cfg.getTemplate("myTemplate", "utf-8");
            String htmlData = FreeMarkerTemplateUtils.processTemplateIntoString(template, data);
            outputStream = new FileOutputStream(file);
            ITextFontResolver fontResolver = renderer.getFontResolver();
            // 解决中文乱码问题,fontPath为中文字体地址
            fontResolver.addFont(classPath + DEFAULT_FONT, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            renderer.setDocumentFromString(htmlData);
            renderer.layout();
            renderer.createPDF(outputStream);
        } catch (Exception e) {
            log.error("生成失败", e);
        } finally {
            renderer.finishPDF();
            IOUtils.closeQuietly(outputStream);
        }
    }

    public static void exportPdf(String templateContent, Map<String, Object> data, HttpServletResponse response) {
        File file = null;
        try {
            String classPath = PdfExportUtil.class.getProtectionDomain().getCodeSource().getLocation().getPath();
            log.info("classPath路径:{}", classPath);
            String fileName = System.currentTimeMillis() + ".pdf";
            createPdf(templateContent, data, new File(classPath + fileName), classPath);
            log.info("pdf长度:{}", new File(classPath + fileName).length());
            file = new File(classPath + fileName);
            ServletOutputStream outputStream = response.getOutputStrea
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值