How to set the text of a PDTextbox to a color?

好久不见. 提交于 2019-12-02 09:49:29

Normally a text field has a default appearance entry from which PDFBox constructs the appearance. Thus, you merely need to change this default appearance to also include a statement selecting red color.

E.g.

PDDocument pdfDoc = PDDocument.load(SOURCE);
PDDocumentCatalog docCatalog = pdfDoc.getDocumentCatalog();
PDAcroForm acroForm = docCatalog.getAcroForm();

for (Object field : acroForm.getFields())
{
    if (field instanceof PDVariableText)
    {
        COSDictionary dict = ((PDField)field).getDictionary();
        COSString defaultAppearance = (COSString) dict.getDictionaryObject(COSName.DA);
        if (defaultAppearance != null)
            dict.setString(COSName.DA, defaultAppearance.getString() + " 1 0 0 rg ");

        field = field instanceof PDTextbox ? new PDTextbox(acroForm, dict) : new PDChoiceField(acroForm, dict);
        ((PDField)field).setValue(VALUE);
    }
}
pdfDoc.save(TARGET);
pdfDoc.close();

This code first enhances the default appearance and then sets the field value. The field variable has to be renewed in between because PDVariableText stores the default appearance in a hidden member during initialization.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!