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

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

问题描述

我做了一个 语法高亮,我想要一个选项来保存为 PDF.我看过这个问题,但下载它不会保留 CSS 样式,这破坏了下载突出显示文件的意义.有没有办法可以在保持 CSS 的同时将我的 pre 元素保存为 PDF?

HTML:

(突出显示的部分)</pre><button id='save'>另存为 PDF</button>

JS:

$('#save').click(function(){//这就是我需要帮助的});

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

解决方案

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

$("#save").click(function() {var text = $("#output")[0].outerHTML;//`styles`: `style` 元素;//或 `String` "<style>.light{color:#0af;}</style>";//或者,直接给 `pre` 元素添加 `style` 属性,//例如,`<pre style="color:#0af;">`var 样式 = $("style")[0].outerHTML;var popup = window.open("", "popup");//附加 `text`:`pre` 元素 `styles`:`style` 元素//在`popup``document.body`popup.document.body.innerHTML = 文本 + 样式;popup.focus();弹出窗口.打印();});

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

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
});

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

解决方案

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/

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

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