Problems with Window.print

here is my problem. I have code that implements window.print, but the problem is that when I close the print window and return to my page, my print button no longer works.

$(function(){ $('#button1').click(function() { $('head').append('<link rel="stylesheet" href="<?php echo base_url() ?>assets/weekly/style/weekly.css" type="text/css"/>'); var printContents = document.getElementById('data').innerHTML; var originalContents = document.body.innerHTML; document.body.innerHTML = printContents; window.print(); document.body.innerHTML = originalContents; //window.location = document.body.innerHTML; //location.reload(); }); }); 

But when I add location.reload() (see the comment), the print button works again, but loads the previous data, not the current data, so I don't want to use location.reload() . Is there any other solution or approach to my problem?

+7
source share
3 answers

To do this, you really need to use a CSS stylesheet for printing, but if you want to achieve your goal this way, it might work better:

 $(function(){ $('#button1').click(function(){ $('head').append('<link rel="stylesheet" href="<?php echo base_url() ?>assets/weekly/style/weekly.css" type="text/css"/>'); var printContents = $( $('#data').html() ); var originalContents = $('body > *').hide(); $('body').append( printContents ); window.print(); printContents.remove(); originalContents.show(); }); }); 

Create a new element using innerHTML of the data element. Hide all children tag body. Add a new element to the body tag. Print out. Delete the new item. Show original content again.

This is still messy, but you should not lose your events.

+2
source

I fixed a similar problem by simply opening a new window with only the content that I wanted to print as follows:

 function printPage(htmlstring){ var boiler = "put any styling or js scripts here to make it look right"; boiler += "<div id='print-page-content'>\n</div>\n"; var PrintWindow = window.open("","newwin", height=600, width=800, toolbar=no, menubar=no"); PrintWindow.document.write(boiler); $(PrintWindow.document).find("#print-page-content").append(htmlstring); $(PrintWindow).ready(function(){ PrintWindow.print(); }); } 

Then just name it:

 printPage(document.body.innerHTML); 
+1
source

Thanks so much for the answers and answers. I really appreciate it. I just want to add the answer that it came from my friend.

First on the button add onlick = "window.print ()"

  <p><img src="images/printButton.gif" id="button1" width="100" height="75" onclick="window.print()"></p> 

And then add a css style like this

 <link href = 'css/print.css' rel = 'stylesheet' style = 'text/css' MEDIA="print, handheld"/> 

Remember that MEDIA = "print, handheld"

0
source

All Articles