Some test text!

menu
Add layerkeyboard_arrow_down

Add a new PDF Layer using JavaScript

Only available with the Full API

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

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

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