1

I am using pdfbox-2.0.2 and I wanted to change colour of fonts of PDField.

I can find examples for pdfbox-1.8.0 but not for pdfbox-2.0.2.

I am getting PDFields using below code -

PDDocument doc = PDDocument.load(inputTemplateNameFile);
PDDocumentCatalog catalog = doc.getDocumentCatalog();
PDAcroForm form = catalog.getAcroForm();
List<PDField> acroFormfieldsTemplateList = form.getFields();

for(PDField field: acroFormfieldsTemplateList){
   if(field.getFullyQualifiedName().equals("TEST_FIELD_NAME")){
      field.setValue("TEST_TEXT");
   }
}

In the above code I want to change font colour of TEST_TEXT.

Jar files used - pdfbox-2.0.2.jar pdfbox-app-2.0.2.jar

Appreciate your help. Thank you.

Hardik Doshi
  • 67
  • 1
  • 3
  • 16

2 Answers2

3

You need to change the default appearance string.

PDVariableText field = (PDVariableText) form.getField("TEST_FIELD_NAME");
String da = field.getDefaultAppearance();
//TODO replace the color here
field.setDefaultAppearance(da);
field.setValue("TEST_TEXT");

The code above has the assumption that your field is a text field, i.e. of type PDVariableText. I've also removed the loop in your code. That part is incorrect, as it would return only the root fields (see the javadoc of getFields).

The default appearance string will usually have a content like "/Helv 10 Tf 0 g", but it could also be different. So to set blue, you can do this:

da = "/Helv 10 Tf 0 0 1 rg";

"rg" is the operator for an RGB color. The values are between 0 and 1. "g" is the operator for a gray color. 0 is black and 1 is white. To use in-between values you use real numbers, e.g. "0.5".

Tilman Hausherr
  • 17,731
  • 7
  • 58
  • 97
  • 2
    Method name is slight different - String da = field.getDefaultAppearance(); field.setDefaultAppearance(da); After changing method names it worked. – Hardik Doshi Aug 23 '16 at 09:34
0

If you want to change font colour and background colour of PDField the first time, you can make a form with Adobe Acrobat Pro DC. For example, it allow to set a transparent background for the PDFField.

enter image description here

Once the pdf is created, you can get PDF of the disk and get the PDFField to setValues you prefer using PDFBox - 2.0.2.

PDDocument.load(new File("ModelosContratos/FormPDF/prueba.pdf")) // get PDFDocument
.getDocumentCatalog().getAcroForm() // get form of PDF
.getField("lessorName") // get field of form by its name
.setValue("Caridad");  // set value desired