Some test text!

menu
Extract layerkeyboard_arrow_down

Extract layers from PDF using JavaScript

Only available with the Full API

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

<html>
  <script src="../lib/core/CoreControls.js"></script>
  <script src="../lib/core/pdf/PDFNet.js"></script>
  <script>
    (async function() {
      CoreControls.setWorkerPath('../lib/core');
      const doc = await PDFNet.PDFDoc.createFromURL(filename);
      const page = await doc.getPage(1);

      const initCfg = await doc.getOCGConfig();
      const ctx = await PDFNet.OCGContext.createFromConfig(initCfg);

      const pdfdraw = await PDFNet.PDFDraw.create();
      pdfdraw.setImageSize(1000, 1000);
      pdfdraw.setOCGContext(ctx);

      // Disable drawing of content that is not optional (i.e. is not part of any layer).
      ctx.setNonOCDrawing(false);

      // Now render each layer in the input document to a separate image.
      const ocgs = await doc.getOCGs(); // Get the array of all OCGs in the document.
      let i;
      const sz = await ocgs.size();
      for (i = 0; i < sz; ++i) {
          const ocg = await PDFNet.OCG.createFromObj(await ocgs.getAt(i));
          ctx.resetStates(false);
          ctx.setState(ocg, true);
          let fname = 'pdf_layers_';
          fname += await ocg.getName();
          fname += '.png';
          const pageBuffer = await pdfdraw.exportStream(page);
          saveAs(new Blob([pageBuffer], {type: 'image/png'}), fname);
      }

      // Now draw content that is not part of any layer...
      ctx.setNonOCDrawing(true);
      ctx.setOCDrawMode(PDFNet.OCGContext.OCDrawMode.e_NoOC);
      const nonLayerBuffer = await pdfdraw.exportStream(page);
      saveAs(new Blob([nonLayerBuffer], {type: 'image/png'}), 'pdf_layers_non_oc.png');
    })()
  </script>
</html>

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

Get the answers you need: Support

close

Free Trial

Get unlimited trial usage of PDFTron SDK to bring accurate, reliable, and fast document processing capabilities to any application or workflow.

Select a platform to get started with your free trial.

Unlimited usage. No email address required.

Join our live demo to learn about use cases & capabilities for WebViewer

Learn more
close