javascript - 使用 CSS 将 pre 元素另存为 PDF

标签 javascript jquery html css pdf

我做了一个syntax highlighter我想要一个保存为 PDF 的选项。我看过this SO question ,但下载它不会保留 CSS 样式,这会破坏下载突出显示文件的意义。有没有办法可以在保留 CSS 的同时将 pre 元素保存为 PDF?

HTML:

<pre id='output'> (highlighted portion) </pre>
<button id='save'>Save as PDF</button>

JS:

$('#save').click(function(){
  //this is what I need help with
});

正如您可能已经注意到的,我正在使用 jQuery,如果这很重要的话。

最佳答案

尝试打开新的 window ,附加 pre htmlstyle ,如果 pre< 有的话 元素,到新的 window document.body ,调用 .focus().print()在新的窗口上;选择系统打印对话框,选择“打印到文件”

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

jsfiddle http://jsfiddle.net/tn04Ldka/2/

关于javascript - 使用 CSS 将 pre 元素另存为 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43624761/

相关文章:

javascript - jQuery 实时处理程序但对于每个()?

javascript - 选项卡在 Bootstrap v4.3.1 中不工作,但在 v4.1.0 中工作

java - JOptionPane 按字面意思显示一些 HTML 标签

javascript - 使用淡入淡出切换 <div> 内容

html - Bootstrap : Get Row-span like behavior?

javascript - 将 Browserify 与 JavaScript 库(例如 Backbone 或 Underscore)一起使用?

javascript - 在 html 中创建 javascript 循环

javascript - 本地服务器在 Firefox 中工作,在 chrome 中被视为搜索

javascript - 无法在 JavaScript 中将对象属性复制到另一个对象

jquery.css 背景图片不附加