admin管理员组

文章数量:1327661

I'm trying to print a certain div in my application using this javascript with JQuery:

function PrintContent()
{
w=window.open();
w.document.write($('#diary').html());
w.print();
w.close();
}

It opens the div in a new tab and the print options panel opens up but the CSS styles are lost. I have a print.css, set to media="print" however, I think that it's obviously not loading this file in the new tab i.e. it's just loading the div and not the header where the CSS is.

Any idea how I can fix this? My javascript isn't that strong.

Thanks!

I'm trying to print a certain div in my application using this javascript with JQuery:

function PrintContent()
{
w=window.open();
w.document.write($('#diary').html());
w.print();
w.close();
}

It opens the div in a new tab and the print options panel opens up but the CSS styles are lost. I have a print.css, set to media="print" however, I think that it's obviously not loading this file in the new tab i.e. it's just loading the div and not the header where the CSS is.

Any idea how I can fix this? My javascript isn't that strong.

Thanks!

Share Improve this question asked Jan 11, 2011 at 9:30 RobimpRobimp 6986 gold badges14 silver badges29 bronze badges 1
  • Do I need to have the stlyesheet referenced inside the DIV in order to make it applicable in print? or having it on main page suffices? – Anil Soman Commented Aug 29, 2012 at 7:41
Add a ment  | 

2 Answers 2

Reset to default 4

Try using this line instead:

w.document.write('<div id="diary">' + $('#diary').html() + '</div>');

You are writing out the inner html of your div and not the actual div tag.

The method above also writes out the div tag with the right id. I only stuck the id in there because you might be formatting div#diary rather than div.

EDIT

This method should keep the styling.

function PrintContent()
{
    var e = document.createElement('div');
    e.id = 'diary';
    e.innerHTML = $('#diary').html();
    document.getElementById('t').appendChild(e);
}

You just have to make a place that this content can be inserted, such as a div with the id of t. Just like the example I posted in the ments.

Because document.write is bad practice:

https://github./jasonday/printThis

本文标签: jqueryPrint Div With Javascript and Preserve StyleStack Overflow