How to Detect Linked PDF on a Page and Show Message to Download Adobe Reader Using Jquery

How to detect linked PDF on a page and show message to download Adobe reader using jquery?

var tip = "<p>Most computers will open PDF documents ";
tip += "automatically, but you may";
tip += "need to download <a title='Link to Adobe website-opens in a new window'";
tip +=" href='http://www.adobe.com/products/acrobat/readstep2.html'
target='_blank'>Adobe Reader</a>.</p>";

$(document).ready(function(){

//IF NUMBER OF PDF LINKS IS MORE THAN ZERO INSIDE DIV WITH ID maincontent
//THEN THIS WILL PUT TIP PARAGRAPH AS LAST CHILD OF DIV
if($("div#maincontent a[href*='/pdf']").length>0){
$("div#maincontent").children(":last-child").after(tip);
}
});

check it here

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

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.

Hyperlink Detection from PDF

You can use Docotic.Pdf library for links extraction (disclaimer: I work for the company).

Below is the code that opens specified file, finds all hyperlinks, collects information about position of each link and draws rectangle around each links.

After that the code creates new PDF (with links in rectangles) and a text file with collected information. In the end, both created files are opened in default viewers.

public static void ListAndHighlightLinks(string inputFile, string outputFile, string outputTxt)
{
using (PdfDocument doc = new PdfDocument(inputFile))
{
StringBuilder sb = new StringBuilder();

for (int i = 0; i < doc.Pages.Count; i++)
{
PdfPage page = doc.Pages[i];
foreach (PdfWidget widget in page.Widgets)
{
PdfActionArea actionArea = widget as PdfActionArea;
if (actionArea == null)
continue;

PdfUriAction linkAction = actionArea.Action as PdfUriAction;
if (linkAction == null)
continue;

Uri url = linkAction.Uri;
PdfRectangle rect = actionArea.BoundingBox;

// add information about found link into string buffer
sb.Append("Page ");
sb.Append(i.ToString());
sb.Append(" : ");
sb.Append(rect.ToString());
sb.Append(" ");
sb.AppendLine(url.ToString());

// draw rectangle around found link
page.Canvas.DrawRectangle(rect);
}
}

// save document with highlighted links and text information about links to files
doc.Save(outputFile);
System.IO.File.WriteAllText(outputTxt, sb.ToString());

// open created PDF and text file in default viewers
System.Diagnostics.Process.Start(outputTxt);
System.Diagnostics.Process.Start(outputFile);
}
}

You can use the sample code with a call like this:

ListAndHighlightLinks("input.pdf", "output.pdf", "links.txt");

Change the entry of the pdf file to pass the exact path to it by me

You need 2 modifications to make it work. Add "multiple" attribute to the input to allow the user to select multiple pdf files.

  <input type="file" multiple accept=".pdf" required id="files" class="form-control">

And then loop through the array of files to calculated the number of pages in each:

[].forEach.call(event.target.files, file => {

Update:
Two additional changes have been added.

1. We must reset the file input at the end of the loop. Otherwise it will only work once and then stop.

// clear file selector to allow reuse
event.target.value = "";

2. We also must set the value "workerSrc" to prevent a console warning message. More details about that here.

pdfjsLib.GlobalWorkerOptions.workerSrc = '//cdnjs.cloudflare.com/ajax/libs/pdf.js/2.7.570/pdf.worker.min.js';

Run the code snippet to see how it works (hold shift key down to select multiple pdf files):

let inputElement = document.getElementById('files')

inputElement.onchange = function(event) {

[].forEach.call(event.target.files, file => {

//var file = event.target.files[i];

//Step 2: Read the file using file reader
var fileReader = new FileReader();

fileReader.onload = function() {

//Step 4:turn array buffer into typed array
var typedarray = new Uint8Array(this.result);

//Step 5:pdfjs should be able to read this
const loadingTask = pdfjsLib.getDocument(typedarray);
loadingTask.promise.then(pdf => {

document.getElementById('result').innerHTML += "<li>" + file.name + " has " + pdf.numPages + "pages</li>";
// The document is loaded here...
});

};
//Step 3:Read the file as ArrayBuffer
fileReader.readAsArrayBuffer(file);

})

// clear file selector to allow reuse
event.target.value = "";

}

// Must set worker to avoid error: Deprecated API usage: No "GlobalWorkerOptions.workerSrc" specified.

pdfjsLib.GlobalWorkerOptions.workerSrc = '//cdnjs.cloudflare.com/ajax/libs/pdf.js/2.7.570/pdf.worker.min.js';
<div class="container">
<h4 class="text-center">Count Pages inside PDF Document</h4>
<div class="form-group container">
<input type="file" multiple accept=".pdf" required id="files" class="form-control">
</div>
<br><br>
<ol class="text-primary container" id="result"></ol>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.7.570/pdf.min.js" integrity="sha512-g4FwCPWM/fZB1Eie86ZwKjOP+yBIxSBM/b2gQAiSVqCgkyvZ0XxYPDEcN2qqaKKEvK6a05+IPL1raO96RrhYDQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">


Related Topics



Leave a reply



Submit