Extract layers from PDF in Android

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

1PDFDoc doc = new PDFDoc(filename);
2Page page = doc.getPage(1);
3
4Config init_cfg = doc.getOCGConfig();
5Context ctx = new Context(init_cfg);
6
7PDFDraw pdfdraw = new 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.
15Obj ocgs = doc.getOCGs(); // Get the array of all OCGs in the document.
16int i, sz = (int) ocgs.size();
17for (i = 0; i < sz; ++i) {
18 Group ocg = new Group(ocgs.getAt(i));
19 ctx.resetStates(false);
20 ctx.setState(ocg, true);
21 String 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...
26ctx.setNonOCDrawing(true);
27ctx.setOCDrawMode(Context.e_NoOC);
28pdfdraw.export(page, output_path + "pdf_layers_non_oc.png");

PDF layers (OCG)
Full sample code which demonstrates how to create, extract, render PDF layers.

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales