Vous êtes sur la page 1sur 10

Stack Overflow

1. Questions
2. Developer Jobs
3. Tags
4. Users

1.
2.
3.
4.
Log In Sign Up

Join Stack Overflow to learn, share knowledge, and build your career.
Email Sign Up OR SIGN IN WITH

Google
Facebook
How to print HTML content on click of a button, but not the
page? [duplicate]
Ask Question

up vote66down vote favorite

31
This question already has an answer here:
 Print <div id=“printarea”></div> only? 25 answers
I want to print some HTML content, when the user clicks on a button. Once the user clicks on that
button, the print dialog of the browser will open, but it will not print the webpage. Instead, it will
print the some other HTML content which is not displayed on the page.

While asking this question, there are few solutions coming into my mind. But I am not sure whether
those are good ideas or something better can be done. One of those solutions are: I can keep this
HTML content in a div and make it display: to print, but display: none to screen. All other
elements on the webpage can be made to display: none for print and display: for the screen. And
then call to print.
Any better idea?

javascript html css printing

shareimprove this question


asked Jun 3 '13 at 10:28

Debiprasad
1,64983761

marked as duplicate by NullPoiиteя, Salman A css Dec 21 '14 at 11:27


This question has been asked before and already has an answer. If those answers do not fully address your question,
please ask a new question.

 Can you show us your code? – 웃웃웃웃웃 Jun 3 '13 at 10:30


 (Further considering that the highest rated answer here is using code from one of the answers to the other
question almost verbatim) – doppelgreener May 8 '14 at 4:39
 1
this library can help with printing selected html elements in a page: printjs.crabbly.com – crabbly Sep 3 '16 at 18:14
add a comment
6 Answers
activeoldest votes

up vote100down vote
I came across another elegant solution for this:

Place your printable part inside a div with an id like this:

<div id="printableArea">
<h1>Print me</h1>
</div>

<input type="button" onclick="printDiv('printableArea')" value="print a div!" />


Now let's create a really simple javascript:

function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;

document.body.innerHTML = printContents;

window.print();

document.body.innerHTML = originalContents;
}
SOURCE : SO Answer
shareimprove this answer
edited May 23 '17 at 12:10

Community♦
11
answered Jun 3 '13 at 11:05

asprin
6,15084390
 15
What will this do to the event listeners? – Juzer Ali Apr 30 '15 at 14:02
 How to open that in new window? – Shylendra Madda Aug 3 '15 at 16:52
 4
this may destroy your animations and events that was added by js after load. Use with caution. – Lukas Liesis Dec
14 '15 at 16:45
 2
