0

Without rendering the HTML first, just print the HTML without opening a new tab, is that possible? Below is my existing code that works printing in a new tab:

  var w = window.open();
  var html = $(data).html();

  $(w.document.body).html(html);
  w.print();
Unheilig
  • 16,196
  • 193
  • 68
  • 98
Alicia
  • 163
  • 1
  • 3
  • 11
  • `window.open` will open a blank window. What is expected? is you want to print the innerHTML of body that before showing it to screen? – Rohit Batta Nov 20 '15 at 04:35
  • @RohitBatta for example in stackoverflow, there's a button when u click it will call some ajax, and the response is html, can print that piece of html without opening a new tab? – Alicia Nov 20 '15 at 04:38
  • You can perhaps render it in a hidden section & print it http://stackoverflow.com/questions/1071962/how-to-print-part-of-rendered-html-page-in-javascript – loxxy Nov 20 '15 at 04:43
  • Yes, you could print that html response. You could either assign that html response to any div and then print that section. You could check the link provided in above comment by @loxxy – Rohit Batta Nov 20 '15 at 04:45
  • You can render HTML somewhere in the same page and control what appears on screen and what is printed with [CSS @media](https://developer.mozilla.org/en-US/docs/Web/CSS/@media) directives in your style sheet. – Roamer-1888 Nov 20 '15 at 05:06
  • @Roamer-1888 I don't want to render the html to the user, but directly print for them. – Alicia Nov 20 '15 at 07:15
  • Yes, your question makes that clear. If you go the @media route for printing, the page would still have screen-borne content - yes? You would need `@media screen` for display to the user, and `@media print` to determine what gets printed. By defining *both* types of content, they will be mutually exclusive - the screen stuff will not print and the print stuff will not appear on the screen - geddit? – Roamer-1888 Nov 20 '15 at 09:48
  • in chrome, you can `console.log(HTMLElement)` it will print all of the properties of an html element... Buuuut, I guess you are not asking that. – ahitt6345 Nov 22 '15 at 05:51
  • media screen is for css, I'm talking about the content (html) – Alicia Nov 24 '15 at 06:32
  • Alicia, you need to do some gentle [background reading](http://www.w3.org/TR/css3-mediaqueries/). – Roamer-1888 Nov 27 '15 at 17:33

1 Answers1

0
  • remove window.open();
  • example

Get Print Data

var printData = document.getElementById('printID').innerHTML;

Get the HTML of whole page

var originalData = document.body.innerHTML;

Add printData to html

document.body.innerHTML =
 "<html><head><title></title></head><body>" +
 printData + "</body>";

Print Page

window.print();

Restore orignal HTML

document.body.innerHTML = originalData;
Naing Min Khant
  • 141
  • 2
  • 6