Some test text!

Text select events

Getting text from text select events

When users select text from a loaded document, this triggers an event that can be used to get the selected text. This is helpful in automatically creating annotations where the selected text is or perhaps extracting the text for creating free text annotations.

Getting selected text from events

The main event of interest triggered by DocumentViewer when text is selected is the textSelected event.

WebViewer({ ... }, viewerElement).then(instance => {
  const { documentViewer } = instance.Core;

  documentViewer.addEventListener('textSelected', (quads, selectedText, pageNumber) => {
    // quads will be an array of 'Quad' objects
    // text is the selected text as a string
    if (selectedText.length > 0) {

The textSelected event gets fired whenever the selected text on the document changes. It is worth considering using debouncing if you are only looking to handle this event once the selection has stopped.

Also the textSelected event fires once for each page with selected text. So if text is selected on page A and B, and the selected text on page A changed, the textSelected event will fire once for each page even though there weren't any changes for page B.

Getting selection from the TextSelect tool

You can also listen for the selectionComplete event on the TextSelect tool. This event does not return the selected text but we can still get the text from the DocumentViewer via getSelectedText.

WebViewer({ ... }, viewerElement).then(instance => {
  const { documentViewer, Tools } = instance.Core;

  const tool = documentViewer.getTool(Tools.ToolNames.TEXT_SELECT);
  tool.addEventListener('selectionComplete', (startQuad, allQuads) => {
    let selectedText = '';
    Object.keys(allQuads).forEach(pageNum => {
      const text = documentViewer.getSelectedText(pageNum);
      selectedText += text;
    // the startQuad and allQuads will have the X and Y values you want

Getting selected text from browser events

Get selected text by listening for a keydown or clipboard copy event.

WebViewer({ ... }, viewerElement).then(instance => {
  const { documentViewer } = instance.Core;
  const showSelectedText = () => {
    const page = documentViewer.getCurrentPage();
    const text = documentViewer.getSelectedText(page);

    if (!!text) {

  // Optionally use keyDown events
  documentViewer.addEventListener('keyDown', function (e) {
    if (e.keyCode == 67 && (e.ctrlKey || e.metaKey)) {
      console.log('Ctrl+C pressed');

  // Otherwise use the copy event
  const iframeWindow = instance.UI.iframeWindow;
  iframeWindow.addEventListener('copy', function (e) {
      console.log('Ctrl+C (copy) pressed');

Next steps

You can read up more on text extractions in our other text extraction guides !

Get the answers you need: Support

Upcoming Webinar: PDFTron SDK Tech Review | Nov 29, 2022 at 2 pm ET


The Platform


© 2022 PDFTron Systems Inc. All rights reserved.


Terms of Use