Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - generate unicode pdf with Apache PDFBox

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.

like image 378
hamed Avatar asked Jul 06 '26 14:07

hamed


1 Answers

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.

like image 56
Tilman Hausherr Avatar answered Jul 08 '26 06:07

Tilman Hausherr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!