gpt4 book ai didi

java - 使用ITextRenderer从HTML生成pdf文件时出现编码问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:13:35 24 4
gpt4 key购买 nike

我正在尝试使用包含非拉丁字符的itextrenderer生成pdf文档。在我看来,这是保加利亚人。
在调用itextrenderer之前,我有一个字符串内容,在一些进程之后(比如用tidy解析)看起来是这样的(我可以通过调试看到这个值)
刺入内容:

td class="description">Вид на потока</td>
td class="description">Статус на потока</td>

以上只是我的一部分。此内容包含有效的HTML语法。我只是在这里放了一小部分来澄清,直到这一部分,我的编码是正确的,因为我能够阅读保加利亚字符。
之后,将执行以下代码来创建文档,将其放入itextrenderer并生成pdf文件。这段代码已经过测试,并且可以处理拉丁字符的内容,因为我能够成功地为英语生成一个pdf文件。
当我用另一种语言(保加利亚语)切换非拉丁字符时,问题就出现了。生成的pdf将忽略所有保加利亚字符,最终结果是一个包含许多空行的pdf。这是生成pdf的部分代码
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

dbf.setValidating(false);
dbf.setNamespaceAware(false);
dbf.setFeature("http://xml.org/sax/features/namespaces", false);
dbf.setFeature("http://xml.org/sax/features/validation", false);
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

DocumentBuilder builder = dbf.newDocumentBuilder();

Document doc = builder.parse(new ByteArrayInputStream(content.getBytes("UTF-8")));

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
InputStream is = null;

ITextRenderer renderer = new ITextRenderer();

renderer.getFontResolver().addFont("fonts/TIMES.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
renderer.getFontResolver().addFont("fonts/TIMESBD.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
renderer.getFontResolver().addFont("fonts/TIMESBI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
renderer.getFontResolver().addFont("fonts/TIMESI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);


renderer.setDocument(doc, null);
renderer.layout();
renderer.createPDF(outputStream);
outputStream.close();


byte[] outputBytes = outputStream.toByteArray();
is = new ByteArrayInputStream(outputBytes);
response.setContentType("application");
response.addHeader("Content-Disposition", "attachment; filename=\"" + "exported.pdf" + "\"");
response.setContentLength(outputBytes.length);
response.getOutputStream().write(inputStreamToBytes(is));

我已经尝试了几件事(主要与编码有关),但不幸的是,我还没有找到解决方案。可能我遗漏了一些显而易见的东西:)
我不确定这是否会增加任何价值,但我使用的是spring,这段代码在控制器中运行
任何帮助都将不胜感激。
桑克斯

最佳答案

您的html是否指定了utf-8编码?你的字体文件在那个路径中找到了吗?
请看一下this gist,它通过提供到系统中字体默认位置的路径,在linux上对汉字有效。

关于java - 使用ITextRenderer从HTML生成pdf文件时出现编码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10231194/

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