gpt4 book ai didi

java - 使用 ITextRenderer pdf 中没有中文单词

转载 作者:太空宇宙 更新时间:2023-11-04 09:32:29 26 4
gpt4 key购买 nike

我正在使用 ItextRenderer 将 html 转换为 pdf,它适用于西类牙语、法语单词,但当我尝试输入中文单词时,它不会出现在 PDF 中

  ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(html);
renderer.layout();

我尝试添加字体但仍然不起作用

   renderer.getFontResolver().addFont("C:\\Windows\\Fonts\\mingliu.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

renderer.getFontResolver().addFont("C:\\Windows\\Fonts\\simsun.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

renderer.getFontResolver().addFont("C:\\Windows\\Fonts\\batang.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

renderer.setDocumentFromString(html);
renderer.layout();
OutputStream os =
Files.newOutputStream(Paths.get("chinese.pdf"));
renderer.createPDF(os);

最佳答案

为了管理中文单词,您需要以下3个库:

        <dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.11</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.11</version>
</dependency>

汉字编码的核心部分是用正确的亚洲字体解析html字符串,核心代码如下:

    void createPDF(final String content, final String filename) {
final Document document = new Document(PageSize.LETTER);
try {
PdfWriter writer = PdfWriter.getInstance(document, Files.newOutputStream(Paths.get("target", filename)));
document.open();
InputStream input = new ByteArrayInputStream(content.getBytes());
XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
worker.parseXHtml(writer, document, input, Charset.forName("UTF-8"), new AsianFontProvider());
} catch (DocumentException | IOException e) {
log.error("Failed to generate PDF for {}", filename, e);
} finally {
document.close();
}
}
class AsianFontProvider extends XMLWorkerFontProvider {
@Override
public Font getFont(final String fontName, final String encoding, final boolean embedded, final float size, final int style, final BaseColor color) {
try {
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font font = new Font(bf, size, style, color);
font.setColor(color);
return font;
} catch (DocumentException | IOException e) {
log.error("Failed to create font for {} with encoding {}", fontName, encoding, e);
throw new IllegalArgumentException("incorrect font creation, please check the font parameters", e);
}
}
}

更多详情,可以访问我的github,我创建了一个mini project对于这个问题:

关于java - 使用 ITextRenderer pdf 中没有中文单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56913007/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com