U+0413 is not available in this font's encoding: WinAnsiEncoding

93 Views Asked by At

I have a PDF with a textField with the name "lastname" and I want to fill it with this value: Горохова

Using PDFBox version 2.0.30 and java.

Here is my code:

public void fillDocument() throws IOException {
    // Create a new document with an empty page.
    PDDocument doc = PDDocument.load(new File("InputPdf.pdf"));
    PDFont formFont = PDType0Font.load(doc, Myclass.class.getResourceAsStream(
        "/org/apache/pdfbox/resources/ttf/LiberationSans-Regular.ttf"), false);
    PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm();
    final PDResources resources = new PDResources();
    acroForm.setDefaultResources(resources);
    final String fontName = resources.add(formFont).getName();
    String defaultAppearanceString = "/" + fontName + " 0 Tf 0 g"; // adjust to replace existing font name

    acroForm.setDefaultResources(resources);
    acroForm.setDefaultAppearance(defaultAppearanceString);
    PDTextField textField = (PDTextField) acroForm.getField("lastName");
    textField.setDefaultAppearance(defaultAppearanceString);
    textField.setValue("Горохова");
    doc.save("output.pdf");
}

But when it tries to set the value, it failed with the error:

java.lang.IllegalArgumentException: U+0413 is not available in this font's encoding: WinAnsiEncoding
    at org.apache.pdfbox.pdmodel.font.PDTrueTypeFont.encode(PDTrueTypeFont.java:398)
    at org.apache.pdfbox.pdmodel.font.PDFont.encode(PDFont.java:337)
    at org.apache.pdfbox.pdmodel.font.PDFont.getStringWidth(PDFont.java:368)
    at org.apache.pdfbox.pdmodel.interactive.form.PlainTextFormatter.format(PlainTextFormatter.java:195)
    at org.apache.pdfbox.pdmodel.interactive.form.AppearanceGeneratorHelper.insertGeneratedAppearance(AppearanceGeneratorHelper.java:567)
    at org.apache.pdfbox.pdmodel.interactive.form.AppearanceGeneratorHelper.setAppearanceContent(AppearanceGeneratorHelper.java:424)
    at org.apache.pdfbox.pdmodel.interactive.form.AppearanceGeneratorHelper.setAppearanceValue(AppearanceGeneratorHelper.java:248)
    at org.apache.pdfbox.pdmodel.interactive.form.PDTextField.constructAppearances(PDTextField.java:264)
    at org.apache.pdfbox.pdmodel.interactive.form.PDTerminalField.applyChange(PDTerminalField.java:227)
    at org.apache.pdfbox.pdmodel.interactive.form.PDTextField.setValue(PDTextField.java:219)

The fun fact is if I add a new page in the existing pdf with a PDTextField and the same value, it works.

0

There are 0 best solutions below