Some test text!

Search
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.

<html>
  <script src="../lib/core/webviewer-core.min.js"></script>
  <script src="../lib/core/pdf/PDFNet.js"></script>
  <script>
    (async function() {
      Core.setWorkerPath('../lib/core');
      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);
      cfg.setName('Default');

      // Add the new OCG to the list of layers that should appear in PDF viewer GUI.
      let layerOrderArray = await doc.createIndirectArray();
      cfg.setOrder(layerOrderArray);
      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
      doc.pagePushBack(page);
    })()
  </script>
</html>

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

Trial setup questions? Ask experts on Discord
Need other help? Contact Support
Pricing or product questions? Contact Sales