Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
982 views
in Technique[技术] by (71.8m points)

java - How to write unicode text to pdf with pdfbox?

I try to use Apache PDFBox 1.8.6 to create a PDF in Java. (See code below)

If I write the string: Hello! 123 abc ??ü? everything works fine.
But if I add an € sign or it's equivalent u20ac the String gets messed up:
t? H e l l o ! 1 2 3 a b c ? ? ü ? ? ? |
I think this has something to do with the encoding, since programms like OpenOffice can export pdf with € or other Unicode signs without a problem.

So what do I have to do to write Unicode String to 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);
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Apparently, PDFBox did not support Unicode fonts. That is, until now: after this bug has been fixed by a great guy, the trunk of PDFBox 2.0.0 shows my Unicode perfectly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...