title: PDFBox: How to "flatten" a PDF-form?
body: <p>How do I "flatten" a PDF-form (remove the form-field but keep the text of the field) with PDFBox?</p>
  
  <p><a href="http://mail-archives.apache.org/mod_mbox/pdfbox-users/201009.mbox/%3C4C9A326F.60902@rayman2200.de%3E">Same question was answered here:</a> </p>
  
  <blockquote>
    <p>a quick way to do this, is to remove the fields from the acrofrom.</p>
    
    <p>For this you just need to get the document catalog, then the acroform 
    and then remove all fields from this acroform.</p>
    
    <p>The graphical representation is linked with the annotation and stay in 
    the document.</p>
  </blockquote>
  
  <p>So I wrote this code:</p>
  
  <pre><code>import java.io.File;
  import java.util.ArrayList;
  import java.util.List;
  
  import org.apache.pdfbox.pdmodel.PDDocument;
  import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
  import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
  import org.apache.pdfbox.pdmodel.interactive.form.PDField;
  
  public class PdfBoxTest {
      public void test() throws Exception {
          PDDocument pdDoc = PDDocument.load(new File("E:\\Form-Test.pdf"));
          PDDocumentCatalog pdCatalog = pdDoc.getDocumentCatalog();
          PDAcroForm acroForm = pdCatalog.getAcroForm();
  
          if (acroForm == null) {
              System.out.println("No form-field --&gt; stop");
              return;
          }
  
          @SuppressWarnings("unchecked")
          List&lt;PDField&gt; fields = acroForm.getFields();
  
          // set the text in the form-field &lt;-- does work
          for (PDField field : fields) {
              if (field.getFullyQualifiedName().equals("formfield1")) {
                  field.setValue("Test-String");
              }
          }
  
          // remove form-field but keep text ???
          // acroForm.getFields().clear();         &lt;-- does not work
          // acroForm.setFields(null);             &lt;-- does not work
          // acroForm.setFields(new ArrayList());  &lt;-- does not work
          // ???
  
          pdDoc.save("E:\\Form-Test-Result.pdf");
          pdDoc.close();
      }
  }
  </code></pre>