Thymeleaf模板引擎生成的html字符串转换成pdf

java 复制代码
依赖引入
 	 implementation("org.springframework.boot:spring-boot-starter-thymeleaf")
     implementation("org.xhtmlrenderer:flying-saucer-pdf")

将ITemplateEngine注入到spring管理的类中,

java 复制代码
Context context = new Context();
context.setVariable("name", wasteDisposalSiteDTO.getName());
String  processHtml= iTemplateEngine.process("hazardousWaste", context);//hazardousWaste是html模板文件路径,需要在配置文件中设置//spring:thymeleaf:prefix: classpath:/templates/ 基本路径
 //下载到浏览器
     // 设置响应类型 pdf
        response.setContentType(MediaType.APPLICATION_PDF_VALUE);

        // 设置响应编码
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());

        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.attachment()
                .filename("1" + ".pdf", StandardCharsets.UTF_8)
                .build()
                .toString());
        // 使用ByteArrayOutputStream来捕获PDF字节流
        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            // 创建ITextRenderer对象
            ITextRenderer renderer = new ITextRenderer();
            ITextFontResolver fontResolver = renderer.getFontResolver();
            ClassPathResource classPathResource = new ClassPathResource("/font/simsun.ttc");//加载字体路径,避免生成的pdf加载不出来汉字。
            fontResolver.addFont(classPathResource.getPath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            renderer.setDocumentFromString(processHtml);
            renderer.layout();
            renderer.createPDF(os);

            // 将生成的PDF字节流写入到HTTP响应的输出流中
            response.getOutputStream().write(os.toByteArray());
            response.getOutputStream().flush();
        } catch (DocumentException e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "PDF generation failed");
        }
//...
相关推荐
a11177614 小时前
星球浏览 漫游(纯html 开源)
前端·开源·html
结网的兔子15 小时前
前端开发(前言)——html,css,JavaScript和vue关系
javascript·css·html
前端 贾公子16 小时前
CSS 系统颜色和暗黑模式的关系及意义
前端·javascript·vue.js·html
Never_Satisfied16 小时前
在HTML & CSS中,如何计算CSS特异性
前端·css·html
Felicia-侧听17 小时前
如何统一PDF页面宽度?统一pdf宽度的2种方法
pdf·pdf宽度统一
雾岛心情18 小时前
【Html&CSS】网页设计中的Node.JS 安装
css·html
开开心心_Every18 小时前
音频格式互转工具,支持Mp3ApeWavFlac互转
linux·运维·服务器·typescript·edge·pdf·asp.net
长城202418 小时前
HTML5 中<meter>标签的属性说明
html·html5·meter·meter标签·meter属性·meter标签属性
2501_9307077818 小时前
如何使用C#代码从 PDF 中提取表格并另存为Excel文件
pdf·excel
悟乙己18 小时前
实施手册:如何自己构建财务PDF文件内容抽取引擎
pdf