Search code examples
jspdfhtml2pdf

html2pdf / jspdf footer not showing properly


Trying to get a footer to show up using html2pdf. Pretty standard code using what I found on Github, SO and others.

document.getElementById('generate').onclick = function () {

    var element = document.getElementById('element-to-print');

    var opt = {
    margin:       0.5,
    filename:     '@pdf_filename',
    pagebreak:    { mode: 'avoid-all' },
    image:        { type: 'jpeg', quality: 0.98 },
    jsPDF:        { unit: 'in', format: 'letter', orientation: 'portrait' }
    };



html2pdf().from(element).set(opt).toPdf().get('pdf').then((pdf) => {
    var totalPages = pdf.internal.getNumberOfPages();

    for (i = 1; i <= totalPages; i++) {
        pdf.setPage(i);
        pdf.setFontSize(10);
        pdf.setTextColor(150);
        pdf.text('PageNum ' + i + ' of ' + totalPages, pdf.internal.pageSize.getWidth() - 115, pdf.internal.pageSize.getHeight() - 10);
    }                 

}).save();

The problem is the footer doesn't appear on the PDF. I know it's somewhere in the file because if I search on "PageNum", I get hits but no display.

If I take out the line jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' } the footer will appear fine but there will be a weird pagination issue and pages (2,3,4++) won't have correct margins.

Fiddle


Solution

  • For future reference, I figured out my problem. The jsPDF unit is set to 'in' but my footer calculations are assuming 'px' (getWidth() - 115). I just tweaked the calculations to something like getWidth() - 5 and it worked