xxxxxxxxxx
var doc = new jsPDF();
var specialElementHandlers = {
'#editor': function (element, renderer) {
return true;
}
};
$('#cmd').click(function () {
doc.fromHTML($('#content').html(), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
doc.save('sample-file.pdf');
});
xxxxxxxxxx
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Export div to PDF using JavaScript</title>
<!-- Include the required libraries -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
</head>
<body>
<!-- The div element to export -->
<div id="div-to-export">
<h1>Hello, World!</h1>
<p>This is a sample div element.</p>
</div>
<!-- The export button -->
<button id="export-btn">Export to PDF</button>
<script>
// The function to export the div element to a PDF file
function exportToPdf() {
// Get the div element to export
const element = document.getElementById("div-to-export");
// Use html2canvas to convert the div element to an image
html2canvas(element).then((canvas) => {
// Get the image data URL
const imgData = canvas.toDataURL("image/png");
// Create a new PDF file
const pdf = new jsPDF();
// Add the image to the PDF file
pdf.addImage(imgData, "PNG", 0, 0);
// Save the PDF file
pdf.save("div-to-pdf.pdf");
});
}
// Call the function when the user clicks the export button
const exportBtn = document.getElementById("export-btn");
exportBtn.addEventListener("click", exportToPdf);
</script>
</body>
</html>