【问题标题】:Converting .pptx to .pdf with itextpdf. Bad character positioning with chinese characters使用 itextpdf 将 .pptx 转换为 .pdf。汉字定位不好
【发布时间】:2018-04-07 00:29:43
【问题描述】:

在我的服务器上将 .pptx 幻灯片转换为 .pdf 文档时遇到问题。我将 itextpdf 5.5.10 和 apache poi 3.15 用于 .pptx 文件。如果文本中包含汉字,则所有字符的定位都不好。在我的本地机器(Windows 7)上我没有问题。这是我机器上的样子

这就是它在服务器上的样子(安装了 ubuntu 字体系列的 CentOS Linux 版本 7.4.1708 (Core))

这是我用来进行转换的 (java) 代码:

PdfContentByte canvas = writer.getDirectContent();
UnicodeFontMapper mapper = new UnicodeFontMapper();
    for (XSLFSlide slide : ppt.getSlides()) {
        PdfTemplate template = canvas.createTemplate(width, height);
        Graphics2D g2d = new PdfGraphics2D(template, width, height, mapper);
        // default rendering options
        DrawFactory.getInstance(g2d).fixFonts(g2d);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
        //Draw slide
        slide.draw(g2d);
        canvas.addTemplate(template, 0, 0);
        g2d.dispose();
        document.newPage();
    }

UnicodeFontMapper 类:

public class UnicodeFontMapper extends DefaultFontMapper {

@Override
public BaseFont awtToPdf(Font font) {
    //using own fonts
    String fontFamily = "ArialUni";
    registerFontFamily(fontFamily);
    int style = com.itextpdf.text.Font.NORMAL;
    if (font.isBold()) {
        if (font.isItalic()) {
            style = com.itextpdf.text.Font.BOLDITALIC;
        } else {
            style = com.itextpdf.text.Font.BOLD;
        }
    }
    com.itextpdf.text.Font pdfFont = FontFactory.getFont(fontFamily, BaseFont.IDENTITY_H, true, font.getSize(), style);
    return pdfFont.getBaseFont();
}

我使用 ArialUni.ttf 字体。据我了解,我的服务器上缺少一些东西,但我无法弄清楚到底是什么。

【问题讨论】:

    标签: java unicode fonts itext apache-poi


    【解决方案1】:

    Arial unicode 并非在所有系统上都存在。 这可能会导致 iText 无法呈现您在该字体中指定的字符。 (类似地,如果字体不包含字形)。

    (可选)如果您使用的是 OpenJDK,您可能希望了解 graphics2D 的工作原理。也许您在 Windows 上使用 Oracle 的 JDK 版本,在 CentOS 上使用 OpenJDK。尽管 JDK 的两个版本应该以相同的方式工作,但在某些方面可能存在细微差别,例如 Graphics2D

    您可以通过运行java -version轻松检查您使用的JDK版本

    【讨论】:

    • 谢谢。在服务器上安装 arialuni.ttf 解决了这个问题。我很困惑,没有考虑它,因为字符是用正确的字形渲染的,但位置错误,所以我认为需要的字体已经安装在服务器上。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    • 2016-07-16
    • 2021-01-15
    • 2018-01-01
    • 2017-10-23
    • 2021-05-31
    • 1970-01-01
    相关资源
    最近更新 更多