This seems overly convoluted. @media print is a much cleaner solution (see 2ne's post below). – Jim DoyleJan 26
'17 at 14:35
 1
My dom event handlers are gone after reattaching the original content. – johntrepreneur Mar 1 '17 at 1:44
show 3 more comments
up vote57down vote
Here is a pure css version

.example-print {
display: none;
}
@media print {
.example-screen {
display: none;
}
.example-print {
display: block;
}
}
<div class="example-screen">You only see me in the browser</div>

<div class="example-print">You only see me in the print</div>


Run code snippet
Expand snippet
shareimprove this answer
edited Sep 18 '17 at 9:49

Jonathan
651723
answered Jun 3 '13 at 10:36

2ne
2,85951945
 1
I like that you don't need to open a new window and all that crap. – Robusto Apr 16 '17 at 22:01
 @Robusto agree in one hand, but I don't like how it's not so good for saving the page (without needing to print), not
to mention when there's paging to be handled. preparing a page to "print" is ambiguous in that sense. – cregox Apr
23 '17 at 13:17
add a comment
up vote41down vote
According to this SO link you can print a specific div with
w=window.open();
w.document.write(document.getElementsByClassName('report_left_inner')[0].innerHTML);
w.print();
w.close();
shareimprove this answer
edited May 23 '17 at 12:10

Community♦
11
answered Jun 3 '13 at 10:35

Jaay
1,2691024
 7
This solution requires JQuery which is not mentioned (or tagged) in the question. You should specify this
dependency in your answer. – musefan Oct 18 '13 at 11:08
 6
replacing $('.report_left_inner').html() by vanilla js would make this the best answer on the page for
simplicity and robustness – zeachco Aug 21 '15 at 21:24
 2
w.document.write(document.getElementsByClassName('report_left_inner')[0].innerHTML);–
karaxuna Jan 13 '16 at 14:45
 2
This is excellent. One point of caution though: you'll need to check and inject your style rules separately, or it'll fall
back to bare HTML. For that I personally did document.write('<style>'+ ... + '</style>'); before
the document.write() given here. – cst1992 Aug 19 '17 at 8:14
add a comment
up vote10down vote
I Want See This
Example http://jsfiddle.net/35vAN/
<html>
<head>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js" > </script>
<script type="text/javascript">

function PrintElem(elem)
{
Popup($(elem).html());
}

function Popup(data)
{
var mywindow = window.open('', 'my div', 'height=400,width=600');
mywindow.document.write('<html><head><title>my div</title>');
/*optional stylesheet*/ //mywindow.document.write('<link rel="stylesheet" href="main.css" type="text/css"
/>');
mywindow.document.write('</head><body >');
mywindow.document.write(data);
mywindow.document.write('</body></html>');

mywindow.print();
mywindow.close();

return true;
}

</script>
</head>
<body>

<div id="mydiv">
This will be printed. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a quam at nibh
adipiscing interdum. Nulla vitae accumsan ante.
</div>

<div>
This will not be printed.
</div>

<div id="anotherdiv">
Nor will this.
</div>

<input type="button" value="Print Div" onclick="PrintElem('#mydiv')" />

</body>

</html>
shareimprove this answer
answered Jul 25 '14 at 12:27

Panchal Deep
197212
 Not working in IE 11 – Hamed Ali Khan Feb 3 '17 at 13:26
add a comment
up vote2down vote
Below Code May Be Help You :

<html>
<head>
<script>
function printPage(id)
{
var html="<html>";
html+= document.getElementById(id).innerHTML;
html+="</html>";

var printWin = window.open('','','left=0,top=0,width=1,height=1,toolbar=0,scrollbars=0,status =0');


printWin.document.write(html);
printWin.document.close();
printWin.focus();
printWin.print();
printWin.close();
}
</script>
</head>
<body>
<div id="block1">
<table border="1" >
</tr>
<th colspan="3">Block 1</th>
</tr>
<tr>
<th>1</th><th>XYZ</th><th>athock</th>
</tr>
</table>

</div>

<div id="block2">
This is Block 2 content
</div>

<input type="button" value="Print Block 1" onclick="printPage('block1');"></input>


<input type="button" value="Print Block 2" onclick="printPage('block2');"></input>
</body>
</html>
shareimprove this answer
answered Jun 3 '13 at 10:36

Butani Vijay
2,82211841
add a comment
up vote2down vote
If you add and remove the innerHTML, all javascript, css and more will be loaded twice, and the
events will fire twice (happened to me), is better hide content, using jQuery and css like this:

function printDiv(selector) {
$('body .site-container').css({display:'none'});
var content = $(selector).clone();
$('body .site-container').before(content);
window.print();
$(selector).first().remove();
$('body .site-container').css({display:''});
}
The div "site-container" contain all site, so you can call the function like:

printDiv('.someDiv');
shareimprove this answer
answered Jul 4 '14 at 0:26

Alejo JM
631410
 Hi Alejo. Clever solution, but it doesn't work in IE. Could you please help me with this
question: stackoverflow.com/questions/49410902 THaNKS! – codeispoetry Mar 21 at 15:56
add a comment
Not the answer you're looking for? Browse other questions tagged javascript html css printing or ask
your own question.
asked
4 years, 10 months ago
viewed
347,631 times
active
6 months ago
Want a php job?

Application Security Engineer
Wikimedia Foundation, Inc.San Francisco, CA
REMOTE
php javascript


Senior/Lead Drupal (PHP) Engineer
Compucorp Ltd.No office location
£20K - £28KREMOTE
php javascript

High response rate


Engineering Manager (focus PHP, Front-End)
Docler HoldingLuxembourg City, Luxembourg
php mysql


Senior/Lead PHP Engineer
Compucorp Ltd.No office location
£15K - £28KREMOTE
php javascript

High response rate

Linked

334
Print <div id=“printarea”></div> only?

-1
How to print a search result in CodeIgniter?

0
Is there any option for printing the graphs generated by c3js?

2
Open another page or image in print Preview

0
How to print a .docx file on a printer using javascript and / or php

0
Does anyone know a way to print the loaded page HTML after DOM is completed?

0
Printing a variable from javascript

0
I need a replacement for iFrame printing due to a recent Windows Update

0
How to create print button for each individual html table within a php foreach loop

0
javascript print() specific div without opening a new window: not working in IE
see more linked questions…

Related

665
Why not use tables for layout in HTML?

1940
How do I detect a click outside an element?

1613
How to make div not larger than its contents?

2217
How can I know which radio button is selected via jQuery?

420
In jQuery, how to attach events to dynamic html elements?

1281
How to create an HTML button that acts like a link?

1954
How can I refresh a page with jQuery?

1293
Redirect from an HTML page

932
How to print to stderr in Python?

595
What is VanillaJS?

Hot Network Questions


 How to avoid being (falsely) accused of plagiarism when reusing notations and definitions
 What methods of transportation could be used to get ground vehicles onto an island surrounded by sharp rocks in shallow water?
 “GOD is real, unless declared integer.”
 Date Multiplying Challenge
 How to build a trap to last the ages?
 Check java version without java -version
 Is there a benefit to staying past the end of Retribution?
 Is the diagonal matrix the only matrix whose square is diagonal?
 How many arguments were passed?
 Do ATC displays show the target altitude that the pilot has set in the autopilot?
 How to deal with colleague who uses unintelligible colloquial/slang terms?
 How to tell driving instructor that I want to change instructors?
 Why do we use trig functions in Fourier transforms, and not other periodic functions?
 Explain this code to me: Doubled delimiters
 What ethical (if any) or economical arguments are offered in defense of the inheritance tax?
 I am charged 9.99 monthly, for what?
 What kind of grin was Raj hinted to have?
 Was Tolkien good at his day job?
 Notes preceding slurs: legato or not?
 Activation of multiple LEDs with transistor
 Why did Lucius interrupt Bruce during their Sonar/Submarine discussion?
 How much movement is needed to climb up a spiral staircase?
 What happens if a CD is scratched but burned to MP3
 Why does my browser think that https://1.1.1.1 is secure?

STACK OVERFLOW
 Questions
 Jobs
 Developer Jobs Directory
 Salary Calculator
 Help
 Mobile
PRODUCTS
 Teams
 Talent
 Ads
 Enterprise
COMPANY
 About
 Press
 Work Here
 Legal
 Privacy Policy
 Contact Us
STACK EXCHANGE
NETWORK
 Technology
 Life / Arts
 Culture / Recreation
 Science
 Other
 Blog
 Facebook
 Twitter
 LinkedIn

site design / logo © 2018 Stack Exchange Inc; user contributions licensed under cc by-sa 3.0 with attribution
required. rev 2018.4.13.29848

Vous aimerez peut-être aussi