栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 软件开发 > 后端开发 > Java

Spring Boot Freemark HTML 生成 PDF

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Boot Freemark HTML 生成 PDF



    org.xhtmlrenderer
    flying-saucer-pdf
    9.1.16



    com.itextpdf
    itextpdf
    5.5.13




    org.freemarker
    freemarker
    2.3.31

 templates.ftl 放入resource文件中

simsun.ttc 为字体文件

1. HttpHeaders 写法

@GetMapping("/pdf")
    public ResponseEntity export(HttpServletResponse response) {
        try {
            HttpHeaders headers = new HttpHeaders();
            Map dataMap = new HashMap<>(16);
            dataMap.put("userName", "张三");
            String htmlStr = PDFUtil.freemarkerRender(dataMap, "templates.ftl");
            byte[] pdfBytes = PDFUtil.createPDF(htmlStr, "simsun.ttc");
            if (pdfBytes != null && pdfBytes.length > 0) {
                String fileName = System.currentTimeMillis() + (int) (Math.random() * 90000 + 10000) + ".pdf";
                headers.setContentDispositionFormData("attachment", fileName);
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                return new ResponseEntity(pdfBytes, headers, HttpStatus.OK);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        return new ResponseEntity<>("{ "code" : "404", "message" : "not found" }", headers, HttpStatus.NOT_FOUND);
    }

 2. Response 写法

@GetMapping("/pdf")
    public void export(HttpServletResponse response) {
        ServletOutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            // 设置参数
            Map dataMap = new HashMap<>(16);
            dataMap.put("text", "

姓名:张三

日期:2022/08/10

"); String htmlStr = PDFUtil.freemarkerRender(dataMap, "templates.ftl"); byte[] pdfBytes = PDFUtil.createPDF(htmlStr, "simsun.ttc"); // 获取输出流 outputStream = response.getOutputStream(); if (pdfBytes != null && pdfBytes.length > 0) { // 设置文件名 String fileName = System.currentTimeMillis() + (int) (Math.random() * 90000 + 10000) + ".pdf"; response.setHeader("content-Type", "application/octet-stream"); response.setCharacterEncoding("utf-8"); response.setHeader("Content-disposition", "attachment;filename=" + fileName); // 写入输出流 outputStream.write(pdfBytes); // 获取输入流 inputStream = new ByteArrayInputStream(pdfBytes); // 输入流保存阿里云 final String upload = OssBootUtil.upload(inputStream, "upload/agree/" + fileName); } } catch (Exception e) { e.printStackTrace(); try { if (outputStream != null) { outputStream.close(); } if (inputStream != null) { inputStream.close(); } } catch (IOException ex) { ex.printStackTrace(); } } }
import com.dpxdata.backend.report.util.ResourceFileUtil;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.*;
import java.util.Map;


public class PDFUtil {
    private PDFUtil(){}

    private volatile static Configuration configuration;

    static {
        if (configuration == null) {
            synchronized (PDFUtil.class) {
                if (configuration == null) {
                    configuration = new Configuration(Configuration.VERSION_2_3_28);
                }
            }
        }
    }

    
    public static String freemarkerRender(Map dataMap, String ftlFilePath) {
        Writer out = new StringWriter();
        configuration.setDefaultEncoding("UTF-8");
        configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        try {
            configuration.setDirectoryForTemplateLoading(new File(ResourceFileUtil.getParent(ftlFilePath)));
            configuration.setLogTemplateExceptions(false);
            configuration.setWrapUncheckedExceptions(true);
            Template template = configuration.getTemplate(ResourceFileUtil.getFileName(ftlFilePath));
            template.process(dataMap, out);
            out.flush();
            return out.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    
    public static byte[] createPDF(String htmlTmpStr, String fontFile) {
        ByteArrayOutputStream outputStream = null;
        byte[] result = null;
        try {
            outputStream = new ByteArrayOutputStream();
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocumentFromString(htmlTmpStr);
            ITextFontResolver fontResolver = renderer.getFontResolver();
            // 解决中文支持问题,需要所需字体(ttc)文件
            fontResolver.addFont(ResourceFileUtil.getAbsolutePath(fontFile),BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            renderer.layout();
            renderer.createPDF(outputStream);
            result=outputStream.toByteArray();
            if(outputStream != null) {
                outputStream.flush();
                outputStream.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

}



    
    Title
    





    

收 据

付款人

${userName!''}

${text!''}

转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/1039397.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号