How to Permanently Modify Layer Visibility in PDFs #2776
Replies: 2 comments 1 reply
-
If you use |
Beta Was this translation helpful? Give feedback.
-
I tried to use this:https://github.com/pymupdf/PyMuPDF-Utilities/blob/master/jupyter-notebooks/optional-content.ipynb, In the tutorial I found: I would like to stick to UI because my end-goal is to create an automation based on it. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
In the example below, I am trying to manipulate the visibility of a specific layer in a PDF file. I use the screenshot_page function to generate screenshots of the page with the layer visibility adjusted, and these screenshots reflect the changes correctly. However, when I use the save_pdf_with_layer function to save a new PDF with the adjusted layer visibility, the saved PDF does not reflect these changes.
Expected Behavior
The saved PDFs should reflect the changes made to layer visibility, showing or hiding specific layers as adjusted in the code.
Actual Behavior
The screenshots generated reflect the changes to layer visibility correctly. However, the PDFs saved using the save_pdf_with_layer function do not reflect these changes; the layers do not appear as expected based on the visibility settings.
import fitz
def list_all_ocg_ids(pdf_path):
"""
List all the OCG IDs (Optional Content Group IDs) in the given PDF.
def save_pdf_with_layer(pdf, output_pdf_path, ocg_id, action):
"""Save a copy of the PDF with a specific OCG state."""
def screenshot_page(pdf, output_image_path, ocg_id, action, page_number=0):
"""Generate a screenshot of the specified page with a specific OCG state."""
page = pdf.load_page(page_number)
list_all_ocg_ids("TEST.pdf")
doc = fitz.open("TEST.pdf")
for item in doc.layer_ui_configs():
print(item)
print()
Set OCG with ID 2 to ON
doc.set_layer_ui_config(1, action=2)
Take a screenshot of the first page reflecting the change
screenshot_page(doc, "screenshot.png", 1, 0)
save_pdf_with_layer(doc, "output_ON.pdf", 2, 2)
Set OCG with ID 2 to OFF
doc.set_layer_ui_config(1, action=0)
Take another screenshot of the first page reflecting the change
screenshot_page(doc, "screenshot2.png", 1, 0)
save_pdf_with_layer(doc, "output_OFF.pdf", 2, 0)
doc.close()
Beta Was this translation helpful? Give feedback.
All reactions