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");
        }
//...
相关推荐
xinixini4 小时前
小初高全学科课程标准PDF
pdf
MinterFusion4 小时前
HTML DOM元素的定位问题
前端·css·html
SQVIoMPLe6 小时前
python-langchain框架(3-7-提取pdf中的图片 )
python·langchain·pdf
Highcharts.js7 小时前
Highcharts客户端导出使用文档说明|图表导出模块讲解
前端·javascript·pdf·highcharts·图表导出
Hilaku7 小时前
一周狂揽40K+ Star⭐ 的 Pretext 到底有多变态?
前端·javascript·html
银河系的一束光8 小时前
旅游网站html、css、bootstrap
css·html·旅游
前端老石人9 小时前
文本级语义与变更标记
前端·html
CHANG_THE_WORLD10 小时前
PDF结构的清晰图示
java·服务器·pdf
怀君10 小时前
Uniapp——View布局生成图片转PDF
pdf·uni-app
其实秋天的枫10 小时前
2026年初中中考英语大纲词汇表1600个电子版PDF(含单词音频和默写本)
经验分享·pdf