Extract layers from PDF on Server/Desktop

To extract PDF layers or OCG (optional content group) from a document.

1doc = PDFDoc(filename)
2page = doc.GetPage(1)
3
4init_cfg = doc.GetOCGConfig()
5ctx = Context(init_cfg)
6
7pdfdraw = PDFDraw()
8pdfdraw.SetImageSize(1000, 1000)
9pdfdraw.SetOCGContext(ctx) # Render the page using the given OCG context.
10
11# Disable drawing of content that is not optional (i.e. is not part of any layer).
12ctx.SetNonOCDrawing(False)
13
14# Now render each layer in the input document to a separate image.
15ocgs = doc.GetOCGs() # Get the array of all OCGs in the document.
16sz = ocgs.Size()
17i = 0
18while i < sz:
19 ocg = Group(ocgs.GetAt(i))
20 ctx.ResetStates(False)
21 ctx.SetState(ocg, True)
22 fname = "pdf_layers_" + ocg.GetName() + ".png"
23 pdfdraw.Export(page, output_path + fname)
24 i = i + 1
25
26# Now draw content that is not part of any layer...
27ctx.SetNonOCDrawing(True)
28ctx.SetOCDrawMode(Context.e_NoOC)
29pdfdraw.Export(page, output_path + "pdf_layers_non_oc.png")

PDF layers (OCG)
Full sample code which demonstrates how to create, extract, render PDF layers. Code sample is available in C++, C#, Java, Python, Go, PHP, Ruby & VB.

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales