Welcome folks today in this blog post we will be inserting colorful popup annotations inside pdf document using jspdf library in javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an index.html
file and inside it we will be including the jspdf library cdn as shown below
index.html
1 2 3 4 5 6 7 |
<head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="https://parall.ax/parallax/js/jspdf.js"></script> <body> <button onclick="generatePDF()">Generate PDF</button> </body> </html> |
As you can see we have the button of generate pdf. When we click this button we will be able to insert the annotations inside the pdf document and download it as pdf document
Now we will be writing the script.js
which will be the custom javascript code as shown below
script.js
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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
function generatePDF() { var pdf = new jsPDF('p', 'pt', 'letter'); var y = 20; var w; var text = 'Text Annotations'; pdf.text(text, 20, y); pdf.setFontSize(12); y += pdf.getLineHeight() * 2; pdf.text("Text Annotation With Popup (closed)", 20, y); pdf.createAnnotation({ type: 'text', title: 'note', bounds: { x: 0, y: y, w: 200, h: 80 }, contents: 'This is text annotation (closed by default)', open: false }); y += pdf.getLineHeight() * 5; pdf.text("Text Annotation With Popup (opened)", 20, y); pdf.createAnnotation({ type: 'text', title: 'another note', bounds: { x: 0, y: y, w: 200, h: 80 }, contents: 'This is a text annotation (opened)', open: true }); y += pdf.getLineHeight() * 5; pdf.text("Free Text Annotation", 20, y); pdf.createAnnotation({ type: 'freetext', bounds: { x: 0, y: y + 10, w: 200, h: 20 }, contents: 'This is a freetext annotation', color: '#ff0000' }); pdf.save("output.pdf") } |
As you can see we are using the createAnnotation()
method inside the jspdf library to create the text annotatio and here we are passing the type of the annotation. It is set to freetext and then it takes the second argument to be the bounds which are x and y coordinates and then we have the width and height of the annotation. And also we have the content of the annotation which will be shown when we hover on the annotation. And also we provide the hexadecimal color to the annotation. And lastly we are saving the pdf document with the custom filename.