Skip to content

Need help to turn off a specific layer in a PDF and save the result #3753

@amaX9

Description

@amaX9

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:

  1. Open original.pdf, which contains multiple layers.
  2. Identify and turn off a specific layer by its name.
  3. 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!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions