Welcome folks today in this blog post we will be using jspdf library
on how to embed html hyperlinks
inside pdf documents
in javascript. All the source code of the application is given below.
Get Started
In order to get started we need to make a index.html
file and copy paste the following code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<!DOCTYPE html> <html> <head> <title>jsPDF Embed HyperLinks in PDF Documents</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script> </head> <body> </body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </html> |
So you can see that we have included the cdn of jspdf
and jquery
. So here we need to make a pdf document inside jspdf
Now we will write some static paragraphs and we will have a button and on that button we will bind a button event listener
1 2 3 4 5 6 7 8 9 10 |
<div id="content"> <h3>Generate PDF files in client-side JavaScript</h3> <p>href="https://parall.ax/products/jspdf#"</p> <p>Or refer to the YouTube video: https://www.youtube.com/watch?v=CnprxD_sJFE<p> </div> <div id="editor"></div> <button id="cmd">Generate PDF</button> |
Now we will write the basic javascript
code which will be required to embed html hyperlinks inside pdf document
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
var doc = new jsPDF(); var specialElementHandlers = { '#editor': function (element, renderer) { return true; } }; $('#cmd').click(function () { doc.fromHTML($('#content').html(), 15, 15, { 'width': 170, 'elementHandlers': specialElementHandlers }); doc.save('sample-file.pdf'); }); |
Full Source Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<!DOCTYPE html> <html> <head> <title>jsPDF Embed HyperLinks in PDF Documents</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script> </head> <body> <div id="content"> <h3>Generate PDF files in client-side JavaScript</h3> <p>href="https://parall.ax/products/jspdf#"</p> <p>Or refer to the YouTube video: https://www.youtube.com/watch?v=CnprxD_sJFE<p> </div> <div id="editor"></div> <button id="cmd">Generate PDF</button> </body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> var doc = new jsPDF(); var specialElementHandlers = { '#editor': function (element, renderer) { return true; } }; $('#cmd').click(function () { doc.fromHTML($('#content').html(), 15, 15, { 'width': 170, 'elementHandlers': specialElementHandlers }); doc.save('sample-file.pdf'); }); </script> </html> |
If you open this index.html
file inside the browser you will see the following screenshot