meles
meles

Reputation: 456

How to toggle visibility of a PDF layer in PDF.js

I have a PDF file with multiple layers. In Adobe Acrobat I can toggle the visibility of those layers via JavaScript included in the PDF. PDF.js, like many others viewers do not support JS within PDFs. But the layers are diplayed in the side pane of the viewer - where I can toggle the visibility. How can I toggle the visibility via JS, triggered by a button outside of the viewer?

enter image description here

Upvotes: 1

Views: 2415

Answers (1)

meles
meles

Reputation: 456

Clone this project https://github.com/mozilla/pdf.js.git and use the viewer at web/viewer.js. The following JavaScript code creates a button and adds an event listener to it. The event listener calls the function PDFViewerApplication.pdfLayerViewer._optionalContentConfig.setVisibility() to adapt the visibility and PDFViewerApplication.pdfLayerViewer.eventBus.dispatch()to update the state.

//Create a button a position it
let btn = document.createElement("button")
btn.style.zIndex = 100;
btn.style.zIndex = 100
btn.style.position = "absolute"
btn.style.height = "30px"
btn.style.top = "100px"
btn.style.left = "200px"
btn.innerHTML = "Toggle Layer"


//store the state
btn.visibilityStatus = false

//bind event to it
btn.addEventListener("click", () => { 
    //toggleVariable
    btn.visibilityStatus = !btn.visibilityStatus

    //set the layer visibility 
    //setVisibility(Layer-ID, visibility)
    PDFViewerApplication.pdfLayerViewer._optionalContentConfig.setVisibility("10113R", btn.visibilityStatus)

    //Apply changes
    PDFViewerApplication.pdfLayerViewer.eventBus.dispatch("optionalcontentconfig", {
        source: PDFViewerApplication.pdfLayerViewer,
        promise: Promise.resolve(PDFViewerApplication.pdfLayerViewer._optionalContentConfig),
    });
  })

document.body.prepend(btn)

Upvotes: 1

Related Questions