Delete Forms from PDF in Java

These examples remove form resources from a page rather than just changing field values.

Remove all form resources from a page

Use this example when every form resource on a selected page should be removed in one operation.

  1. Open the source PDF Document.
  2. Access the XFormCollection for the target page.
  3. Clear the collection and save the updated document.
public static void removeAllForms(Path inputFile, int pageNum, Path outputFile) {
    try (Document document = new Document(inputFile.toString())) {
        XFormCollection forms = document.getPages().get_Item(pageNum).getResources().getForms();
        forms.clear();
        document.save(outputFile.toString());
    }
}

Remove specific form resources

Use this example when only selected form resources, such as Typewriter forms, should be deleted.

  1. Open the source PDF Document.
  2. Access the XFormCollection for the target page.
  3. Filter the XForm resources you want to remove and delete them from the collection.
  4. Save the updated PDF Document.
public static void removeSpecifiedForm(Path inputFile, int pageNum, Path outputFile) {
    try (Document document = new Document(inputFile.toString())) {
        XFormCollection forms = document.getPages().get_Item(pageNum).getResources().getForms();
        List<String> formNames = new ArrayList<>();
        for (XForm form : forms) {
            if ("Typewriter".equals(form.getIT()) && "Form".equals(form.getSubtype())) {
                formNames.add(forms.getFormName(form));
            }
        }
        for (String formName : formNames) {
            forms.delete(formName);
        }
        document.save(outputFile.toString());
    }
}