5

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.

1
  • I only want to print the pre, not the entire page
    – Cyoce
    Commented May 9, 2015 at 7:57

1 Answer 1

3

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/

2
  • Thanks, but CSS is not preserved. Is there an addition to this answer that would allow the use of CSS, or would this require a different approach? jsfiddle
    – Cyoce
    Commented May 9, 2015 at 18:01
  • @Cyoce See updated post. Could add style element from initial document to popup document; add style attribute to pre element; or, create String "<style>.light{color:#0af;}</style>" that should be rendered as html at popup , and be applied to pre.light element. Commented May 9, 2015 at 18:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.