How to rotate individual pages of pdf and safe the rotation in database so that next time a user opens that pdf they get the pages with the saved rotation

Hello there,

In WebViewer 8.0 you would need to enable the left panel by default when the document is loaded, and then use event delegation on left panel to watch for button clicks on the single page rotation buttons.

const { documentViewer } = instance.Core
documentViewer.addEventListener('documentLoaded',()=>{
  let panelElement = instance.docViewer.getScrollViewElement().closest('#app').querySelector('[data-element="thumbnailsPanel"]');
  if (!parentElement) {
    instance.UI.toggleElementVisibility('leftPanel');
    panelElement = instance.docViewer.getScrollViewElement().closest('#app').querySelector('[data-element="thumbnailsPanel"]');
  }
  panelElement.addEventListener('click', (e) => {
    if (e.target.dataset?.element === 'thumbRotateClockwise' || e.target.dataset?.element === 'thumbRotateCounterClockwise') {
      // The single page rotations are performed asychronously and there are no events firings in 8.0, so we have to manually add a delay before the page finishes rotating itself.
      setTimeout(() => {
        const pageNumber = parseInt(e.target.parentElement.previousSibling.textContent);
        const rotation = instance.docViewer.getDocument().getPageRotation(pageNumber);
        console.log('page ', pageNumber, ' self rotation is ', rotation);
      }, 500);
    }
  });
})

If you have the option to upgrade to the latest WebViewer, you can listen to the ‘pagesUpdated’ event on documentViewer and the code becomes shorter & cleaner:

const { documentViewer } = instance.Core
documentViewer.addEventListener('pagesUpdated',(changes)=>{
    changes.contentChanged.forEach(pageNumber=>{
        const rotation = documentViewer.getDocument().getPageRotation(pageNumber)
        console.log('page ', pageNumber, ' self rotation is ', rotation);
    })
})

For both situations, when you load the document back, you can use documentViewer.getDocument().rotatePages to rotate to your saved rotations.

assuming we have the saved page rotations data structured like this

const rotationData = [
  {pageNumber: 1, rotation: 180},
  {pageNumber: 3, rotation: 90},
  {pageNumber: 4, rotation: 270},
]

We can use the following code to rotate our individual pages back:

const { documentViewer } = instance.Core
documentViewer.addEventListener('documentLoaded',()=>{
  rotationData.forEach(page=>{
    const originalRotation = documentViewer.getDocument().getPageRotation(page.pageNumber)
    if (originalRotation !== page.rotation) {
      documentViewer.getDocument().rotatePages([page.pageNumber], (page.rotation-originalRotation)/90);
    }
  })
})
1 Like