Get information from a form

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

31st May 2016
iText PDF

Switch code for this example

CheckBoxValues.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.  * Example written by Bruno Lowagie in answer to:
  10.  * http://stackoverflow.com/questions/19698771/checking-off-pdf-checkbox-with-itextsharp
  11.  *
  12.  * Given a check box in a form, how do we know which values to use in setField?
  13.  */
  14. package com.itextpdf.samples.sandbox.acroforms;
  15.  
  16. import com.itextpdf.forms.PdfAcroForm;
  17. import com.itextpdf.forms.fields.PdfFormField;
  18. import com.itextpdf.kernel.pdf.PdfDocument;
  19. import com.itextpdf.kernel.pdf.PdfReader;
  20. import com.itextpdf.test.annotations.type.SampleTest;
  21.  
  22. import org.junit.Assert;
  23. import org.junit.BeforeClass;
  24. import org.junit.Test;
  25. import org.junit.experimental.categories.Category;
  26.  
  27. import java.io.FileInputStream;
  28. import java.util.Map;
  29.  
  30. @Category(SampleTest.class)
  31.  
  32. public class CheckBoxValues {
  33.     public static final String CMP = "Yes\nOff\n";
  34.     public static final String DEST = "./target/test/resources/sandbox/acroforms/check_box_values.pdf";
  35.     public static final String FIELD = "CP_1";
  36.     public static final String SRC = "./src/test/resources/pdfs/datasheet.pdf";
  37.  
  38.     @BeforeClass
  39.     public static void beforeClass() throws Exception {
  40.         new CheckBoxValues().manipulatePdf();
  41.     }
  42.  
  43.     @Test
  44.     public void manipulatePdf() throws Exception {
  45.         PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC));
  46.         PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, true);
  47.  
  48.         Map fields = form.getFormFields();
  49.         PdfFormField field = fields.get(FIELD);
  50.  
  51.         StringBuilder sb = new StringBuilder();
  52.         String[] states = field.getAppearanceStates();
  53.         for (String state : states) {
  54.             sb.append(state);
  55.             sb.append('\n');
  56.         }
  57.         System.out.println(sb);
  58.  
  59.         pdfDoc.close();
  60.  
  61.         Assert.assertEquals(CMP, sb.toString());
  62.     }
  63. }

Resources

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