Welcome folks today in this blog post we will be adding page numbers in header in all pages inside pdf document using javascript in browser. 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 calculating the number of pages present inside the pdf and then we will be showing the page numbers in headers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var doc = jsPDF(); doc.addPage(); doc.addPage(); doc.addPage(); doc.addPage(); var pageCount = doc.internal.getNumberOfPages(); //Total Page Number for(i = 0; i < pageCount; i++) { doc.setPage(i); let pageCurrent = doc.internal.getCurrentPageInfo().pageNumber; //Current Page doc.setFontSize(12); doc.text('page: ' + pageCurrent + '/' + pageCount, 10, 10); } doc.save("hello.pdf") |
As you can see we are adding empty pages inside pdf document using the addPage()
methods. Now we are looping through to the pageCount which is the total number of pages present inside the pdf document. And for each loop we are targeting the top left position of the page and rendering out the current page number of the pdf document as shown below