I am trying to implement a method which will download any div of a webpage. Previously i was using jsPDF and html2Canvas to download it but now i don’t wanna use any external library, so can we implement the same thing using pure vanilla javascript.
printDivAsPdf(divId: string, filename = 'generated-pdf') {
const printContent = document.getElementById(divId);
if (!printContent) {
console.error(`Div with ID '${divId}' not found.`);
return;
}
// Create a new style element to apply CSS for printing
const style = document.createElement('style');
style.innerHTML = `
@media print {
/* Additional CSS for printing */
body {
-webkit-print-color-adjust: exact; /* Safari and Chrome */
color-adjust: exact; /* Firefox */
}
/* Apply page break inside avoid to the main container and its child elements */
#${divId}, #${divId} div {
page-break-inside: avoid;
margin: 0; /* Remove margins */
padding: 0; /* Remove padding */
/* Uncomment the line below to set width to 100% of page width */
/* width: 100%; */
}
}
`;
// Append the style element to the document head
document.head.appendChild(style);
// Create a new jsPDF instance with custom settings
const pdf = new jsPDF({
orientation: 'portrait',
unit: 'mm',
format: 'a4'
});
const scale = 0.18;
// Generate PDF from HTML content using html2canvas
pdf.html(printContent, {
callback: () => {
pdf.save(`${filename}.pdf`); // Save PDF with specified filename
// Remove the injected style element after generating the PDF
document.head.removeChild(style);
},
x: 0,
y: 0,
html2canvas: {
scale: scale
}
});
I was using this but can we do the same thing using pure Vanilla JS ???
New contributor
Abhishek Anand is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.