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 PDFTron WebViewer Class: DocumentViewer 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);
};