You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Itext7 Xamarin Form中阿拉伯字体排版及RTL设置失效问题

解决iText7阿拉伯文显示异常问题(单字母拆分、RTL布局失效)

问题核心

阿拉伯文属于复杂书写脚本,需要iText7启用复杂文本排版支持,仅设置字体和表格方向不足以正确渲染连写字符与RTL布局。

修复步骤

1. 替换为完整支持阿拉伯文的字体

常规Arial字体对阿拉伯文连写的支持不完整,建议改用Arial Unicode MS或专门的阿拉伯字体(如Amiri、Scheherazade)。修改字体调用代码:

PdfFont font = GetFont("ArialUnicodeMS.ttf", "ArialUnicodeMS");

2. 启用OpenType复杂脚本处理

在创建字体时需明确开启复杂脚本支持,修改GetFont方法的返回逻辑:

// 修改GetFont方法的返回语句
FontProgram fontProgram = FontProgramFactory.CreateFont(fontBytes);
if (fontProgram is OpenTypeFontProgram otf) {
    otf.SetAdvancedFeatures(true); // 启用连写、字形变换等复杂排版特性
}
return PdfFontFactory.CreateFont(fontProgram, PdfEncodings.IDENTITY_H, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED);

3. 为文本元素单独配置RTL属性

表格的SetBaseDirection仅控制列的排列方向,每个文本元素(Paragraph、Cell)需要单独设置RTL与对齐:

// 创建单元格时配置文本方向
Cell arabicCell = new Cell()
    .Add(new Paragraph("النص العربي المثال")
        .SetFont(font)
        .SetBaseDirection(BaseDirection.RIGHT_TO_LEFT)
        .SetTextAlignment(TextAlignment.RIGHT));
table1.AddCell(arabicCell);

4. 确保表格RTL配置生效

保留表格的方向设置,同时确保单元格添加顺序符合RTL逻辑(或依赖iText自动反转列顺序):

Table table1 = new Table(5, true);
table1.SetBaseDirection(BaseDirection.RIGHT_TO_LEFT);
table1.SetWidth(new UnitValue(UnitValue.PERCENT, 100));

完整修复后代码片段

public PdfFont GetFont(string filename)
{
    var assembly = typeof(ResultVehicleCheckList).GetTypeInfo().Assembly;
    var fontStream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.Assets.Fonts.{filename}");
    byte[] fontBytes;

    using (var memoryStream = new MemoryStream())
    {
        fontStream.CopyTo(memoryStream);
        fontBytes = memoryStream.ToArray();
    }

    FontProgram fontProgram = FontProgramFactory.CreateFont(fontBytes);
    if (fontProgram is OpenTypeFontProgram otf)
    {
        otf.SetAdvancedFeatures(true);
    }
    return PdfFontFactory.CreateFont(fontProgram, PdfEncodings.IDENTITY_H, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED);
}

// 初始化与使用示例
PdfFont arabicFont = GetFont("ArialUnicodeMS.ttf");
Table table1 = new Table(5, true);
table1.SetBaseDirection(BaseDirection.RIGHT_TO_LEFT);
table1.SetWidth(new UnitValue(UnitValue.PERCENT, 100));

// 添加阿拉伯文单元格
Cell sampleCell = new Cell()
    .Add(new Paragraph("مثال على نص عربي")
        .SetFont(arabicFont)
        .SetBaseDirection(BaseDirection.RIGHT_TO_LEFT)
        .SetTextAlignment(TextAlignment.RIGHT));
table1.AddCell(sampleCell);

内容的提问来源于stack exchange,提问作者ABM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 06:40:23