使用CSS将前置元素保存为PDF [英] Save a pre element as PDF with CSS

查看:123
本文介绍了使用CSS将前置元素保存为PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了语法荧光笔,我想要一个保存为PDF的选项。我查看了此SO问题,但下载它不会保留CSS样式,这会废除下载突出显示的文件的点。有没有办法我可以保存我的 pre 元素作为PDF,同时保持CSS?

I made a syntax highlighter and I want an option to save as a PDF. I've looked at this SO question, but downloading it doesn’t preserve the CSS styling, which ruins the point of downloading the highlighted file. Is there a way I can save my pre element as a PDF while maintaining the CSS?

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,如果这很重要。

As you may have noticed, I'm using jQuery, if that matters.

推荐答案

尝试开启新的视窗,附加 pre html , style 元素,到新窗口 document.body ,调用 .focus() .print()在新窗口选择系统打印对话框,选择打印到文件

Try opening new window , appending pre html , style , if any for pre element, to new window document.body , calling .focus() , .print() on new window ; select system print dialog, select "Print to file"

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

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

这篇关于使用CSS将前置元素保存为PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