Extract layers from PDF on Server/Desktop

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

1doc = PDFDoc.new($filename)
2page = doc.GetPage(1)
3
4init_cfg = doc.GetOCGConfig
5ctx = Context.new(init_cfg)
6
7pdfdraw = PDFDraw.new
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 do
19 ocg = Group.new(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
25end
26
27# Now draw content that is not part of any layer...
28ctx.SetNonOCDrawing(true)
29ctx.SetOCDrawMode(Context::E_NoOC)
30pdfdraw.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