I have encountered an issue with a custom Js script that I developed. The purpose of this script is to style a specific div in HTML using CSS.
Currently, the script is functional and performing its intended task. However, it is not behaving exactly as desired. At present, it only displays content visible on the user's screen and excludes any content above or below that is not currently within view. This can be problematic when dealing with HTML documents containing a significant amount of content.
Additionally, the script is rendering white backgrounds as black for reasons unknown.
Sample Code
$('#print').click(function() {
var w = document.getElementById("content").offsetWidth;
var h = document.getElementById("content").offsetHeight;
html2canvas(document.getElementById("content"), {
dpi: 300,
scale: 3,
onrendered: function(canvas) {
var img = canvas.toDataURL("image/jpeg", 1);
var doc = new jsPDF('L', 'px', [w, h]);
doc.addImage(img, 'JPEG', 0, 0, w, h);
doc.save('sample-file.pdf');
}
});
});
body {
background: beige;
}
header {
background: red;
}
footer {
background: blue;
}
#content {
background: yellow;
width: 70%;
height: 100px;
margin: 50px auto;
border: 1px solid orange;
padding: 20px;
}
Edit
I have found a temporary solution to the issues I was facing but am still exploring ways to improve the quality and eliminate unnecessary white space from the document.
Here is the current state of the Js snippet:
function getPDF() {
var HTML_Width = $(".canvas_div_pdf").width();
var HTML_Height = $(".canvas_div_pdf").height();
var top_left_margin = 15;
var PDF_Width = HTML_Width + (top_left_margin * 2);
var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
var canvas_image_width = HTML_Width;
var canvas_image_height = HTML_Height;
var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;
//more code for creating PDF
};
If you wish to use the functionality above, simply add onclick='getpdf()'
to your button.
To address the issue of black rendering, ensure you assign an ID or class to the targeted div and set a CSS Background color of #ffffff.
Any assistance would be greatly appreciated.
Kind Regards, Faz.