Adding an annotation in the center of the current view

47 views
Skip to first unread message

Matt Parizeau

unread,
Mar 9, 2021, 7:54:34 PM3/9/21
to PDFTron WebViewer
Q: How can I add an annotation programmatically to the center of the current viewport?

A: 
You can calculate the center of the viewport using the scrollview element https://www.pdftron.com/api/web/CoreControls.DocumentViewer.html#getScrollViewElement and convert the window coordinates to page coordinates to add the annotation to the page. https://www.pdftron.com/documentation/web/guides/coordinates/#converting-between-window-and-viewer-page-coordinates

const { docViewer, annotManager, Annotations } = instance;

const getPage = function(displayMode, windowCoordinates) {
  const page = displayMode.getSelectedPages(windowCoordinates, windowCoordinates);
  const clickedPage = (page.first !== null) ? page.first : docViewer.getCurrentPage();
  return clickedPage;
};

const getCenter = function() {
  const viewerElement = docViewer.getScrollViewElement();

  const top = viewerElement.scrollTop + viewerElement.offsetTop;
  const bottom = top + viewerElement.offsetHeight;
  const left = viewerElement.scrollLeft + viewerElement.offsetLeft;
  const right = left + viewerElement.offsetWidth;

  const windowCoordinateCenter = {
    x: (left + right) / 2,
    y: (top + bottom) / 2
  };

  const displayMode = docViewer.getDisplayModeManager().getDisplayMode();

  const pageNumber = getPage(displayMode, windowCoordinateCenter);

  const pageCoordinates = displayMode.windowToPage(windowCoordinateCenter, pageNumber);

  return pageCoordinates;
};

const addAnnotationToCenter = function() {
  const centerPageCoordinates = getCenter();

  const annotationWidth = 20;
  const annotationHeight = 20;

  const rectangleAnnot = new Annotations.RectangleAnnotation();
  rectangleAnnot.PageNumber = centerPageCoordinates.pageNumber;
  // values are in page coordinates with (0, 0) in the top left
  rectangleAnnot.X = centerPageCoordinates.x - (annotationWidth / 2);
  rectangleAnnot.Y = centerPageCoordinates.y - (annotationHeight / 2);
  rectangleAnnot.Width = annotationWidth;
  rectangleAnnot.Height = annotationHeight;
  rectangleAnnot.Author = annotManager.getCurrentUser();

  annotManager.addAnnotation(rectangleAnnot);
  // need to draw the annotation otherwise it won't show up until the page is refreshed
  annotManager.redrawAnnotation(rectangleAnnot);
};
Reply all
Reply to author
Forward
0 new messages