Some test text!

< Web samples

Separate Layers (OCGs) in a PDF

This JavaScript sample lets you identify & separate layers in a PDF document (no servers or other external dependencies required). This sample also gives you the option to show or hide different OCG (Optional Content Group) layers in a PDF document. This functionality is commonly used in the construction & engineering space where users can hide irrelevant graphical content (HVAC, Electrical or Piping elements) from a blueprint. This sample works on all browsers (including IE10) and mobile devices without using plug-ins. For an example of this functionality visit our PDF Layer Separation demo.

Step 1: Get your free trial license key, or sign in

Start Trial
Sign in

Step 2: Add the code:

var viewerElement = document.getElementById('viewer');
var viewer = new PDFTron.WebViewer({
  path: '../../../lib',
  l: window.sampleL,
  initialDoc: '../../../samples/files/construction-drawing-final.pdf',
}, viewerElement);

viewerElement.addEventListener('documentLoaded', function() {
  var viewerInstance = viewer.getInstance();
  var docViewer = viewerInstance.docViewer;
  var doc = docViewer.getDocument();
  var layersElement = document.getElementById('layers');

  docViewer.on('pageComplete', function() {
    viewerInstance.closeElement('loadingModal');
  });

  // Get PDF layers array
  doc.getLayersArray().then(function(layers) {
    layers.forEach(function(layer, index) {
      var input = document.createElement('input');
      input.id = layer.name;
      input.type = 'checkbox';
      input.checked = layer.visible;
      input.onchange = function(e) {
        viewerInstance.openElement('loadingModal');
        // Show/hide a layer
        layers[index].visible = e.target.checked;
        doc.setLayersArray(layers);
        // Redraw the canvas
        docViewer.refreshAll();
        docViewer.updateView();
      };

      var label = document.createElement('label');
      label.htmlFor = layer.name;
      label.innerHTML = layer.name;

      var lineBreak = document.createElement('br');

      layersElement.appendChild(input);
      layersElement.appendChild(label);
      layersElement.appendChild(lineBreak);
    });
  });
});