Welcome folks today in this blog post we will be drawing a colored and filled
rectangle and write some text
over it in pdf document using jspdf 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 copy paste the following code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.2.3/jspdf.plugin.autotable.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script> </head> <body> </body> </html> |
And now inside the html5 code we are including the jspdf
library cdn and also we are including the html2canvas
library cdn. And now we need to write the html
code as shown below
1 |
<button onclick="generatePDF()">Generate PDF</button> |
Now as you can see we have added a button which is used to generate the pdf document. Now we have added the onclick
event listener which is the method called generatePDF()
now we need to define this method in javascript.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
function generatePDF() { var doc = new jsPDF(); doc.setFontSize(17); doc.setFillColor(0,0,0); doc.rect(100, 20, 60, 10, 'F'); doc.setTextColor(255, 255, 255); doc.text(100,28, 'USD.00'); doc.save("output.pdf") } </script> |
As you can see we are using the methods to set the font size and the background fill color and then we are drawing the rectangle
shape inside the pdf document and then inside it we are writing the text which is usd
inside it. And then we are saving the pdf document using the save()
method