【问题标题】:How to write unicode text to pdf with pdfbox?如何使用 pdfbox 将 unicode 文本写入 pdf?
【发布时间】:2014-10-20 22:09:54
【问题描述】:

我尝试使用Apache PDFBox 1.8.6Java 中创建PDF。 (见下面的代码)

如果我写字符串:Hello! 123 abc äöüß 一切正常。
但是,如果我添加一个 € 符号或等效的 \u20ac,则字符串会变得混乱:
þÿ H e l l o ! 1 2 3 a b c ä ö ü ß ¬ ¬ ¦
我认为这与编码有关,因为像 OpenOffice 这样的程序可以毫无问题地导出带有 € 或其他 Unicode 符号的 pdf。

那么我必须怎么做才能将 Unicode 字符串写入 PDF?

try {
        PDDocument doc = new PDDocument();
        PDPage page = new PDPage();
        doc.addPage(page);
        PDPageContentStream stream = new PDPageContentStream(doc, page);
        PDFont font = PDType1Font.COURIER;
        //font.setFontEncoding(new EncodingManager().getEncoding(COSName.WIN_ANSI_ENCODING));
        stream.setFont(font, 14);
        stream.beginText();
        stream.setNonStrokingColor(Color.BLACK);
        stream.moveTextPositionByAmount(20, 750);
        String text = "Hello! 123 abc äöüß € \u20ac";
        //JOptionPane.showMessageDialog(null, text);
        stream.drawString(text);
        stream.endText();
        stream.stroke();
        stream.close();
        doc.save("test.pdf");
        doc.close();
    } catch (Exception ex) {
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    }

【问题讨论】:

标签: java pdf pdfbox


【解决方案1】:

显然,PDFBox 不支持 Unicode 字体。也就是说,直到现在:this bug 被大佬修复后,PDFBox 2.0.0 的主干完美地显示了我的 Unicode。

【讨论】:

  • 太棒了,这很有帮助
猜你喜欢
  • 2015-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-29
  • 2012-12-11
  • 2018-11-05
  • 1970-01-01
  • 2015-03-23
相关资源
最近更新 更多