Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Footer to pdf using jsPDF

I am generating pdf from jsPDF api , I want to add footer to each page with page number .

How to achieve this . It is having option of adding footer from fromHTML plugin , but I am writing without HTML.

var doc = new jsPDF("portrait","px","a4");
like image 552
Sumeet Kumar Yadav Avatar asked Nov 04 '15 06:11

Sumeet Kumar Yadav


3 Answers

You have to implement it yourself. You can do something like this:

var doc = new jsPDF();
doc.page=1; // use this as a counter.

function footer(){ 
    doc.text(150,285, 'page ' + doc.page); //print number bottom right
    doc.page ++;
};

// and call footer() after each doc.addPage()
like image 188
Bas van Stein Avatar answered Nov 13 '22 12:11

Bas van Stein


Stephen Collins is the best answer! It works well with jspdf-autotable plugin.

With this is made after all is added to the doc, so we can use easy the total page number!

Add some style to the Stephen Collins answer: "page x of total"

const addFooters = doc => {
  const pageCount = doc.internal.getNumberOfPages()

  doc.setFont('helvetica', 'italic')
  doc.setFontSize(8)
  for (var i = 1; i <= pageCount; i++) {
    doc.setPage(i)
    doc.text('Page ' + String(i) + ' of ' + String(pageCount), doc.internal.pageSize.width / 2, 287, {
      align: 'center'
    })
  }
}


let doc = new jsPDF()

doc.text(...)
doc.autoTable(...)
addFooters(doc)
doc.save()
like image 15
sainf Avatar answered Nov 13 '22 13:11

sainf


I know this post is old but I'm going to offer another solution. First define your total amount of pages. There's multiple ways to determine this so I won't go into that.

        var doc = new jsPDF('p', 'pt', 'letter');
        doc.page = 1; // use this as a counter.
        var totalPages = 10; // define total amount of pages
        // HEADER
        doc.setFontSize(20);//optional
        doc.setTextColor(40);//optional
        doc.setFontStyle('normal');//optional
        doc.text("Report", 50, 22);// set your margins
        // FOOTER
        var str = "Page " + doc.page  + " of " +  totalPages;
        doc.setFontSize(10);// optional
        doc.text(str, 50, doc.internal.pageSize.height - 10);//key is the interal pageSize function


        // Add Page content
        .....


        //Add new page and increase page count
        doc.addPage();
        doc.page ++;
        //Begin process all over again.

This works well in a loop as you can set your page count by taking your array.length + 1 (as it's zero based).

like image 8
Reginald Goolsby Avatar answered Nov 13 '22 14:11

Reginald Goolsby