Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting notified when the user clicks a link in an embedded PDF

I got a PDF embedded in my page, and I'd like to set something like a Javascript-callback to be called whenever the user clicks a link within the PDF.

Is there a way to accomplish this?

like image 207
DeX3 Avatar asked May 09 '11 08:05

DeX3


2 Answers

If you check out the Acrobat JS Reference for the minimum version you want to support, you'll see documentation on the HostContainer object.

In the PDF:

this.hostContainer.messageHandler =
{
  onMessage: function(messageArray)
  {
    for(var i = 0; i < messageArray.length; i++)
      console.println("Message " + i + ": " + messageArray[i]);
  },
  onError: function(error, messageArray){ },
  onDisclose: function() {return true;}
};

In your HTML, assuming your PDF is inside an <object id="thePdf"> tag:

function messageFunc(messageArray) {
    for(var i = 0; i < messageArray.length; i++)
      alert("Message " + i + ": " + messageArray[i]);
}

document.getElementById("thePdf").messageHandler = { onMessage: messageFunc };

In your PDF, you'd also need to modify the links so they have a JS action that would post a message to the containing web page. This could be done programmatically (varying wildly depending on the language/library you use), or manually in Acrobat Pro.

this.hostContainer.postMessage(["urlClicked", "http://blah.blah.blah..."]);

Not terribly hard, but no one's ever heard of it. I'd be stunned if this worked anywhere outside an Adobe viewer (Reader/Acrobat) for the next several years.

If you want to send a message from your HTML to the PDF for some reason, it goes something like this:

var thePDF = document.getElementById("thePdf");
thePDF.postMessage(["This", "is", "an", "array", "too."]);

You could even yank out all the existing links and have the PDF request the links be opened by the wrapping HTML page... that way you can give the new windows names, close them from JS, etc. You can get down right snazzy.

But you have to be able to change the PDFs.

like image 121
Mark Storer Avatar answered Sep 27 '22 20:09

Mark Storer


Your link is probably represented as a "Link annotation" inside your PDF file. Annotations in PDF can contain "Additional Actions", you could use a pdf processing software like iText (free for non commercial use) or Amyuni PDF Creator(commercial, usual disclaimer applis) to add a Javascript action to the "Additional Actions" collection of your link(s). You can invoke a page or method in your server using this Javascript code.

like image 24
yms Avatar answered Sep 27 '22 20:09

yms