How to set image to fit width of the page using jsPDF?

后端 未结 11 2143
醉话见心
醉话见心 2020-12-04 21:37

Is there any way to solve this? I tried to set width and height in mm. How can I set it to full-width?

11条回答
  •  -上瘾入骨i
    2020-12-04 22:24

    My answer deals with a more specific case of what you are asking but I think one could draw some ideas from this to apply more generally. Also, I would post this as a comment to Purushoth's answer (on which mine is based), if only I could.

    Ok, so my problem was how to fit a web page into the pdf document, without losing the aspect ratio. I used jsPDF in conjuction with html2canvas and I calculated the ratio from my div's width and height. I applied that same ratio to the pdf document and the page fit perfectly onto the page without any distortion.

    var divHeight = $('#div_id').height();
    var divWidth = $('#div_id').width();
    var ratio = divHeight / divWidth;
    html2canvas(document.getElementById("div_id"), {
         height: divHeight,
         width: divWidth,
         onrendered: function(canvas) {
              var image = canvas.toDataURL("image/jpeg");
              var doc = new jsPDF(); // using defaults: orientation=portrait, unit=mm, size=A4
              var width = doc.internal.pageSize.getWidth();    
              var height = doc.internal.pageSize.getHeight();
              height = ratio * width;
              doc.addImage(image, 'JPEG', 0, 0, width-20, height-10);
              doc.save('myPage.pdf'); //Download the rendered PDF.
         }
    });
    

提交回复
热议问题