Search code examples
javascripthtmlpdfjspdfhtml2canvas

convert web page to a pdf with styles


I want to convert a web page to PDF including all the styles I've added. I've used jspdf.js and html2Canvas. But I got only a blur picture in PDF form. I've searched for many JavaScript codes but didn't find a correct one.

Script I have written is:

function getPDF() {
  html2canvas(document.body, {
    onrendered: function(canvas) {
      var img = canvas.toDataURL("Image/jpeg");
      //window.open(img);
      var doc = new jsPDF({
        unit: 'px',
        format: 'a4'
      });
      doc.addImage(img, 'JPEG', 0, 0, 440, 627);
      doc.save("download");

    }
  });
}

Thank You!


Solution

  • There may be a few things that are contributing.

    Your encoder options for the canvas.toDataURL are missing, so you're getting the defaults. The defaults may be creating a low quality image. Try this for the highest quality JPEG image:

    var img = canvas.toDataURL("Image/jpeg", 1.0);
    

    You might also try creating your jsPDF object with measurements, rather than pixels:

    var pdf = new jsPDF("p", "mm", "a4");  // jsPDF(orientation, units, format)
    

    And when you add the image, scale it to the dimensions of the page:

    pdf.addImage(imgData, 'JPEG', 10, 10, 190, 277);  // 190x277 mm @ (10,10)mm
    

    See if that gives you a better image quality.