使用itextpdf将.pptx转换为.pdf。中文字符定位不好

时间:2017-10-25 19:20:57

标签: java unicode fonts itext apache-poi

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

enter image description here

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

这是我用来进行转换的(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字体。据我了解,我在服务器上遗漏了一些东西,但我无法弄清楚到底是什么。

1 个答案:

答案 0 :(得分:3)

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

或者,如果您使用的是OpenJDK,您可能需要查看graphics2D的工作方式。也许您在Windows上使用Oracle的JDK版本,在CentOS上使用OpenJDK。虽然JDK的两个版本都应该以相同的方式工作,但某些方面可能存在细微差别,例如Graphics2D

您可以通过运行java -version

轻松检查所使用的JDK版本
相关问题