Delete Forms from PDF in Java
Contents
[
Hide
]
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.
- Open the source PDF Document.
- Access the XFormCollection for the target page.
- 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.
- Open the source PDF Document.
- Access the XFormCollection for the target page.
- Filter the XForm resources you want to remove and delete them from the collection.
- 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());
}
}