3

我正在尝试使用包含非拉丁字符的 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,并且此代码在 Controller 中运行

任何帮助将不胜感激。

谢谢

4

0 回答 0