Search code examples
javaspring-bootunicodearabicopenpdf

How to write Arabic text in a PDF using OpenPDF and Java


I use OpenPDF to generate a PDF from a Spring Boot application. Everything works fine when I use French or English alphabets, but when I write in Arabic nothing is displayed.

I read that I have to use the Unicode form for the Arabic words. For example, the Arabic word الاسم converted to its Unicode form gives the following string:

\u0627\u0644\u0627\u0633\u0645

So I am wondering whether there is any way to convert Arabic words to Unicode in Java, and could I use that approach with OpenPDF? Or is there any alternative way to write Arabic in a PDF using OpenPDF and Java 17/Spring Boot?


Solution

  • This example of writing Arabic text to a PDF using OpenPDF solves my problem. (RightToLeft.java in the OpenPDF documentation.)

    The main idea is to create a BaseFont that supports Arabic text, as shown on line 51:

    BaseFont bf = BaseFont.createFont("c:\\windows\\fonts\\times.ttf", BaseFont.IDENTITY_H, true);
    

    You can replace that .ttf file supporting Arabic text with your own file. You put it in the resources folder, and name it like this: src/main/resources/youTtfFile.ttf.

    You also need to specify right to left (RTL) directionality, as shown on line 61:

    ct.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);