Created
February 13, 2025 18:15
-
-
Save JeroenSteen/c46f176d50d3448c6cc275b53a3f5c43 to your computer and use it in GitHub Desktop.
Make Cut-Layer unprintable of Multiple PDF's in bulk via python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pikepdf | |
import os | |
folder_path = os.getcwd() # Current folder | |
layer_to_modify = "Cut" # Name of the layer to modify | |
for file in os.listdir(folder_path): | |
if file.endswith(".pdf"): | |
pdf_path = os.path.join(folder_path, file) | |
pdf = pikepdf.Pdf.open(pdf_path) | |
# Locate the /OCProperties dictionary (where layers are defined) | |
ocprops = pdf.Root.get(pikepdf.Name("/OCProperties")) | |
if ocprops: | |
ocgs = ocprops.get(pikepdf.Name("/OCGs")) | |
default_config = ocprops.get(pikepdf.Name("/D"), pikepdf.Dictionary()) | |
if ocgs: | |
# Find the "Cut" layer object | |
for layer in ocgs: | |
if layer.get(pikepdf.Name("/Name")) == layer_to_modify: | |
print(f"Modifying layer '{layer_to_modify}' in {file}") | |
# Ensure /Usage dictionary exists | |
if pikepdf.Name("/Usage") not in layer: | |
layer[pikepdf.Name("/Usage")] = pikepdf.Dictionary() | |
usage = layer[pikepdf.Name("/Usage")] | |
# Set visibility settings (create if missing) | |
if pikepdf.Name("/View") not in usage: | |
usage[pikepdf.Name("/View")] = pikepdf.Dictionary() | |
if pikepdf.Name("/Print") not in usage: | |
usage[pikepdf.Name("/Print")] = pikepdf.Dictionary() | |
usage[pikepdf.Name("/View")][pikepdf.Name("/ViewState")] = pikepdf.Name("/Never") | |
usage[pikepdf.Name("/Print")][pikepdf.Name("/PrintState")] = pikepdf.Name("/Never") | |
# Set Initial State (Turn Off Layer by Default) | |
if pikepdf.Name("/OFF") not in default_config: | |
default_config[pikepdf.Name("/OFF")] = pikepdf.Array() | |
default_config[pikepdf.Name("/OFF")].append(layer) | |
# Ensure the default settings are updated | |
ocprops[pikepdf.Name("/D")] = default_config | |
# Save modified PDF | |
new_pdf_path = os.path.join(folder_path, "modified_" + file) | |
pdf.save(new_pdf_path) | |
pdf.close() | |
print("Layer modified: Now hidden, unprintable, and OFF by default!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment