You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
PyPDF2 does not currently have any support for Optional Content Groups (OCGs). When merging multiple documents into a single document the layers are effectively
flattened and functionality is lost.
It looks like the OCG settings are stored in the 'OCProperties' dictionary in 'Root' - see dump below.
The problem here is that it uses IndirectObjects, which don't necessarily have the same ID in the input PDF to the output PDF when the page is appended. How do we get the ID of the corresponding new object in the output PDF?
As this feature request didn't receive an update for a long time, I'm closing it.
I'm linking it in #1181 so that we don't forget about it. Please feel free to add more information (PDFs that use it; other projects that implement it; explanations how it would improve PyPDF2)
@snorfalorpagus@emmama1234 Hi, I know it's been a while but did either of you ever get further with this? I'm working on the same thing and used reader.trailer['/Root']['/OCProperties'] and reader._get_object to get all the direct object references. Then re-mapped them to the writer using writer._add_object and writer._root_object['/OCProperties']. The pdf still has trouble opening but I feel like I'm close. Do any of you have any suggestions? I can share the python code too if that helps.
@MartinThoma would love for this to be implemented in pypdf.
@stefan6419846 Hi, I saw it was linked in #1181. My code does not work yet and still stuck.. The output pdf still does not have layers information and is blank.
Here's what I am doing so far:
import pypdf
from pypdf.generic import ArrayObject, DictionaryObject, NameObject
def get_ocgs_direct(reader):
ocgs_props = DictionaryObject({})
if "/OCProperties" in reader.trailer["/Root"]:
ocgs_props = reader.root_object["/OCProperties"]
if (len(ocgs_props) > 0):
# get direct objects for ocgs
for i, indirect in enumerate(ocgs_props["/OCGs"]):
pdfobject = reader.get_object(indirect)
ocgs_props[NameObject("/OCGs")][i] = pdfobject
# repeat for order
for i, indirect in enumerate(ocgs_props["/D"]["/Order"]):
if isinstance(indirect, pypdf.generic._data_structures.ArrayObject):
# nested lists to resolve
arr = ArrayObject([reader.get_object(indirect[0])])
arr.append(ArrayObject([reader.get_object(indirect[1][0])]))
ocgs_props[NameObject("/D")][NameObject("/Order")][i] = ArrayObject(arr)
else:
pdfobject = reader.get_object(indirect)
ocgs_props[NameObject("/D")][NameObject("/Order")][i] = pdfobject
return ocgs_props
def set_ocgs_direct(writer, ocgs_direct):
# re-reference ocjs to writer pdf using add_object
for i, direct in enumerate(ocgs_direct["/OCGs"]):
indirectobject = writer._add_object(DictionaryObject(direct)) # find out name object type
ocgs_direct[NameObject("/OCGs")][i] = indirectobject
# should update [/d][/order] already.
for i, direct in enumerate(ocgs_direct["/D"]["/Order"]):
if isinstance(direct, pypdf.generic._data_structures.ArrayObject):
#nested lists to resolve
direct[0] = writer._add_object(DictionaryObject(direct[0]))
direct[1][0] = writer._add_object(DictionaryObject(direct[1][0]))
else:
indirect = writer._add_object(DictionaryObject(direct))
ocgs_direct[NameObject("/D")][NameObject("/Order")][i] = indirect
if "/OCProperties" in writer.root_object.keys():
writer.root_object[NameObject("/OCProperties")].update(ocgs_direct)
else:
writer._root_object[NameObject("/OCProperties")] = DictionaryObject(ocgs_direct)
@mmalik1234 I am going to re-open this issue for now as there seems to be further interest, although this will probably only be supported if this is a contributed as a PR and is easy enough to maintain. I cannot help much with this, as I have no use case which would use OCGs.
Having a quick look at your code, you probably should not have to use the full class path for ArrayObject in the isinstance (although only related to style). Additionally, the last condition looks wrong with the backslash as key.
My usecase is, that I set pagenumbers or other overlay information on each page. I want to put such overlays on a named layer for easy identification and en-/disable viewing and printing hereof.
Specifically I want to be able to identify the layer to be able to remove the overlay again, e.g. inserting new pagenumbers while removing the old beforehand.
Thus, I need to be able to add the layer and ensure I can draw overlays on them.
Other way to identify and remove an overlay might also work - but layers / OCGs are the current idea.
I would like this to happen! I added an issue in pdfly before figuring out it needs support here first. py-pdf/pdfly#190
My use case has to do with the PDF exports from AutoCAD which put each CAD layer (windows, doors, walls) on separate PDF layers / OCGs, and I would like the ability to work with them programmatically: toggle on/off, remove, add, copy to a new file, etc.
pymupdf has the ability to toggle visibility, but I'm not sure about the rest:
importpymupdfddoc=pymupdf.open("file.pdf")
ogcs=doc.get_ocgs()
lyr_xref=ogcs[0]
doc.set_layer(-1, on=[lyr_xref], basestate="OFF") # turn off all but the first layer
In pypdf I can retrieve these objects pretty easily, how can I actually do things with them?
In pypdf, you mostly need to know the official PDF specification and understand it to work with this, although it always is hard to help without an actual example file.
Section 8.11 of the PDF 2.0 specification defines the necessary aspects. The visibility policy for an OCG membership dictionary (OCMD) is defined by its visibility policy key /P in the easiest case, being set to either /AllOn, /AnyOn, /AnyOff or /AllOff. This can be overridden by the /VE key which defines a more complex visibility expression.
At the moment, every action should be possible in theory if you use the low-level interface where necessary. The main issue might be that we do not have a high-level interface at the moment.
Just getting my bearings in the codebase and the reference spec.... Could you perhaps point me to a basic example of what you mean by the "low-level interface?"
In constants.py I see the implementations of various spec tables, am I correct that Section 8.11 would need to be added here? For example I'm not seeing an implementation of Table 97 for the OGC visibility policy, just OC_PROPERTIES in CatalogDictionary.
For example, given that you have a OCMD (obj['/Type'] == '/OCMD'), you could access the policy with obj['/P'] and update it with obj[NameObject('/P')] = NameObject('/AllOn').
am I correct that Section 8.11 would need to be added here?
Yes, constants/names would be added there, but it is not strictly necessary for the basic usage. If we add proper support for OCGs to pypdf, we would have to define a suitable interface first anyway.
You can find other CAD examples here and export to PDF with TrueVew (gratis) to see the layers situation.
I do not have a suitable Windows machine available, but as I am most likely not going to implement the new functionality myself anyway due to different reasons, it might help interested community members to look into it and evaluate implementations.
Hello, apologies as I should have posted here prior to submitting the PR, but in order to resolve an issue with pypdf and Esri software, we believe we have found a way to at least preserve OCGs/OCMDs when appending PDFs and wanted to see if this could be worth adding to pypdf.
The idea behind this implementation was that the "/OCProperties" and "/OCGs" could still be read with pypdf, but they were seemingly not preserved when the file was merged or appended into the output PDF and so the OCG layers would disappear from the output merged PDF file.
To preserve them, our implementation attempts to clone the OCG layer objects into the writer and uses a translation dictionary to map the source indirect object IDs to their new object IDs in the output PDF without duplicating indirect references. Once those references are translated, the writer can rebuild the OCG entries including "/OCGs" and related structures such as "/D", "/Order", "/RBGroups", and "/Configs". So far this has worked with the test files we've tried internally.
The PR (#3980) should hopefully also work on your end and we would greatly appreciate the larger community testing with their own OCG pdfs along with feedback or improvements to the code.
Still working through the PR process, but I did take a look at the 3 failed tests for now. 2 of them are from my tests and should be resolved once the sample files are updated, but I did get the following:
Regarding the "test_workflows.py", from some local testing it appears to perform a merge using the pypdf library and compares the output of that against a "control" PDF:
Considering the results: Failed: len(actual) = 217,997 vs len(expected) = 217,857
The test showing that the "actual" merge is a slightly larger size than the "expected" control PDF makes sense as the control currently lacks OCG related structures. I guess there's a note to be made that we'll need to update that file if this enhancement goes through.
Activity
mstamy2 commentedon Apr 22, 2014
Thanks - We definitely need support for layered PDFs to display correctly (and possibly support for adding/removing layers?
snorfalorpagus commentedon Jun 10, 2014
It looks like the OCG settings are stored in the 'OCProperties' dictionary in 'Root' - see dump below.
The problem here is that it uses IndirectObjects, which don't necessarily have the same ID in the input PDF to the output PDF when the page is appended. How do we get the ID of the corresponding new object in the output PDF?
snorfalorpagus commentedon Jun 10, 2014
Screenshot below of the PDF in Acrobat Reader (on Linux) that was used for the dump above.
emmama1234 commentedon Jul 28, 2015
How did you get the dumped structure?
snorfalorpagus commentedon Jul 28, 2015
@emmama1234 I've got the dumped structure like this:
emmama1234 commentedon Aug 20, 2015
@snorfalorpagus did you find any way to add/remove OCG layers to multiple pages Pdf with PyPDF2?
snorfalorpagus commentedon Aug 21, 2015
I didn't get any further than viewing the data as posted above. :(
emmama1234 commentedon Aug 21, 2015
@snorfalorpagus Thanks! i'll take a look at it to see if i can find something
MartinThoma commentedon Jul 29, 2022
As this feature request didn't receive an update for a long time, I'm closing it.
I'm linking it in #1181 so that we don't forget about it. Please feel free to add more information (PDFs that use it; other projects that implement it; explanations how it would improve PyPDF2)
mmalik1234 commentedon Oct 24, 2024
@snorfalorpagus @emmama1234 Hi, I know it's been a while but did either of you ever get further with this? I'm working on the same thing and used
reader.trailer['/Root']['/OCProperties']andreader._get_objectto get all the direct object references. Then re-mapped them to the writer usingwriter._add_objectandwriter._root_object['/OCProperties']. The pdf still has trouble opening but I feel like I'm close. Do any of you have any suggestions? I can share the python code too if that helps.@MartinThoma would love for this to be implemented in pypdf.
stefan6419846 commentedon Oct 24, 2024
You are of course always invited to provide a corresponding PR to add such support.
mmalik1234 commentedon Oct 25, 2024
@stefan6419846 Hi, I saw it was linked in #1181. My code does not work yet and still stuck.. The output pdf still does not have layers information and is blank.
Here's what I am doing so far:
stefan6419846 commentedon Oct 25, 2024
@mmalik1234 I am going to re-open this issue for now as there seems to be further interest, although this will probably only be supported if this is a contributed as a PR and is easy enough to maintain. I cannot help much with this, as I have no use case which would use OCGs.
Having a quick look at your code, you probably should not have to use the full class path for
ArrayObjectin theisinstance(although only related to style). Additionally, the last condition looks wrong with the backslash as key.mmalik1234 commentedon Oct 25, 2024
@stefan6419846 Thanks. This comment from 1181 shows my use case. #1181 (comment)
osos commentedon Mar 19, 2025
My usecase is, that I set pagenumbers or other overlay information on each page. I want to put such overlays on a named layer for easy identification and en-/disable viewing and printing hereof.
Specifically I want to be able to identify the layer to be able to remove the overlay again, e.g. inserting new pagenumbers while removing the old beforehand.
Thus, I need to be able to add the layer and ensure I can draw overlays on them.
Other way to identify and remove an overlay might also work - but layers / OCGs are the current idea.
p-vdp commentedon Oct 20, 2025
I would like this to happen! I added an issue in
pdflybefore figuring out it needs support here first. py-pdf/pdfly#190My use case has to do with the PDF exports from AutoCAD which put each CAD layer (windows, doors, walls) on separate PDF layers / OCGs, and I would like the ability to work with them programmatically: toggle on/off, remove, add, copy to a new file, etc.
pymupdf has the ability to toggle visibility, but I'm not sure about the rest:
In
pypdfI can retrieve these objects pretty easily, how can I actually do things with them?stefan6419846 commentedon Oct 20, 2025
In pypdf, you mostly need to know the official PDF specification and understand it to work with this, although it always is hard to help without an actual example file.
Section 8.11 of the PDF 2.0 specification defines the necessary aspects. The visibility policy for an OCG membership dictionary (OCMD) is defined by its visibility policy key
/Pin the easiest case, being set to either/AllOn,/AnyOn,/AnyOffor/AllOff. This can be overridden by the/VEkey which defines a more complex visibility expression.At the moment, every action should be possible in theory if you use the low-level interface where necessary. The main issue might be that we do not have a high-level interface at the moment.
p-vdp commentedon Oct 20, 2025
@stefan6419846 Thanks! I'll look into the API and see what I can find.
Here's a sample file: building001-0_floor1.pdf
You can find other CAD examples here and export to PDF with TrueVew (gratis) to see the layers situation.
p-vdp commentedon Oct 21, 2025
Just getting my bearings in the codebase and the reference spec.... Could you perhaps point me to a basic example of what you mean by the "low-level interface?"
In
constants.pyI see the implementations of various spec tables, am I correct that Section 8.11 would need to be added here? For example I'm not seeing an implementation of Table 97 for the OGC visibility policy, justOC_PROPERTIESinCatalogDictionary.stefan6419846 commentedon Oct 21, 2025
For example, given that you have a OCMD (
obj['/Type'] == '/OCMD'), you could access the policy withobj['/P']and update it withobj[NameObject('/P')] = NameObject('/AllOn').Yes, constants/names would be added there, but it is not strictly necessary for the basic usage. If we add proper support for OCGs to pypdf, we would have to define a suitable interface first anyway.
I do not have a suitable Windows machine available, but as I am most likely not going to implement the new functionality myself anyway due to different reasons, it might help interested community members to look into it and evaluate implementations.
mTangtrongwanit commentedon Sep 2, 2026
Hello, apologies as I should have posted here prior to submitting the PR, but in order to resolve an issue with pypdf and Esri software, we believe we have found a way to at least preserve OCGs/OCMDs when appending PDFs and wanted to see if this could be worth adding to pypdf.
The idea behind this implementation was that the "/OCProperties" and "/OCGs" could still be read with pypdf, but they were seemingly not preserved when the file was merged or appended into the output PDF and so the OCG layers would disappear from the output merged PDF file.
To preserve them, our implementation attempts to clone the OCG layer objects into the writer and uses a translation dictionary to map the source indirect object IDs to their new object IDs in the output PDF without duplicating indirect references. Once those references are translated, the writer can rebuild the OCG entries including "/OCGs" and related structures such as "/D", "/Order", "/RBGroups", and "/Configs". So far this has worked with the test files we've tried internally.
The PR (#3980) should hopefully also work on your end and we would greatly appreciate the larger community testing with their own OCG pdfs along with feedback or improvements to the code.
mTangtrongwanit commentedon Sep 4, 2026
Still working through the PR process, but I did take a look at the 3 failed tests for now. 2 of them are from my tests and should be resolved once the sample files are updated, but I did get the following:
FAILED tests/test_workflows.py::test_merge_output - Failed: len(actual) = 217,997 vs len(expected) = 217,857
Regarding the "test_workflows.py", from some local testing it appears to perform a merge using the pypdf library and compares the output of that against a "control" PDF:
PDF with OCGs (https://github.com/py-pdf/pypdf/blob/main/resources/Seige_of_Vicksburg_Sample_OCR.pdf)
Plain PDF (no OCGs) (https://github.com/py-pdf/pypdf/blob/main/resources/crazyones.pdf)
"Control" Merged PDF that lacks OCGs (https://github.com/py-pdf/pypdf/blob/main/resources/Seige_of_Vicksburg_Sample_OCR-crazyones-merged.pdf)
Considering the results: Failed: len(actual) = 217,997 vs len(expected) = 217,857
The test showing that the "actual" merge is a slightly larger size than the "expected" control PDF makes sense as the control currently lacks OCG related structures. I guess there's a note to be made that we'll need to update that file if this enhancement goes through.