itext - 如何用希伯来语生成 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出来是空白的
解决方案
我更改了您的代码的一些细节,现在我明白了:
我的变化:
嵌入字体
由于我的系统上没有安装 Rubik,我必须将字体嵌入到 PDF 中才能有机会看到任何内容。因此,我在创建时替换BaseFont.NOT_EMBEDDED
为:BaseFont.EMBEDDED
var 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)下载字体时,您可以在选择抽屉的自定义选项卡中看到默认情况下只有拉丁字符包含在下载中,特别是不包含希伯来语的:
我使用下载的字体文件进行了测试,并启用了所有语言选项:
推荐阅读
- javascript - HTML5 网页音频的 JavaScript 代码,用于读取播放列表并填充六个数组
- python - 在 Raspberry Pi 上使用 python 套接字时的非线性/不一致 sendall() 时间
- html - 如何使用 css 将第一个 iframe 定位到第五个 iframe?
- arduino - Raspberry Pi 4 和 Arduino BLE 33 之间的蓝牙通信失败
- reactjs - 如何修复 React Hook useEffect 缺少依赖项:
- java - 通过套接字将图像从 python opencv numpy ndarray 传输到 java 缓冲图像
- bigdata - 如何在 Kusto 中运行预定功能?
- intellij-idea - 这个 IntelliJ 功能的名称是什么?
- vue.js - 如何参考 Vue 3 原型?
- android - 在我的片段中设置适配器以使其工作