使用Thymeleaf生成含阿拉伯文本的PDF显示空白问题求助
解决Thymeleaf + Flying Saucer生成阿拉伯语PDF空白问题
针对你遇到的PDF空白问题,从核心环节排查并修复:
1. 确认Thymeleaf渲染的HTML内容正确性
首先要确保Thymeleaf输出的HTML是完整且编码正确的,添加编码配置并打印渲染结果:
private String parseThymeleafTemplate() { ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver(); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode(TemplateMode.HTML); templateResolver.setCharacterEncoding("UTF-8"); // 强制指定UTF-8编码 TemplateEngine templateEngine = new TemplateEngine(); templateEngine.setTemplateResolver(templateResolver); Context context = new Context(); context.setVariable("title", "عنوان"); String renderedHtml = templateEngine.process("template", context); System.out.println(renderedHtml); // 打印确认内容是否包含阿拉伯语 return renderedHtml; }
如果打印的HTML无目标内容,先排查Thymeleaf模板路径、变量赋值是否正确。
2. 修复字体加载问题
你的字体加载存在3个关键问题,逐一修正:
- 路径问题:
src/main/resources是开发路径,打包后不存在,改用Classpath方式加载 - TTC是字体集合,必须指定具体字体索引
- 改用
BaseFont.EMBEDDED确保字体嵌入PDF,避免依赖系统字体
修改后的PDF生成代码:
public void onPrintPdfButtonClick() throws DocumentException, IOException { String outputFolder = ".../template.pdf"; // 使用try-with-resources自动管理流,避免资源泄漏 try (OutputStream outputStream = new FileOutputStream(outputFolder)) { ITextRenderer renderer = new ITextRenderer(); ITextFontResolver resolver = renderer.getFontResolver(); // 从Classpath加载字体文件 try (InputStream fontStream = getClass().getResourceAsStream("/Al Nile.ttc")) { if (fontStream == null) { throw new IOException("未找到字体文件Al Nile.ttc"); } // 指定TTC中的第一个字体(索引0),并嵌入PDF resolver.addFont(fontStream, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, BaseFont.NOT_CACHED, new int[]{0}); } String htmlContent = parseThymeleafTemplate(); // 明确指定UTF-8编码加载HTML renderer.setDocumentFromString(htmlContent, null, "UTF-8"); renderer.layout(); renderer.createPDF(outputStream); } }
3. 完善HTML模板,确保字体和RTL生效
在模板中添加UTF-8元标签和全局CSS,强制应用字体与RTL排版规则:
<html xmlns:th="http://www.thymeleaf.org" lang="ar" dir="rtl"> <head> <meta charset="UTF-8"> <style> * { font-family: "Al Nile", sans-serif !important; direction: rtl; } </style> </head> <body> <h3 style="text-align: center; color: black"> <span th:text="${title}"></span> </h3> </body> </html>
排查步骤总结
- 检查Thymeleaf渲染的HTML是否包含正确的阿拉伯语文本
- 确认字体文件存在于
src/main/resources目录,打包后能被Classpath访问 - 验证字体加载是否成功,可通过捕获异常排查路径或文件损坏问题
- 确保PDF生成时流正确关闭,避免文件损坏无法打开
内容的提问来源于stack exchange,提问作者Youssef Ehab
相关产品推荐
相关产品推荐

