Delete Forms from PDF in Python

Remove all Forms from PDF

This code removes all form elements from the first page of a PDF document and then saves the modified document to the specified output path.

  1. Load the PDF document.
  2. Access page resources.
  3. Clear form objects.
  4. Save the updated document.

    import aspose.pdf as ap
    import os

    data_dir = "/path/to/your/pdf/files/"
    path_infile = os.path.join(data_dir, infile)
    path_outfile = os.path.join(data_dir, outfile)

    document = ap.Document(path_infile)
    forms = document.pages[page_num].resources.forms
    forms.clear()
    document.save(path_outfile)

Remove Specified Form

Next example iterates through the form objects on a given PDF page, identifies typewriter form annotations, deletes them, and then saves the updated PDF using Aspose.PDF for Python via .NET.

  1. Load the PDF document.
  2. Access page forms.
  3. Iterate over forms.
  4. Check for typewriter forms.
  5. Delete the matched form.
  6. Save the updated document.

    import aspose.pdf as ap
    import os

    data_dir = "/path/to/your/pdf/files/"
    path_infile = os.path.join(work_dir, infile)
    path_outfile = os.path.join(work_dir, outfile)

    document = ap.Document(path_infile)
    forms = document.pages[page_num].resources.forms
    for form in forms:
        if (form.it == "Typewriter" and form.subtype == "Form"):
            name = forms.get_form_name(form)
            forms.delete(name)
    document.save(path_outfile)