luckydonald
luckydonald

Reputation: 6856

Flattening PDF fields removes formatting

I try to flatten form fields (PDAcroForm.flatten()) in a pdf, which contain rich text. When doing so the formatting (bold, italics, color, size) get lost.

pdfs It's not edible any longer, but the formatting is also gone.

    String inputFileName = "test.pdf";

    String val = "<?xml version=\"1.0\"?>"
            + "<body xmlns=\"http://www.w3.org/1999/xhtml\">"
            +   "<p style=\"color:#FF0000;font-size:8pt;\">"
            +       "<i>Small</i> <b>Red</b>&#13;"
            +   "</p>"
            +   "<p style=\"color:#00FF00;font-size:20pt;\">"
            +       "<i>Big</i> <b>Green</b>&#13;"
            +   "</p>"
            + "</body>";
    String valNoFormat = "Small Red\rBig Green\r";

    PDDocument pdf_document = PDDocument.load(new File(inputFileName));
    PDAcroForm acroForm = pdf_document.getDocumentCatalog().getAcroForm();
    PDTextField acroField = (PDTextField)acroForm.getField("example_field_number_one");

    acroField.setValue(valNoFormat);
    acroField.setRichTextValue(val);

    acroForm.setNeedAppearances(true);
    pdf_document.save(new File("output01.pdf"));

    List<PDField> the_fields = new ArrayList<PDField>();
    for (PDField field: pdf_document.getDocumentCatalog().getAcroForm().getFieldTree()) {
        the_fields.add(field);
    }
    System.out.println("Flattening fields: " + Arrays.stream(the_fields.toArray()).map(field -> ((PDField)field).getFullyQualifiedName()).collect(Collectors.joining(", ","[","]")));
    acroForm.setNeedAppearances(true);
    pdf_document.getDocumentCatalog().getAcroForm().flatten(the_fields, true);
    pdf_document.save(new File("output02.pdf"));

Created that form elements with Adobe Acrobat Pro 10.1.1, via the form menu, and simply saved the pdfs as test.pdf.

For completeness sake I uploaded everything on github:

The question is, how can I remove the input field and flatten it while maintaining style from the content, and preferable features like auto size from the field?

Upvotes: 0

Views: 824

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109547

Maybe it suffices to remove the editable state:

for (PDField field: pdf_document.getDocumentCatalog().getAcroForm().getFieldTree()) {
    field.setReadOnly(true);
}

Upvotes: 0

Related Questions