JSFiddle - React, Tailwind, and code Playground
by Nimitt Shah
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.min.js"></script>
<div id="content">
<p>1 This is the element you only want to capture</p>
<p>2 This is the element you only want to capture</p>
<p>3 This is the element you only want to capture</p>
<p>4 This is the element you only want to capture</p>
<p>5 This is the element you only want to capture</p>
</div>
<button id="print">Download Pdf</button>
<footer>This is the footer</footer>
CSS
body {
background: beige;
}
header {
background: red;
}
footer {
background: blue;
}
#content {
background: yellow;
width: 70%;
height: 100px;
margin: 50px auto;
border: 1px solid orange;
overflow-y:auto;
}
#content > p{
background: yellow;
width: 70%;
overflow-y:auto;
}
.html2canvas-container { width: 3000px !important; height: 3000px !important; }
JavaScript
$(document).ready(function() {
$('#print').click(function() {
var currentPosition = document.getElementById("content").scrollTop;
var w;
var h;
document.getElementById("content").style.height="auto";
var doc = new jsPDF('p', 'pt', 'letter');
$("#content").find("p").each(function(){
w = $(this).width();
h = $(this).height();
html2canvas($(this)[0], {
dpi: 300, // Set to 300 DPI
scale: 3, // Adjusts your resolution
onrendered: (canvas)=> {
let img = canvas.toDataURL("image/jpeg", 1);
console.log(img);
doc.addImage(img, 'PNG', 20, 40, w, h);
doc.addPage();
}
});
});
setTimeout(function(){ doc.save('sample-file.pdf')}, 500);
document.getElementById("content").style.height="100px";
document.getElementById("content").scrollTop = currentPosition;
});
});