Some test text!

menu
search
chevron_right Web samples

Snap-to lines & objects in pDFs using JavaScript

This JavaScript sample illustrates how to use the snap API to automatically detect and snap-to the nearest control point. This is commonly used to make measuring the distance between two points in a drawing or blueprint more intuitive for users. This sample works on all browsers (including IE10) and mobile devices without using plug-ins. Too see an example visit our Snap-to Demo.

To run this sample, get started with a free trial of PDFTron SDK.

JavaScript

HTML

(() => {
  const getMouseLocation = (e) => {
    const scrollElement = readerControl.docViewer.getScrollViewElement();
    const scrollLeft = scrollElement.scrollLeft || 0;
    const scrollTop = scrollElement.scrollTop || 0;

    return {
      x: e.pageX + scrollLeft,
      y: e.pageY + scrollTop
    };
  };

  const mouseToPagePoint = (e) => {
    const displayMode = readerControl.docViewer.getDisplayModeManager().getDisplayMode();
    const windowPoint = getMouseLocation(e);

    const page = displayMode.getSelectedPages(windowPoint, windowPoint);
    const pageIndex = (page.first !== null) ? page.first : readerControl.docViewer.getCurrentPage() - 1;

    return {
      point: displayMode.windowToPage(windowPoint, pageIndex),
      pageNumber: pageIndex + 1
    };
  };

  $(document).on('documentLoaded', () => {
    const lineAnnot = new Annotations.LineAnnotation();
    lineAnnot.setStartPoint(0, 0);
    lineAnnot.setEndPoint(0, 0);
    lineAnnot.PageNumber = 1;

    const annotManager = readerControl.docViewer.getAnnotationManager();
    annotManager.addAnnotation(lineAnnot);

    readerControl.docViewer.on('mouseMove', (jqueryE, e) => {
      const result = mouseToPagePoint(e);
      const pagePoint = result.point;
      const pageNumber = result.pageNumber;
      const oldPageNumber = lineAnnot.PageNumber;

      lineAnnot.PageNumber = pageNumber;
      lineAnnot.setStartPoint(pagePoint.x, pagePoint.y);
      // refresh old page since line annotation has been removed from it
      if (pageNumber !== oldPageNumber) {
        annotManager.drawAnnotations(oldPageNumber);
      }

      readerControl.docViewer.snapToNearest(pageNumber, pagePoint.x, pagePoint.y).then((snapPoint) => {
        lineAnnot.setEndPoint(snapPoint.x, snapPoint.y);
        annotManager.redrawAnnotation(lineAnnot);
      });
    });
  });
})(window);
// eslint-disable-next-line spaced-comment
//# sourceURL=config.js
close

Free Trial

Get unlimited trial usage of PDFTron SDK to bring accurate, reliable, and fast document processing capabilities to any application or workflow.

Select a platform to get started with your free trial.

Unlimited usage. No email address required.

PDFTron Receives USD$71 Million Growth Investment Led By Silversmith Capital Partners

Learn more
close