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");
        }
//...
相关推荐
redfred6 小时前
Stirling-PDF 使用教程:开源 PDF 工具箱 50+ 工具 PDF转Word/合并/压缩/OCR 桌面版 Docker 部署详解
pdf·开源·word
2501_930707789 小时前
如何使用C#代码向 PDF 文档添加多种类型的注释
pdf
SamChan9014 小时前
Python+PyMuPDF提取PDF表格并翻译:表格结构检测与双语重建实战
windows·python·ai·pdf·wpf
E_ICEBLUE15 小时前
Python 实现 Markdown 转 Word、PDF:从转换到页面设置
python·pdf·word·markdown·格式转换
zhonyu鱼15 小时前
Drawpile:多人实时协作绘画,一起在同一块画布上画画
笔记·pdf·开源·开源软件
SamChan9016 小时前
Python+OpenCV检测PDF翻译后排版偏移:像素级格式一致性验证
python·opencv·ai·pdf·wpf
todoitbo16 小时前
PDF 合并、转换也能自己部署:极空间运行 Stirling PDF,文件交给自己的服务器处理
网络安全·pdf·文件·nas·极空间
专家大圣16 小时前
给自己搭一个 PDF 工具站:Stirling-PDF 部署、格式转换与远程访问实战
网络·pdf·内网穿透
RD_daoyi16 小时前
谷歌改写了76%的标题:超60字符的,95%会被谷歌自己重写
大数据·服务器·开发语言·前端·搜索引擎·html
IMPYLH16 小时前
HTML 的 <map> 元素
前端·html