Home  >  Article  >  Web Front-end  >  How to Capture a Code Block as PDF while Preserving CSS Styling in a Browser?

How to Capture a Code Block as PDF while Preserving CSS Styling in a Browser?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-23 15:50:02521browse

How to Capture a Code Block as PDF while Preserving CSS Styling in a Browser?

Downloading Highlighted Pre Element as PDF with CSS Preservation

To save a pre element as PDF while preserving the CSS styling, you can utilize a method that involves opening a new window, injecting the HTML and CSS, and printing to a PDF file.

Solution:

  1. Open a new window and focus it.
  2. Append the pre element's HTML and the necessary CSS styles to the new window's document body.
  3. Call the .focus() method on the new window.
  4. Call the .print() method on the new window.
  5. In the system print dialog, select "Print to file" and save the PDF.

Here's the jQuery code you can use:

$("#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();
});

The above is the detailed content of How to Capture a Code Block as PDF while Preserving CSS Styling in a Browser?. 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