我做了一个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
html
、 style
,如果 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/