Some test text!

Hamburger Icon

Web / Guides / Extract layer

Extract layers from PDF using JavaScript

Make sure you have Full API enabled in WebViewer.

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

  <script src="../lib/core/webviewer-core.min.js"></script>
  <script src="../lib/core/pdf/PDFNet.js"></script>
    (async function() {
      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);

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

      // 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.setState(ocg, true);
          let fname = 'pdf_layers_';
          fname += await ocg.getName();
          fname += '.png';
          const pageBuffer = await pdfdraw.exportStream(page);

          //optionally save the blob to a file or upload to a server
          const layerBlob = new Blob([pageBuffer], { type: 'image/png' });

      // Now draw content that is not part of any layer...
      const nonLayerBuffer = await pdfdraw.exportStream(page);

      // optionally save the blob to a file or upload to a server
      const nonLayerBlob = new Blob([nonLayerBuffer], { type: 'image/png' });

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

Have questions? Connect with our experts on Discord.