Change the content of a button

This is a code example of iText PDF, discover more.

31st May 2016
iText PDF

Switch code for this example

ChangeButton.java
  1. /*
  2.  
  3.     This file is part of the iText (R) project.
  4.     Copyright (c) 1998-2016 iText Group NV
  5.  
  6. */
  7.  
  8. /**
  9.  * This example was written by Bruno Lowagie in answer to the following question:
  10.  * http://stackoverflow.com/questions/26804092/itext-button-resize-affects-label
  11.  */
  12. package com.itextpdf.samples.sandbox.acroforms;
  13.  
  14. import com.itextpdf.forms.PdfAcroForm;
  15. import com.itextpdf.forms.fields.PdfFormField;
  16. import com.itextpdf.kernel.pdf.*;
  17. import com.itextpdf.samples.GenericTest;
  18. import com.itextpdf.test.annotations.type.SampleTest;
  19.  
  20. import org.junit.experimental.categories.Category;
  21.  
  22. import java.io.File;
  23.  
  24. @Category(SampleTest.class)
  25. public class ChangeButton extends GenericTest {
  26.     public static final String DEST = "./target/test/resources/sandbox/acroforms/change_button.pdf";
  27.     public static final String SRC = "./src/test/resources/pdfs/hello_button.pdf";
  28.  
  29.     public static void main(String[] args) throws Exception {
  30.         File file = new File(DEST);
  31.         file.getParentFile().mkdirs();
  32.         new ChangeButton().manipulatePdf(DEST);
  33.     }
  34.  
  35.     @Override
  36.     protected void manipulatePdf(String dest) throws Exception {
  37.         PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(DEST));
  38.         PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, true);
  39.         PdfFormField button = form.copyField("Test");
  40.         PdfArray rect = button.getWidgets().get(0).getRectangle();
  41.         rect.set(2, new PdfNumber(rect.getAsNumber(2).floatValue() + 172));
  42.         button.setValue("Print Amended");
  43.         form.replaceField("Test", button);
  44.         pdfDoc.close();
  45.     }
  46. }
Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now