I’ve been working on a function in JavaScript that allows me to download the content of a specified as a PDF file. The function works by generating HTML content with print styles, converting it into a blob object, and then triggering a download using an anchor element.But when I try to open the pdf it showing like this:
Downloaded pdf
Here’s the function:
downloadDivById(divId: string, fileName: string) {
const printContent = document.getElementById(divId);
if (!printContent) {
console.error(`Div with ID '${divId}' not found.`);
return;
}
// Generate HTML content with print styles
const printHTML = `
<html>
<head>
<title>${fileName}</title>
<style>
/* Add @media print styles here */
@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 */
}
/* Add other print styles as needed */
${this.getAllStyles()} /* Include all CSS rules from stylesheets */
${this.getMediaQueryStyles()}
}
</style>
</head>
<body>
${printContent.outerHTML}
</body>
</html>
`;
// Create a new blob object containing the HTML content
const blob = new Blob([printHTML], { type: "application/pdf" });
// Create a URL for the blob object
const url = URL.createObjectURL(blob);
// Create an anchor element to trigger the download
const a = document.createElement("a");
a.href = url;
a.download = fileName + ".pdf";
// Append the anchor element to the document body and trigger the click event
document.body.appendChild(a);
a.click();
// Clean up by revoking the URL and removing the anchor element
setTimeout(() => {
URL.revokeObjectURL(url);
document.body.removeChild(a);
}, 100);
}
I applied media queries for custom page breaks and css and I want to download a pdf with these css applied.
New contributor