Is it possible to save HTML page as PDF using JavaScript or jquery?

Viewed 347763

Is it possible to save HTML page as PDF using JavaScript or jquery?

In Detail:

I generated one HTML Page which contains a table . It has one button 'save as PDF'. If user clicks that button then that HTML page has to convert as PDF file.

Is it possible using JavaScript or jquery?

13 Answers

I used jsPDF and dom-to-image library to export HTML to PDF.

I post here as reference to whom concern.

$('#downloadPDF').click(function () {
    domtoimage.toPng(document.getElementById('content2'))
      .then(function (blob) {
          var pdf = new jsPDF('l', 'pt', [$('#content2').width(), $('#content2').height()]);
          pdf.addImage(blob, 'PNG', 0, 0, $('#content2').width(), $('#content2').height());
          pdf.save("test.pdf");
      });
});

Demo: https://jsfiddle.net/viethien/md03wb21/27/

It is much easier and reliable to convert html to pdf server side. We are using Google Puppeteer. It is well maintained with wrappers for any server side language of your choosing. Puppeteer uses headless Chrome to generate screenshots and/or PDF files. It will save you a LOT of headache especially if you need to generate complex PDF files with tables, images, graphs, multiple pages and so

https://developers.google.com/web/tools/puppeteer/

Had similar issue, could not use jspdf since my legacy code contained multiple tables with several colspan inside. In Jspdf thead > th's must match tbody > tr > td

I ended up using html2pdf package which worked for me

on your file add the library

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.8.1/html2pdf.bundle.min.js" integrity="sha512-vDKWohFHe2vkVWXHp3tKvIxxXg0pJxeid5eo+UjdjME3DBFBn2F8yWOE0XmiFcFbXxrEOR1JriWEno5Ckpn15A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Get the content you want to save as pdf

var pdf_content = document.getElementById("pdf_body");

Add option or configuration to your file

var options = {
      margin:       1,
      filename:     'isolates.pdf',
      image:        { type: 'jpeg', quality: 0.98 },
      html2canvas:  { scale: 2 },
      jsPDF:        { unit: 'in', format: 'letter', orientation: 'portrait' }
    };

Save the file

html2pdf(pdf_content, options);

I know this is an old question, but depending on the readers use case an easy way is to call window.print() and tell the user to choose the save as PDF option. In CSS you can use media queries to hide or show content specifically for printing so you can control what is shown on the PDF. For example I use these .no-print and .only-print for this purpose.

.only-print {
   display: none
}
@media print {
  .no-print {
    display: none
  }
  .only-print {
    display: block
  }
}

In my use case I hide all the navigation and buttons stuff, I also hide some collapsed blocks and instead show all the uncollapsed blocks.

Related