Welcome folks today in this blog post we will be adding page numbers
at footer inside pdf documents using jspdf
library and we will be using javascript for this purpose. All the source code of the application will be shown below.
Get Started
In order to get started we need to include the jspdf library
and it’s cdn
like this inside our application
1 |
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script> |
After including the cdn
we need to write the business logic of the application inside our index.html
file like this
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 |
<script> 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); // PAGE NUMBERING // Add Page number at bottom-right // Get the number of pages 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'); </script> |
Now inside this block of code we have added four pages and also we have added the page numbers
or pagination to let users know which page is there inside pdf document. It is there at footer position.
If you open index.html
inside browser you will see the following screenshot