Some test text!

Hamburger Icon

Web / Guides / Add layer

Add a new PDF Layer using JavaScript

Make sure you have Full API enabled in WebViewer.

To add a PDF layer or OCG (optional content group) to a new document.

  <script src="../lib/core/webviewer-core.min.js"></script>
  <script src="../lib/core/pdf/PDFNet.js"></script>
    (async function() {
      let doc = await PDFNet.PDFDoc.create();
      const builder = await PDFNet.ElementBuilder.create();
      const writer = await PDFNet.ElementWriter.create();

      // Create a layer
      const imageLayer = await PDFNet.OCG.create(doc, 'Image Layer');
      const cfg = await PDFNet.OCGConfig.create(doc, true);

      // Add the new OCG to the list of layers that should appear in PDF viewer GUI.
      let layerOrderArray = await doc.createIndirectArray();
      layerOrderArray.pushBack(await image_layer.getSDFObj());

      // Start a new page
      const page = await doc.pageCreate();
      writer.beginOnPage(page); // Begin writing to the page

      // Add new content to the page and associate it with one of the layers.
      const nullEncoderHints = new PDFNet.Obj('0');
      const img = await PDFNet.Image.createFromURL(doc, imagename, nullEncoderHints);
      const img_obj = await img.getSDFObj();
      img_obj.put('OC', imageLayer);
      writer.writePlacedElement(await builder.createImageScaled(img, 300, 600, 200, -150));
      await writer.end();   // save changes to the current page

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

Get the answers you need: Chat with us