Extract layers from PDF on Server/Desktop

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

1$doc = new PDFDoc($filename);
2$page = $doc->GetPage(1);
3
4$init_cfg = $doc->GetOCGConfig();
5$ctx = new Context($init_cfg);
6
7$pdfdraw = new PDFDraw();
8$pdfdraw->SetImageSize(1000, 1000);
9$pdfdraw->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).
12$ctx->SetNonOCDrawing(false);
13
14// Now render each layer in the input document to a separate image.
15$ocgs = $doc->GetOCGs(); // Get the array of all OCGs in the document.
16$sz = $ocgs->Size();
17for ($i=0; $i<$sz; ++$i) {
18 $ocg = new Group($ocgs->GetAt($i));
19 $ctx->ResetStates(false);
20 $ctx->SetState($ocg, true);
21 $fname = "pdf_layers_".$ocg->GetName().".png";
22 $pdfdraw->Export($page, $output_path.$fname);
23}
24
25// Now draw content that is not part of any layer...
26$ctx->SetNonOCDrawing(true);
27$ctx->SetOCDrawMode(Context::e_NoOC);
28$pdfdraw->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