使用ITextRenderer从HTML生成pdf文件时编码问题

时间:2012-04-19 15:13:49

标签: java pdf encoding itext

我正在尝试使用包含非拉丁字符的ITextRenderer生成pdf文档。就我而言,这里是保加利亚语。

在调用ITextRenderer之前,我有一个 String内容,在某些进程之后(比如使用tidy解析)看起来就像那样(我能通过调试看到这个值)

刺痛内容

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

以上只是我的String的一部分。此内容包含有效的html语法。我只是把它的一小部分放在这里来澄清,直到这一部分,我的编码是正确的,因为我能够阅读保加利亚字符。

之后,会出现以下代码,用于创建文档,将其放入 itextrenderer 并生成 pdf 文件。由于我能够成功生成英语语言的pdf文件,因此该代码已经经过测试并正常工作用于 lating characters 的内容。

当我使用非拉丁字符切换其他语言(保加利亚语)时出现问题。生成的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

中运行

任何帮助将不胜感激。

Thanx

1 个答案:

答案 0 :(得分:1)

您的HTML是否指定了UTF-8编码?您的字体文件是否在该路径中找到?

通过提供系统中字体默认位置的路径,查看this gist表示它适用于Linux上的中文字符。

相关问题