java - generate unicode pdf with Apache PDFBox

▼魔方 西西 提交于 2019-12-23 20:56:21

问题


I have to generate pdf in my spring mvc application. recently I tested iTextPdf library, but i could not generate unicode pdf document. in fact I didn't see non-latin characters in the generated document. I decided to use Apache PDFBox for my purpose, but I don't know has it support unicode characters? If has, is there any good tutorial for learning pdfBox? And If not, which library should I use? Thanks in advance.


回答1:


The 1.8.* versions don't support PDF generation with Unicode, but the 2.0.* versions do. This is the example EmbeddedFonts.java:

public class EmbeddedFonts
{
    public static void main(String[] args) throws IOException
    {
        PDDocument document = new PDDocument();
        PDPage page = new PDPage(PDRectangle.A4);
        document.addPage(page);

        String dir = "../pdfbox/src/main/resources/org/apache/pdfbox/resources/ttf/";
        PDType0Font font = PDType0Font.load(document, new File(dir + "LiberationSans-Regular.ttf"));

        PDPageContentStream stream = new PDPageContentStream(document, page);

        stream.beginText();
        stream.setFont(font, 12);
        stream.setLeading(12 * 1.2);

        stream.newLineAtOffset(50, 600);
        stream.showText("PDFBox Unicode with Embedded TrueType Font");
        stream.newLine();

        stream.showText("Supports full Unicode text ?");
        stream.newLine();

        stream.showText("English русский язык Tiếng Việt");

        stream.endText();
        stream.close();

        document.save("example.pdf");
        document.close();
    }
}

Note that unlike iText, PDFBox support for PDF creation is very low level, i.e. we don't support paragraphs or tables out of the box. There is no tutorial, but a lot of examples. The API orients itself on the PDF specification.




回答2:


The current version of Apache PDFBox can't deal with Unicode, see: https://pdfbox.apache.org/ideas.html

iTextPdf v. 5.x generates pdf files with Unicode. There is an exemple here: iText in Action: Chapter 11: Choosing the right font part3.chapter11.UnicodeExample http://itextpdf.com/examples/iia.php?id=199

To run it, you just need to adapt the value of EncodingExample.FONT and to add some code to create the output file.



来源:https://stackoverflow.com/questions/28133789/java-generate-unicode-pdf-with-apache-pdfbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!