Tuesday, July 31, 2018

Using Pdfbox to fill PDF template with data which might be in Arabic

Hello,

In my previous post I shared how we can create a pdf and write in Arabic in it.

However, in many cases there is a need to fill a pdf template with data and that is prone to mistakes, time consuming and boring too. So, in order to rectify this it is better to keep the data in a database and generate the form pre-populated with the static data then worry about adding the additional data only.

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

Download arial.ttf from here

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.File;
import java.io.IOException;
import org.apache.fontbox.ttf.TrueTypeFont;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDTrueTypeFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDTextField;

public class PDFtester {

    public static void main(String[] args) throws IOException, ArabicShapingException {

        PDDocument doc = PDDocument.load(new File("c:\\data\\letters\\letter.pdf"));
        PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm();
        PDResources formResources = acroForm.getDefaultResources();

        PDType0Font font = PDType0Font.load(doc, new File("C:\\data\\arial.ttf"));

        formResources.put(COSName.getPDFName("F0"), font);
        String s = "نحن معشر الانبياء امرنا ان نخاطب الناس على قدر عقولهم";
        PDTextField formField = (PDTextField) acroForm.getField("15");
        formField.setDefaultAppearance("/F0 0 Tf 0 g");
        formField.setValue(new StringBuilder(new ArabicShaping(ArabicShaping.LETTERS_SHAPE).shape(s)).reverse().toString());

        doc.save("c:\\data\\letters\\filling.pdf");
        doc.close();
    }
}


There is a small glitch in the pdf document which that when you click inside the field letters are getting disconnected and style converts into LTR (Left to Right). I am working on figuring the issue, but the pdf is printable and it will work fine.

No comments:

Post a Comment