4

I am currently trying to open, edit & save a PDF file using PDFBox. with plain-text fields it already works but I'm having a hard time setting RichTextFormat-Text as value, since everytime I use "setRichTextValue", save and open the document, the field is empty (unchanged).

Code is as follows (stripped from multiple functions):

PDDocument pdfDoc = PDDocument.load(new File("my pdf path"));
PDDocumentCatalog docCatalog = pdfDoc.getDocumentCatalog();
PDAcroForm acroForm = docCatalog.getAcroForm();
PDField field = acroForm.getField("field-to-change");
if (field instanceof PDTextField) {
    PDTextField tfield = (PDTextField) field;
    COSDictionary dict = field.getCOSObject();
    //COSString defaultAppearance = (COSString) dict.getDictionaryObject(COSName.DA);
    //if (defaultAppearance != null && font != "" && size > 0)
    //  dict.setString(COSName.DA, "/" + font + " " + size + " Tf 0 g");
    boolean rtf = true;
    String val = "{\rtf1\ansi\deff0 {\colortbl;\red0\green0\blue0;\red255\green0\blue0;} \cf2 Red RTF Text \cf1 }";
    tfield.setRichText(rtf);
    if (rtf)
        tfield.setRichTextValue(val);
    else
        tfield.setValue(val);
}
// save document etc.

by digging the PDFBox documentation I found this for .setRichTextValue(String r)

 * Set the fields rich text value.
 * Setting the rich text value will not generate the appearance
 * for the field.
 * You can set {@link PDAcroForm#setNeedAppearances(Boolean)} to
 * signal a conforming reader to generate the appearance stream.
 * Providing null as the value will remove the default style string.
 * @param richTextValue a rich text string

so I added

pdfDoc.getDocumentCatalog().getAcroForm().setNeedAppearances(true);

..directly after the PDDocument object and it didnt change anything. So I searched further and found the AppearanceGenerator class, which should create the styles automatically? But it doesnt seem to, and you cant call it manually.

I'm at a loss here and Google is no help either. Seems nobody ever used this before or I'm just too stupid. I want the solution to be done in PDFBox since you dont pay for licenses and it already works for everything else I am doing (getting & replacing images, removing text fields), so it must be possible right?

Thanks in advance.

ThexBasic
  • 715
  • 1
  • 6
  • 24

0 Answers0