I am working on a project and I want to print div content.The code which I am using is fulfilling my requirements,but I am getting simple output without Css applied to it and also not getting the image.Please help me.I am attaching the code and output I am getting and output I want.
Code:
function PrintElem(elem) { Popup($(elem).html()); } function Popup(data) { var mywindow = window.open('', 'new div', 'height=400,width=600'); mywindow.document.write('<html><head><title></title>'); mywindow.document.write('<link rel="stylesheet" href="css/midday_receipt.css" type="text/css" />'); mywindow.document.write('</head><body >'); mywindow.document.write(data); mywindow.document.write('</body></html>'); mywindow.print(); mywindow.close(); return true; }
Output I am getting before clicking print button:
Output I am getting by clicking print button:
To print the content of div in JavaScript, first store the content of div in a JavaScript variable and then the print button is clicked. The contents of the HTML div element to be extracted.
Developer Tools. The DevTools ( F12 or Cmd/Ctrl + Shift + I ) can emulate print styles, although page breaks won't be shown. In Chrome, open the Developer Tools and select More Tools, then Rendering from the three-dot icon menu at the top right. Change the Emulate CSS Media to print at the bottom of that panel.
HTML, CSS and JavaScript You can use CSS to change the appearance of your web page when it's printed on a paper. You can specify one font for the screen version and another for the print version. You have seen @media rule in previous chapters. This rule allows you to specify different style for different media.
You need to include the style to the printWindow by setting the style. Set id to the css style and add by fetching using document. getElementById. This will print whereever you place the qr code above the image.
If you wanna render the CSS you must add a timeout before printing it because it takes some time for CSS to be applied to the HTML and then you will be able to print it.
Try this:
function Popup(data) { var mywindow = window.open('', 'new div', 'height=400,width=600'); mywindow.document.write('<html><head><title></title>'); mywindow.document.write('<link rel="stylesheet" href="css/midday_receipt.css" type="text/css" />'); mywindow.document.write('</head><body >'); mywindow.document.write(data); mywindow.document.write('</body></html>'); mywindow.document.close(); mywindow.focus(); setTimeout(function(){mywindow.print();},1000); mywindow.close(); return true; }
You need to change the css property media
to print
. Add new line to your function createPopup() as below you attached your css:
mywindow.document.write( "<link rel=\"stylesheet\" href=\"style.css\" type=\"text/css\" media=\"print\"/>" );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With