Unable to save Arabic words in a PDF - PDFBox Java

That's how I made it work, I hope it would help others. Just use the font that is supported by the language that you want to use in the PDF.

public static void main(String[] args) throws IOException
{
  String formTemplate = "myFormPdf.pdf";

  try (PDDocument pdfDocument = PDDocument.load(new File(formTemplate)))
  {
    PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm();
    // you can read ttf from resources as well, this is just for testing 
    PDFont font = PDType0Font.load(pdfDocument,new File("/path/to/font.ttf"));
    String fontName = acroForm.getDefaultResources().add(pdfont).getName();
    if (acroForm != null)
    {
        PDTextField field = (PDTextField) acroForm.getField( "sampleField" );
        field.setDefaultAppearance("/"+fontName +" 0 Tf 0 g");
        field.setValue("جملة");
    }

    pdfDocument.save("updatedPdf.pdf"); 
  }
}

Edited: Adding the comment of mkl The font name and the font size are parameters of the Tf instruction, and the gray value 0 for black is the parameter for the g instruction. Parameters and instruction names must be appropriately separated.

Tags:

Java

Pdfbox