首页 > 解决方案 > 如何用希伯来语生成 PDF?目前生成的 PDF 为空

问题描述

我正在使用 iTextSharp 5.5.13,当我尝试使用希伯来语生成 PDF 时,它显示为空。这是我的代码:我做错了什么?

    public byte[] GenerateIvhunPdf(FinalIvhunSolution ivhun)
    {
        byte[] pdfBytes;
        using (var mem = new MemoryStream())
        {
            Document document = new Document(PageSize.A4);
            PdfWriter writer = PdfWriter.GetInstance(document, mem);
            writer.PageEvent = new MyHeaderNFooter();
            document.Open();
            var font = new 
            Font(BaseFont.CreateFont("C:\\Downloads\\fonts\\Rubik-Light.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED), 14);
            Paragraph p = new Paragraph("פסקת פתיחה")
            {
                Alignment = Element.ALIGN_RIGHT

            };
            PdfPTable table = new PdfPTable(2)
            {
                RunDirection = PdfWriter.RUN_DIRECTION_RTL
            };
            PdfPCell cell = new PdfPCell(new Phrase("מזהה", font));
            cell.BackgroundColor = BaseColor.BLACK;
            table.AddCell(cell);

            document.Add(p);
            document.Add(table);
            document.Close();
            pdfBytes = mem.ToArray();

        }
        return pdfBytes;
    }

PDF出来是空白的

标签: itext

解决方案


我更改了您的代码的一些细节,现在我明白了:

截屏

我的变化:

嵌入字体

由于我的系统上没有安装 Rubik,我必须将字体嵌入到 PDF 中才能有机会看到任何内容。因此,我在创建时替换BaseFont.NOT_EMBEDDED为:BaseFont.EMBEDDEDvar font

var font = new Font(BaseFont.CreateFont("Rubik-Light.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 14);

Paragraph那种工作

您在Paragraph p不指定字体的情况下创建。因此,使用具有默认编码的默认字体。默认编码是WinAnsiEncoding,它类似于 Latin1,因此无法表示希伯来字符。我将您的 Rubik 字体实例添加到Paragraph p创建中:

Paragraph p = new Paragraph("פסקת פתיחה", font)
{
    Alignment = Element.ALIGN_RIGHT
};

等等,文字出现了。

iText 开发人员经常表示,在 iText 5.x 和更早的版本中,从右到左的脚本仅在某些上下文中得到正确支持,例如在表格中,但在其他情况下,例如立即添加到文档中的段落中不支持。当您Paragraph p立即添加到 中时Document document,其字母在输出中以错误的顺序出现。

制作PdfPTable作品

您将 定义PdfPTable table为有两列 ( new PdfPTable(2)),但随后只添加了一个单元格。因此,table甚至不包含一个完整的行。因此,iText 在添加到文档时不会绘制任何内容。

我将定义更改为table只有一列:

PdfPTable table = new PdfPTable(1)
{
    RunDirection = PdfWriter.RUN_DIRECTION_RTL
};

此外,我注释掉了将单元格背景设置为黑色的行,因为通常很难在黑色上阅读黑色:

PdfPCell cell = new PdfPCell(new Phrase("מזהה", font));
//cell.BackgroundColor = BaseColor.BLACK;
table.AddCell(cell);

文字再次出现。

正确下载字体

另一个可能的障碍是,从您提供的 URL(https://fonts.google.com/selection?selection.family=Rubik)下载字体时,您可以在选择抽屉的自定义选项卡中看到默认情况下只有拉丁字符包含在下载中,特别是不包含希伯来语的:

截屏

我使用下载的字体文件进行了测试,并启用了所有语言选项:

截图,全选


推荐阅读