Welcome folks today in this blog post we will be adding the page numbers at footer in pdf document using jspdf library in browser using javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to include the jspdf
library cdn as shown below
1 2 3 4 5 6 7 8 9 |
<!doctype> <html> <head> <title>jsPDF Convert PDF to Base64 String</title> <script type="text/javascript" src=" https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script> </head> <body> </body> </html> |
Now we need to write the javascript code where we will be using the jspdf
library to add the text
inside the pdf document.
1 2 3 4 5 6 7 8 9 10 11 12 |
var doc = new jsPDF('p', 'mm', 'a4'); // Some stuff doc.text("Some text", 74, 150); doc.addPage(); doc.text("Some text", 74, 150); doc.addPage(); doc.text("Some text", 74, 150); doc.addPage(); doc.text("Some text", 74, 150); doc.addPage(); doc.text("Last page", 74, 150); |
As you can see we are using the text()
method to place the text at x and y coordinates. And also we are adding a new page using the addPage()
method
And now we need to enter the page numbers
at the footer position in pdf document using the jspdf
library. And now we will be calculating the number of pages inside the pdf document. And after that we are using the for loop
to iterate over all the pages in pdf document
1 2 3 4 5 6 7 8 9 10 11 12 |
const pageCount = doc.internal.getNumberOfPages(); // For each page, print the page number and the total pages for (var i = 1; i <= pageCount; i++) { // Go to page i doc.setPage(i); //Print Page 1 of 4 for example doc.text('Page ' + String(i) + ' of ' + String(pageCount), 210 - 20, 297 - 30, null, null, "right"); } // Save the doc doc.save('test.pdf'); |
As you can see in the for loop
we are using the setPage()
method to set the page number inside the pdf document and after that we are adding the page numbers inside the pdf document at the footer position.