1

我有一个带有中文/韩文字符的 HTML 字符串。我想使用 iText 将 HTML 转换为 PDF。我已经读到我们需要将 FONT 嵌入到 PDF 中以使 unicode 字符显示在 PDF 上。

当我尝试嵌入 wts11.ttf(使用编码 IDENTITY_H)或 STSong-Light(使用 encodingUniGB-UCS2-H)时,我只能看到中文字符,但看不到韩文字符。我尝试使用 arialuni.ttf(使用编码 IDENTITY_H),但仍然只能看到中文字符而看不到韩文。

有人可以告诉我确切的字体应该是什么。或者,如果我遗漏了什么。

下面是代码片段:

Document document = new Document();
Paragraph paragraph=new Paragraph();
PdfWriter.getInstance(document, baos);
document.open();
BaseFont bff = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
Font f = new Font(bff);

// FontFactory.registerDirectories(); 
// Font f = FontFactory.getFont("Arial Unicode MS", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

document.add(new Paragraph());
HTMLWorker htmlWorker = new HTMLWorker(document);

List<Element> objects=htmlWorker.parseToList(new StringReader(message),null);
paragraph.setFont(f);
for (Element elem : objects) {
    paragraph.add(elem);
}
document.add(paragraph);
4

2 回答 2

1

如果升级到使用 XML Worker,有不同的方法可以解决这个问题。

我重用了官方示例中的代码,更具体地说是ParseHtmlAsian示例,并调整了用作此示例源代码的 HTML,如下所示:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    </head>
    <body>
    <p><span style="font-size:12.0pt; font-family:MS Mincho">長空</span>
    <span style="font-size:12.0pt; font-family:Times New Roman,serif">(Broken Sword),</span>
    <span style="font-size:12.0pt; font-family:MS Mincho">秦王殘劍</span>
    <span style="font-size:12.0pt; font-family:Times New Roman,serif">(Flying Snow),</span>
    <span style="font-size:12.0pt; font-family:MS Mincho">飛雪</span>
    <span style="font-size:12.0pt; font-family:Times New Roman,serif">(Moon), </span>
    <span style="font-size:12.0pt; font-family:MS Mincho">如月</span>
    <span style="font-size:12.0pt; font-family:Times New Roman,serif">(the King), and</span>
    <span style="font-size:12.0pt; font-family:MS Mincho">秦王</span>
    <span style="font-size:12.0pt; font-family:Times New Roman,serif">(Sky).</span></p>
    <p style="font-size: 12.0pt; font-family:Batang">빈집</p>
    <p>Test</p>
    </body>
</html>

结果如下所示:

在此处输入图像描述

如您所见,所有文本均已正确呈现,因此请不要传播诸如“iText 未呈现中文/韩文字符”之类的错误消息;-)

请将此答案转发给您的管理层,以便您的 CTO 了解在旧 iText 版本上投入时间比购买使用新 iText 版本的许可证更昂贵。

于 2015-01-09T18:44:03.480 回答
0
  1. 下载 Malgun-Gothic-Bold_29380.ttf 字体。
  2. 将其存储在asset->fonts->Malgun-Gothic-Bold_29380.ttf 字体中
  3. 此代码适用于 cjk 和 English 和 vitenames

字体 fontbold=FontFactory.getFont("assets/fonts/Malgun-Gothic-Bold_29380.ttf", BaseFont.IDENTITY_H,BaseFont.EMBEDDED, 12);

于 2016-02-05T12:15:29.663 回答