Home  >  Article  >  Web Front-end  >  How to Preserve CSS Styling When Saving Syntax Highlighter Pre Element as a PDF?

How to Preserve CSS Styling When Saving Syntax Highlighter Pre Element as a PDF?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-23 16:38:01653browse

How to Preserve CSS Styling When Saving Syntax Highlighter Pre Element as a PDF?

How to Save a Syntax-Highlighter Pre Element as a PDF Preserving CSS Styling

To save a syntax highlighter pre element as a PDF while maintaining the CSS, consider this alternative approach:

Solution:

  1. Create a New Window: Open a new browser window using window.open().
  2. Append HTML and CSS: Append the HTML content of the pre element ($("#output")[0].outerHTML) and any necessary CSS styles ($("style")[0].outerHTML) to the body of the new window.
  3. Focus and Print: Call .focus() and .print() on the new window. This will trigger the system print dialog, allowing you to select "Print to file" to save the pre element as a PDF.

jQuery Implementation:

<code class="javascript">$("#save").click(function() {
  var text = $("#output")[0].outerHTML;
  var styles = $("style")[0].outerHTML;
  var popup = window.open("", "popup");
  popup.document.body.innerHTML = text + styles;
  popup.focus();
  popup.print();
});</code>

Demonstration:

You can see this solution in action at the following jsfiddle: http://jsfiddle.net/tn04Ldka/2/

The above is the detailed content of How to Preserve CSS Styling When Saving Syntax Highlighter Pre Element as a PDF?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn