Saving HTML Content with CSS as PDF
In web development, preserving visual aesthetics is crucial, even when exporting content to different formats. This can present challenges when attempting to save HTML elements as PDFs, as the CSS styling may be lost during the conversion process.
For cases where it's imperative to retain CSS in saved PDFs, consider utilizing the following approach:
This method effectively preserves CSS styling by ensuring that the element's appearance is faithfully rendered when saved as a PDF. Here's a JavaScript snippet that demonstrates the approach:
$("#save").click(function() {
var text = $("#output")[0].outerHTML;
// `styles`: `style` element;
// or `String` "<style>.light{color:#0af;}</style>" ;
// alternatively , add `style` attribute to `pre` element directly,
// e.g., `<pre style="color:#0af;">`
var styles = $("style")[0].outerHTML;
var popup = window.open("", "popup");
// append `text`:`pre` element `styles`:`style` element
// at `popup` `document.body`
popup.document.body.innerHTML = text styles;
popup.focus();
popup.print();
});
By adopting this approach, you can efficiently save HTML elements as PDFs while maintaining their visual aesthetics through CSS styling.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3