How to calculate div height which is converted as image to fit the PDF using jsPDF & html2Canvas?

余生长醉 提交于 2020-01-16 02:04:48

问题


I am converting div to image by using html2canvas.

I want to calculate height of the div(in px) such that it will fit on the PDF page maintaining the aspect ratio of image It should work on all window sizes(larger screens, IPAD, Desktop, laptop).

I am using jsPDF for generating PDF

Here is the fiddle example http://jsfiddle.net/akshay1818/ys0z984x/51/

HTML Code

<div id="target">
    Set div height(in px) such that it will fit on the page maintaing the aspect ratio
</div>

<button onclick="takeScreenShot()">to pdf</button>

JavaScript Code

window.takeScreenShot =function() {
      const layout = document.getElementById("target");
      const doc = new jsPDF("l", "mm", "a4");

       const canvasimg = html2canvas(layout).then(async(canvasimg)=>{
            let doc = new jsPDF("l", "mm", "a4");
            let img = canvasimg.toDataURL('image/png');
            const imgProps = doc.getImageProperties(img);
            const pdfWidth = doc.internal.pageSize.getWidth();
            var pdfPgHt = doc.internal.pageSize.getHeight();
            const imgRatioHeight = (imgProps.height * pdfWidth) / imgProps.width;
            doc.addImage(img, 'PNG', 0, 0, pdfWidth, imgRatioHeight);
            doc.save('report.pdf');
       })
}

Thanks in Advance.

来源:https://stackoverflow.com/questions/59508759/how-to-calculate-div-height-which-is-converted-as-image-to-fit-the-pdf-using-jsp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!