javascriptjspdfhtml2pdf

Html2pdf - Adding text to new page in already generated PDF not working


I am trying to add a footer to each page in my pdf file I am creating using Html2pdf.

content = document.querySelector(".pdf");
const config = {
   filename:  'document.pdf',
   image: {type: 'jpeg',quality: 1.0},
   html2canvas: {dpi: 300, letterRendering: true},
   jsPDF: {orientation: 'portrait', unit: 'in', format: 'a4'},
   // pdfCallback: pdfCallback
}
$("button").on('click', function() {
  html2pdf().from(content).set(config).toPdf().get('pdf').then((pdf) => {
      var totalPages = pdf.internal.getNumberOfPages();

      pdf.addPage();
      pdf.setFontSize(22);
      pdf.text(10,10,"Hello World");
      pdf.save('document.pdf');

  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.9.3/html2pdf.bundle.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div classs="pdf">
  Original Page
</div>

<button>Get PDF</button>

This does add a new page, but the text is not visible on that page. What am I doing wrong here?


Solution

  • You had several small mistakes that added up to your text not showing:

    Here is the fiddle, as it doesn't work in SO's snippets https://jsfiddle.net/gm8p9a3c/

        content = document.querySelector(".pdf");
        const config = {
           filename:  'document.pdf',
           image: {type: 'jpeg',quality: 1.0},
           html2canvas: {dpi: 300, letterRendering: true},
           jsPDF: {orientation: 'portrait', unit: 'in', format: 'a4'},
           // pdfCallback: pdfCallback
        }
        $("button").on('click', function() {
          html2pdf().from(content).set(config).toPdf().get('pdf').then((pdf) => {
              var totalPages = pdf.internal.getNumberOfPages();
    
              pdf.addPage();
              pdf.setFontSize(22);
              pdf.text("Hello World", 1, 1);
              pdf.save('document.pdf');
    
          })
        })