0% found this document useful (0 votes)
3 views1 page

Deep Clean PDF - Py

The document is a Python script that deep cleans a PDF file by removing various types of JavaScript, including document-level, field-level, and page-level scripts. It uses the pypdf library to read an input PDF and write a cleaned output PDF. The script checks for the existence of the input file and handles potential version differences in the pypdf library.

Uploaded by

Dustin Shorter
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views1 page

Deep Clean PDF - Py

The document is a Python script that deep cleans a PDF file by removing various types of JavaScript, including document-level, field-level, and page-level scripts. It uses the pypdf library to read an input PDF and write a cleaned output PDF. The script checks for the existence of the input file and handles potential version differences in the pypdf library.

Uploaded by

Dustin Shorter
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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)

You might also like