-
Notifications
You must be signed in to change notification settings - Fork 690
Closed
Description
Describe the issue:
I need to open a PDF file (original.pdf), turn off a specific layer by its name, and save the result as updated.pdf. I am having difficulty achieving this with PyMuPDF and would appreciate any guidance or examples on how to perform this task.
Steps to achieve the task:
- Open
original.pdf, which contains multiple layers. - Identify and turn off a specific layer by its name.
- Save the modified PDF as
updated.pdf.
Desired functionality:
- Open the PDF file.
- Turn off the layer named
Layer_name_01. - Save the resulting PDF with the layer turned off.
Current code:
import fitz
import sys
def turn_off_layer(pdf_path, layer_name, output_path):
# Open the source PDF file
src = fitz.open(pdf_path)
# Find the layer (OCG) named 'Layer_name_01'
ocgs = src.get_ocgs()
layer_to_turn_off = None
for key, ocg in ocgs.items():
if ocg.get("name") == layer_name:
layer_to_turn_off = key
break
if layer_to_turn_off is not None:
# Turn off the layer
ocg_off = src.set_ocmd(ocgs=[layer_to_turn_off], policy="AllOff")
# Create a new PDF to save the changes
doc = fitz.open()
for page_num in range(src.page_count):
page = doc.new_page(width=src[page_num].rect.width, height=src[page_num].rect.height)
page.show_pdf_page(page.rect, src, page_num, oc=ocg_off)
# Save the modified PDF
doc.save(output_path, garbage=3, pretty=True, deflate=True, clean=True)
print(f"Layer '{layer_name}' turned off and saved as {output_path}")
else:
print(f"Layer '{layer_name}' not found in the PDF.")
if __name__ == "__main__":
if len(sys.argv) != 4:
print("Usage: python turn_off_layer.py <input_pdf> <layer_name> <output_pdf>")
else:
pdf_path = sys.argv[1]
layer_name = sys.argv[2]
output_path = sys.argv[3]
turn_off_layer(pdf_path, layer_name, output_path)Environment:
Python version: 3.6.8
PyMuPDF version: 1.19.6
Any guidance or examples on how to achieve this would be greatly appreciated. Thank you!
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels