Search code examples
javafontspdfbox

Java Unable to load arabic character U+062C into PDF on PDFBox even though it exists on the font


The font I am using is an arial.tff. Aside from this specific character (U+062C) all the other characters seem to be working fine.

Somehow when it reaches this point it just throws:

java.lang.IllegalArgumentException: U+062C ('afii57420') is not available in this font Helvetica (generic: ArialMT) encoding: StandardEncoding with differences

Code below:

PDFont font = PDType0Font.load(pdfDocumentTemplate, this.resourceLoader.getResource("classpath:arial.ttf").getInputStream(), false);
PDAcroForm pdAcroForm = pdAcroFormOptional.get();
String fontName = pdAcroForm.getDefaultResources()
                            .add(font)
                            .getName();

for (GenerateDocumentPlaceholder placeholder : command.getPlaceholderList()) {
    PDTextField field = (PDTextField) pdAcroForm.getField(placeholder.getName());
    try {
        if (field != null) {
            field.setDefaultAppearance("/" + fontName + " 0 Tf 0 g");
            field.setValue(placeholder.getValue());
        }
    } catch (Exception ex) {
        log.error("Error while updating field {}", placeholder.getValue(), ex);
    }
}

And here's the font with the character: enter image description here

Any ideas?


Solution

  • Fixed by replacing the embedded resources within pdf by doing this:

    private String getPdfFontName(PDAcroForm pdAcroForm, PDDocument pdfDocumentTemplate, String resource) throws ConstraintViolatedException {
            String fontName = "";
            try {
                PDResources pdResources = new PDResources();
                pdAcroForm.setDefaultResources(pdResources);
                PDFont font = PDType0Font.load(pdfDocumentTemplate, this.resourceLoader.getResource(resource).getInputStream());
                pdResources.put(COSName.getPDFName("Helv"), font);
                fontName = pdResources.add(font).getName();
            } catch (Exception ex) {
                log.warn("Error while adding arabic font", ex);
            }
            return fontName;
        }
    

    And then using it like this:

            String fontName = this.getPdfFontName(pdAcroForm, pdfDocumentTemplate, "classpath:Arial.ttf");
    
            for (GenerateDocumentPlaceholder placeholder : command.getPlaceholderList()) {
                PDTextField field = (PDTextField) pdAcroForm.getField(placeholder.getName());
                try {
                    if (field != null) {
                        field.setDefaultAppearance("/" + fontName + " 0 Tf 0 g");
                        field.setValue(placeholder.getValue());
                 } catch (Exception ex) {
                        log.error("Error while updating field {}", placeholder.getValue(), ex);
                 }
            }