问题
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