Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

jsPDF Tutorial to Add Page Numbers in Header in All Pages inside PDF Document in Browser Using JS

Posted on December 16, 2022

 

 

 

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

 

 

JavaScript
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

 

 

 

Recent Posts

  • Android Java Project to Crop,Scale & Rotate Images Selected From Gallery and Save it inside SD Card
  • Android Kotlin Project to Load Image From URL into ImageView Widget
  • Android Java Project to Make HTTP Call to JSONPlaceholder API and Display Data in RecyclerView Using GSON & Volley Library
  • Android Java Project to Download Youtube Video Thumbnail From URL & Save it inside SD Card
  • Android Java Project to Embed Google Maps & Add Markers Using Maps SDK
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme