I am trying to capture a div with canvas inside. it is a tshirt editor. now i am capturing this div with html2canvas and then printing it in pdf using jspdf. Now the problem is that the captured image is of very low quality and blurry. its dpi are very low.
This is the original div picture:
and this is the printed version of that div:
You can see the quality difference between them is huge.
Anyway here is the code of capturing the div and then converting it into pdf
var myimage;
function print() {
window.scrollTo(0, 0);
html2canvas(document.getElementById('shirtDiv')).then(function(canvas) {
myimage = canvas.toDataURL("image/jpeg");
setTimeout(print2, 1);
var doc = new jsPDF();
doc.addImage(myimage, 'JPEG', 35, 20, 130, 155);
doc.save('Test.pdf');
});
}
<div id="shirtDiv" class="page" style="width: 530px; height: 630px; position: relative; background-color: rgb(255, 255, 255); " >
<img name="tshirtview" id="tshirtFacing" src="img/crew_front.png">
<div id="drawingArea" style="position: absolute;top: 100px;left: 160px;z-index: 10;width: 200px;height: 400px;">
</div></div>
Please ignore the on-line CSS
Ok i did it because of the similar question asked by someone else in this link but the answer wasn't marked correct because he didn't explained it right maybe. Anyway here is the solution.
var myimage;
function print() {
window.scrollTo(0, 0);
html2canvas(document.getElementById('shirtDiv')[0],{scale:4}).then(function(canvas) {
myimage = canvas.toDataURL("image/jpeg");
var doc = new jsPDF();
doc.addImage(myimage, 'JPEG', 35, 20, 130, 155);
doc.save('Test.pdf');
});
}
The scale property was mentioned everywhere but i was having trouble to apply it. yes i know i am stupid but maybe someone else is like me and this might help them :)
UPDATE VERSION
This HTML2CANVAS solution was still not working good for me because the scale option does increase the target div's size before capturing it but it won't work if you have something inside that div which won't resize e.g in my case it was canvas for my editing tool. Anyway for this i opted for domtoimage and trust me i think that this is the best solution of them all. I didn't had to face any problem of html2canvas for example: need to be at the top of webpage so html2canvas can capture the shot completely and Low dpi problem
Anyway sorry for the story but i thought everyone should know and here is the code
function print() {
var node = document.getElementById('shirtDiv');
var options = {
quality: 0.95
};
domtoimage.toJpeg(node, options).then(function (dataUrl) {
var doc = new jsPDF();
doc.addImage(dataUrl, 'JPEG', -18, 20, 240, 134.12);
doc.save('Test.pdf');
});
}
Cdn for dom to image: https://cdnjs.com/libraries/dom-to-image
Cdn for jspdf: https://cdnjs.com/libraries/jspdf