Groups keyboard shortcuts have been updated
Dismiss
See shortcuts

Add link annotations to document automatically for URLs in text

53 views
Skip to first unread message

Matt Parizeau

unread,
Dec 19, 2016, 8:12:01 PM12/19/16
to PDFTron WebViewer
Q:

I have a PDF document with a URL which is clickable in other PDF viewers but not in WebViewer. Is it possible to have this link be clickable?

A:

You can add the following code to a config file to detect URLs in the text and add a link on the page:

$(document).on('viewerLoaded', function() {
 
var addedForPages = {};

 
var docViewer = readerControl.docViewer;
 
var urlRegex = /[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g;

  docViewer
.on('pageComplete', function(e, pageIndex) {
   
if (addedForPages[pageIndex]) {
     
return;
   
}
    addedForPages
[pageIndex] = true;

   
var doc = docViewer.getDocument();
    doc
.loadPageText(pageIndex, function(text) {

     
while ((match = urlRegex.exec(text)) != null) {
       
var startIndex = match.index;
       
var endIndex = startIndex + match[0].length;
        doc
.getTextPosition(pageIndex, startIndex, endIndex, function(quads) {
         
var firstChar = quads[0];
         
var lastChar = quads[quads.length - 1];
         
var topLeft = { x: Math.min(firstChar.x1, firstChar.x3), y: Math.min(firstChar.y1, firstChar.y3) };
         
var bottomRight = { x: Math.max(lastChar.x1, lastChar.x3), y: Math.max(lastChar.y1, lastChar.y3) };

         
var link = new Annotations.Link({
            rect
: [topLeft.x, topLeft.y, bottomRight.x, bottomRight.y]
         
});
          link
.PageNumber = pageIndex + 1;
          link
.addAction('U', new Actions.URI({uri: match[0]}));

         
var annotManager = docViewer.getAnnotationManager();
          annotManager
.addAnnotation(link);
          annotManager
.drawAnnotations(link.PageNumber, null, true);
       
});
     
}
   
});
 
});
});

Reply all
Reply to author
Forward
0 new messages