Work with PDF Layers using Python
PDF layers, also called Optional Content Groups (OCGs), let you organize content into separate visual groups that can be shown or hidden in compatible PDF viewers. In Aspose.PDF, layer operations are built around the Layer API.
With Aspose.PDF for Python via .NET, you can:
- Add multiple layers to a page.
- Lock and unlock layers to control visibility behavior.
- Extract layers into separate files or streams.
- Flatten layered content into the page.
- Merge multiple layers into one layer.
Add Layers to a PDF
This example creates a PDF with three layers. It uses a Document, adds a Page, and appends Layer objects to that page.
- Create a new
Documentand add aPage. - Create and add the red layer.
- Create and add the green layer.
- Create and add the blue layer.
- Save the PDF document.
The resulting PDF will contain three separate layers: a red line, a green line, and a blue line. Each can be toggled on or off in PDF readers that support layered content.
import aspose.pdf as ap
def add_layers(outfile: str) -> None:
document = ap.Document()
page = document.pages.add()
# Red layer
layer = ap.Layer("oc1", "Red Line")
layer.contents.append(ap.operators.SetRGBColorStroke(1, 0, 0))
layer.contents.append(ap.operators.MoveTo(500, 700))
layer.contents.append(ap.operators.LineTo(400, 700))
layer.contents.append(ap.operators.Stroke())
page.layers.append(layer)
# Green layer
layer = ap.Layer("oc2", "Green Line")
layer.contents.append(ap.operators.SetRGBColorStroke(0, 1, 0))
layer.contents.append(ap.operators.MoveTo(500, 750))
layer.contents.append(ap.operators.LineTo(400, 750))
layer.contents.append(ap.operators.Stroke())
page.layers.append(layer)
# Blue layer
layer = ap.Layer("oc3", "Blue Line")
layer.contents.append(ap.operators.SetRGBColorStroke(0, 0, 1))
layer.contents.append(ap.operators.MoveTo(500, 800))
layer.contents.append(ap.operators.LineTo(400, 800))
layer.contents.append(ap.operators.Stroke())
page.layers.append(layer)
document.save(outfile)
print(f"Layers added successfully. File saved at {outfile}")
Lock a PDF Layer
This example opens a PDF, locks a specific layer on the first page, and saves the updated file.
Locking a layer prevents users from changing that layer’s visibility state in supported PDF viewers. Layers are accessed from a page and managed through the page’s layer collection.
Available methods and property:
Layer.lock()locks the layer.Layer.unlock()unlocks the layer.Layer.lockedreturns the current lock state.
- Open the PDF document.
- Access the first page of the PDF.
- Check if the page has layers.
- Get the first layer and lock it.
- Save the updated PDF.
If the PDF contains layers, the first layer will be locked, ensuring its visibility state cannot be changed by the user. If no layers are found, a message is printed instead.
import aspose.pdf as ap
def lock_layer(infile: str, outfile: str) -> None:
document = ap.Document(infile)
page = document.pages[1]
if len(page.layers) > 0:
layer = page.layers[0]
layer.lock()
document.save(outfile)
print(f"Layer locked successfully. File saved at {outfile}")
else:
print("No layers found in the document.")
Extract PDF Layer Elements
This example uses the Aspose.PDF for Python via .NET library to extract individual layers from the first page of a PDF document and save each layer as a separate PDF file by using Layer.save().
To create a new PDF from a layer, the following code snippet can be used:
- Load the PDF
Document. - Access layers on page 1 through
Page. - Check whether layers exist.
- Iterate through layers and save each one.
import aspose.pdf as ap
def extract_layers(infile: str, outfile: str) -> None:
document = ap.Document(infile)
layers = document.pages[1].layers
if len(layers) == 0:
print("No layers found in the document.")
return
index = 1
for layer in layers:
output_file = outfile.replace(".pdf", f"{index}.pdf")
layer.save(output_file)
print(f"Layer {index} saved to {output_file}")
index += 1
It is possible to extract PDF layer elements and save them into a new PDF file stream:
from io import FileIO
import aspose.pdf as ap
def extract_layers_stream(infile: str, outfile: str) -> None:
document = ap.Document(infile)
if len(document.pages[1].layers) == 0:
print("No layers found in the document.")
return
layer = document.pages[1].layers[0]
with FileIO(outfile, "wb") as output_layer:
layer.save(output_layer)
print(f"Layer extracted to stream: {outfile}")
Flatten a Layered PDF
This script uses Aspose.PDF for Python via .NET to flatten all layers on the first page of a PDF document. Flattening merges the visual content of each layer into one unified layer, making it easier to print, share, or archive without losing visual fidelity or layer-specific data. The operation is performed with Layer.flatten().
- Load the PDF document.
- Access layers on page 1.
- Check whether layers exist.
- Flatten each layer with
layer.flatten(True). - Save the modified document.
import aspose.pdf as ap
def flatten_layers(infile: str, outfile: str) -> None:
document = ap.Document(infile)
layers = document.pages[1].layers
if len(layers) == 0:
print("No layers found in the document.")
return
for layer in layers:
layer.flatten(True)
document.save(outfile)
print(f"Layers flattened successfully. File saved at {outfile}")
Merge All Layers in a PDF into One
This code snippet uses Aspose.PDF to merge all layers on the first page of a PDF into one unified layer with a custom name by using Page.merge_layers().
- Load the PDF document.
- Access page 1 and retrieve its layers.
- Check whether layers exist.
- Define a new layer name.
- Merge the layers into one.
- Save the document.
import aspose.pdf as ap
def merge_layers(infile: str, outfile: str) -> None:
document = ap.Document(infile)
page = document.pages[1]
if len(page.layers) == 0:
print("No layers found in the document.")
return
new_layer_name = "LayerNew"
page.merge_layers(new_layer_name)
document.save(outfile)
print(f"Layers merged successfully. File saved at {outfile}")