jsPDF Tutorial to Add Page Numbers at Footer in PDF Documents Using Javascript Full Example For Beginners

jsPDF Tutorial to Add Page Numbers at Footer in PDF Documents Using Javascript Full Example For Beginners

 

 

 

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

 

 

<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

 

 

<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>

 

See also  How to get Full Path of Uploaded Image in Electron Application

 

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

 

 

 

 

 

Leave a Reply