iText 7 HTML转PDF场景下阿拉伯语RTL排版失效问题咨询
iText 7 HTML转PDF阿拉伯语RTL布局异常解决方案
问题根源
iText 7 的 pdfHTML 组件默认未启用双向文本(BIDI)排版能力,阿拉伯语、希伯来语等从右到左书写的语言,仅靠HTML的dir属性和字体配置无法触发RTL排版逻辑,必须显式开启BIDI支持开关。
修复方案
1. 核心代码修改
在原有ConverterProperties配置中新增BIDI支持属性即可,修改后的业务代码如下:
public static final String[] FONTS = { "src/main/resources/fonts/noto/NotoNaskhArabic-Regular.ttf", "src/main/resources/fonts/noto/arial.ttf" }; String htmlString = null; try { // 显式指定编码避免乱码 htmlString = FileUtils.readFileToString(htmlTemplateFile, "UTF-8"); } catch (IOException e) { e.printStackTrace(); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); ConverterProperties properties = new ConverterProperties(); FontProvider fontProvider = new DefaultFontProvider(false, false, false); for (String font : FONTS) { FontProgram fontProgram = FontProgramFactory.createFont(font); fontProvider.addFont(fontProgram); } properties.setFontProvider(fontProvider); properties.setCharset("UTF-8"); // 新增:开启双向文本支持,RTL语言必须配置 properties.setProperty(HtmlConverterProperty.BIDI_SUPPORT, true); HtmlConverter.convertToPdf(htmlString, baos, properties);
注意:如果你的iText版本较低找不到HtmlConverterProperty.BIDI_SUPPORT常量,可以直接用字符串"pdfHTML.bidi.support"作为配置key
2. 可选HTML优化
如果整页存在大量阿拉伯语内容,可直接在<html>或<body>标签上添加dir="rtl"属性,无需每个<td>单独配置,局部LTR内容单独加dir="ltr"即可,优化后的HTML示例:
<html dir="rtl"> <head> <style> .arabic { font-family: 'Noto Naskh Arabic'; } .french { font-family: Arial; direction: ltr; } </style> </head> <body> <table> <tbody> <tr> <td class="arabic">قرأت جميع بنود المدونة خلف هذا العقد المكتوبة بالفرنسية و قبلت بها و أتحمل مسؤولية السيارة خلال مدة هذا العقد</td> </tr> <tr> <td class="french">J'ai lu et j'accepte les formes mentionnées au recto et verso de présent contrat et du carnet de bord</td> </tr> <tr> <td class="arabic">شركة %currentUserName% لها كامل الصلاحية في إسترجاع سيارتها في أي وقت وذلك وبدون أي تعويض</td> </tr> <tr> <td class="french">La Sté %currentUserName% se réserve le plein droit de récupérer la voiture à tous moment sans justif ni indermnité</td> </tr> </tbody> </table> </body> </html>
生效验证
修改代码后重新运行转换流程,即可看到阿拉伯语文本正常从右到左排版,语序、连字显示符合预期。
内容的提问来源于stack exchange,提问作者Simo
相关产品推荐
相关产品推荐

