Monday, July 30, 2018

Using Java and Pdfbox to create PDF with Arabic text

Hello,

I am writing this post to demonstrate how to create pdf file using pdfbox library, more importantly how to write in Arabic in it which is not very common topic people talk about.

Simply, the below represents the code to do that, and depending on your scenario you can dig more on the rest of the library, it is open source and very rich.

Prerequisites:
-pdfbox v.2.0.11
-ICU v.62
-arial.ttf

You can download pdfbox-app-2.0.11.jar which is the latest as of the time I am writing this post from here.

You can download ICU from here

You can download arial.ttf from here and put it in c:\data\ for the example to work

Go to netbeans or the IDE you are using and them to your Libraries and create the below desktop program.

package pdftester;

import com.ibm.icu.text.ArabicShaping;
import com.ibm.icu.text.ArabicShapingException;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDTrueTypeFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;

public class PDFtester {

    public static void main(String[] args) {

        PDDocument doc = new PDDocument();
        PDPage page = new PDPage();
        doc.addPage(page);
        PDPageContentStream pageContentStream;
        try {
            pageContentStream = new PDPageContentStream(doc, page);
            pageContentStream.beginText();
            pageContentStream.setFont(PDType0Font.load(doc, new File("c:\\data\\arial.ttf")), 20);
            pageContentStream.newLineAtOffset(250, 750);
            String s = "سامر احمد";
            pageContentStream.showText(new StringBuilder(new ArabicShaping(ArabicShaping.LETTERS_SHAPE).shape(s)).reverse().toString());
            pageContentStream.endText();
            pageContentStream.close();
            doc.save("c:\\data\\test.pdf");
            doc.close();
        } catch (IOException ex) {
            Logger.getLogger(PDFtester.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ArabicShapingException ex) {
            Logger.getLogger(PDFtester.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

1 comment: