File: /home/neptune/Documents/deep_clean_pdf.
py Page 1 of 1
from pypdf import PdfReader, PdfWriter
import os
SCRIPT_DIR = [Link]([Link](__file__))
INPUT_FILENAME = "[Link]"
OUTPUT_FILENAME = "[Link]"
def deep_clean_pdf(input_file, output_file):
if not [Link](input_file):
print(f"Error: {input_file} not found.")
return
reader = PdfReader(input_file)
writer = PdfWriter(clone_from=reader)
# Handle version differences in pypdf
catalog = writer.root_object if hasattr(writer, 'root_object') else writer._root_object
# 1. Strip Document-Level JavaScript
if "/Names" in catalog and "/JavaScript" in catalog["/Names"]:
del catalog["/Names"]["/JavaScript"]
if "/OpenAction" in catalog:
del catalog["/OpenAction"]
if "/AA" in catalog:
del catalog["/AA"]
# 2. Strip Field-Level JavaScript (Calculations, Formatting)
# Form fields are usually in the AcroForm dictionary
if "/AcroForm" in catalog:
acroform = catalog["/AcroForm"]
if "/Fields" in acroform:
for field_ref in acroform["/Fields"]:
field = field_ref.get_object()
# Remove Actions (/A) and Additional Actions (/AA) from the field
if "/AA" in field:
del field["/AA"]
if "/A" in field:
del field["/A"]
# 3. Strip Page-Level JavaScript
for page in [Link]:
page_obj = page.get_object()
if "/AA" in page_obj:
del page_obj["/AA"]
with open(output_file, "wb") as f:
[Link](f)
print(f"Deep clean complete. Saved to: {output_file}")
# Use exact filenames
deep_clean_pdf(INPUT_FILENAME, OUTPUT_FILENAME)