Add a new PDF Layer using JavaScript

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

1<html>
2 <script src="../lib/core/webviewer-core.min.js"></script>
3 <script src="../lib/core/pdf/PDFNet.js"></script>
4 <script>
5 (async function() {
6 Core.setWorkerPath('../lib/core');
7 let doc = await PDFNet.PDFDoc.create();
8 const builder = await PDFNet.ElementBuilder.create();
9 const writer = await PDFNet.ElementWriter.create();
10
11 // Create a layer
12 const imageLayer = await PDFNet.OCG.create(doc, 'Image Layer');
13 const cfg = await PDFNet.OCGConfig.create(doc, true);
14 cfg.setName('Default');
15
16 // Add the new OCG to the list of layers that should appear in PDF viewer GUI.
17 let layerOrderArray = await doc.createIndirectArray();
18 cfg.setOrder(layerOrderArray);
19 layerOrderArray.pushBack(await image_layer.getSDFObj());
20
21 // Start a new page
22 const page = await doc.pageCreate();
23 writer.beginOnPage(page); // Begin writing to the page
24
25 // Add new content to the page and associate it with one of the layers.
26 const nullEncoderHints = new PDFNet.Obj('0');
27 const img = await PDFNet.Image.createFromURL(doc, imagename, nullEncoderHints);
28 const img_obj = await img.getSDFObj();
29 img_obj.put('OC', imageLayer);
30 writer.writePlacedElement(await builder.createImageScaled(img, 300, 600, 200, -150));
31 await writer.end(); // save changes to the current page
32 doc.pagePushBack(page);
33 })()
34 </script>
35</html>

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

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales