Save a pre element as PDF with CSS

后端 未结 1 1986
北海茫月
北海茫月 2020-11-27 22:53

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 poi

相关标签:
1条回答
  • 2020-11-27 23:45

    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/

    0 讨论(0)
提交回复
热议问题