Extract layers from PDF on Server/Desktop

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

1doc := NewPDFDoc(filename)
2page = doc.GetPage(1)
3
4init_cfg := doc.GetOCGConfig()
5ctx := NewContext(init_cfg)
6
7pdfdraw := NewPDFDraw()
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.
16if ocgs != nil{
17 sz := ocgs.Size()
18 i := int64(0)
19 for i < sz{
20 ocg := NewGroup(ocgs.GetAt(i))
21 ctx.ResetStates(false)
22 ctx.SetState(ocg, true)
23 fname := "pdf_layers_" + ocg.GetName() + ".png"
24 fmt.Println(fname)
25 pdfdraw.Export(page, outputPath + fname)
26 i = i + 1
27 }
28}
29
30// Now draw content that is not part of any layer...
31ctx.SetNonOCDrawing(true)
32ctx.SetOCDrawMode(ContextE_NoOC)
33pdfdraw.Export(page, outputPath + "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