Python - create a multi-layered PDF

4.9k Views Asked by At

Is there a way to use Python to create a multiple layers PDF. But not merge.

I think the multiple layers PDF means there is more than one layers in a page and I can select which layer to show in Acrobat.

Here is a document I find about layered PDF: http://www.open.ac.uk/opencetl/files/opencetl/file/ecms/web-content/Multi-pdf-how-to-%20file.pdf

And an example of layered PDF: http://www.talkgraphics.com/attachment.php?s=1901864ddbe7b63f672440daffc3907e&attachmentid=76844&d=1285324919

3

There are 3 best solutions below

0
On

From what I can tell, neither Reportlab nor pypdf have mechanisms to create the blocks of marked content necessary to implement layers (or Optional Content Groups).

I have created such using IronPython and Datalogics .Net interface to APDFL. There is also a Java interface, so you could do the same with Jython.

The technique is basically that you create an OptionalContentGroup for your layer, you then add the content that you want in your layer to a container, and you set the Container's OptionalContentMembershipDict to an OptionalContentMemberDict that connects the two.

ocg = PDFL.OptionalContentGroup(doc,"Labels")
doc.DefaultOptionalContentConfig.Order.Insert(0,PDFL.OptionalContentOrderLeaf(ocg))
labelContainer.OptionalContentMembershipDict = PDFL.OptionalContentMembershipDict(doc,[ocg,],PDFL.VisibilityPolicy.AnyOn)

Where labelContainer is a Container Element I had added to the Content of my page.

Disclosure: I work for Datalogics.

0
On

The number of viewers that need to view layers is a very small minority and usually not of PDF/X-4 standard, But many Python Editors can modify or add OCGs however because of complexity, many are commercial grade applications, such as MuPDF based PyMuPDF. https://pymupdf.readthedocs.io/en/latest/document.html#Document.get_layer

Up to now

PDF/X-1a and PDF/X-3, which are still widely used as the standard data exchange with commercial printers, explicitly forbid the usage of OCGs (Optional Content Groups aka layers).

The Downside of Layers is that Even if you were to produce them then the majority of PDF readers including Lightweight Adobe Acrobat see them as one or all without any means to switch on and off except by install a bloated Acrobat Editor or Full Enhanced Reader such as DC. Or a lightweight annotation editing app

enter image description here enter image description here

1
On

You can use PyPDF2 to overlay pages from different PDF files, producing another PDF file that is not flattened.

You can find a good example adding a watermark here. Take a look at the example and explanation in the "Overlaying Pages" section.