【问题标题】:Save a pre element as PDF with CSS使用 CSS 将前置元素保存为 PDF
【发布时间】:2015-07-20 01:46:49
【问题描述】:

我创建了一个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,如果这很重要的话。

【问题讨论】:

  • 我只想打印pre,而不是整个页面

标签: javascript jquery html css pdf


【解决方案1】:

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

$("#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/

【讨论】:

  • 谢谢,但是 CSS 没有被保留。这个答案是否有允许使用 CSS 的补充,或者这需要不同的方法? jsfiddle
  • @Cyoce 查看更新后的帖子。可以将 style 元素从初始文档添加到 popup 文档;将style 属性添加到pre 元素;或者,创建 String "&lt;style&gt;.light{color:#0af;}&lt;/style&gt;" 应在 popup 处呈现为 html,并应用于 pre.light 元素。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多