Я использую Apache PDFBox для создания PDF-файла с полями формы и встраивания собственного шрифта TrueType (FreeSans.ttf) с включенным поднабором. Однако, когда я устанавливаю значение в текстовом поле, вместо фактического текста отображаются бессмысленные символы.
Версии: 2.x, 3.x
Шрифты: любые шрифты, загруженные из внешнего источника, кроме 14 стандартных шрифтов.
Воспроизводимый пример:
package org.example;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDTextField;
import java.io.InputStream;
public class Main {
public static void main(String[] args) {
try (PDDocument document = new PDDocument()) {
PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);
PDAcroForm acroForm = new PDAcroForm(document);
document.getDocumentCatalog().setAcroForm(acroForm);
// Load external TrueType font with subsetting enabled
PDType0Font font;
try (InputStream fontStream = Main.class.getResourceAsStream("/FreeSans.ttf")) {
if (fontStream == null) {
throw new RuntimeException("FreeSans.ttf not found in resources");
}
font = PDType0Font.load(document, fontStream, true);
}
// Add font to form resources
PDResources formResources = new PDResources();
String fontResourceName = formResources.add(font).getName();
acroForm.setDefaultResources(formResources);
acroForm.setDefaultAppearance("/" + fontResourceName + " 12 Tf 0 0 0 rg");
// Create text field with value
PDTextField textField = new PDTextField(acroForm);
textField.setPartialName("testField");
textField.setDefaultAppearance("/" + fontResourceName + " 12 Tf 0 0 0 rg");
// Set widget rectangle and add to page
textField.getWidgets().get(0).setRectangle(new PDRectangle(100, 700, 200, 20));
textField.getWidgets().get(0).setPage(page);
page.getAnnotations().add(textField.getWidgets().get(0));
acroForm.getFields().add(textField);
textField.setValue("Hello, this is a filled form field!");
acroForm.setNeedAppearances(false);
acroForm.refreshAppearances();
document.save("output.pdf");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Вывод на консоль:
WARNING: Using fallback font LiberationSans for CID-keyed TrueType font FreeSans
WARNING: widget of field testField has no rectangle, no appearance stream created
Подробнее здесь: https://stackoverflow.com/questions/798 ... etype-font