I found this code to print in Javascript.
function printData()
{
var divToPrint=document.getElementById("printTable");
newWin= window.open("");
newWin.document.write(divToPrint.outerHTML);
newWin.print();
newWin.close();
}
The element ID "printTable" is the ID of the table that I want to print but unfortunately it only prints out the contents of the table and not the style of the table. I just want to have borders on it so that it is easier to read in print. Can anyone help me?
Copy let table = document. createElement('table'); let thead = document. createElement('thead'); let tbody = document. createElement('tbody'); table.
JavaScript does not have any print object or print methods. You cannot access output devices from JavaScript. The only exception is that you can call the window.print() method in the browser to print the content of the current window.
Print Settings in Chrome Browser 1. Print pages by pressing Ctrl + P on the keyboard or click or tap the three-dot menu button from the top right of the Chrome window. 2. Choose Print from the menu.
Here is your code in a jsfiddle example. I have tested it and it looks fine.
http://jsfiddle.net/dimshik/9DbEP/4/
I used a simple table, maybe you are missing some CSS on your new page that was created with JavaScript.
<table border="1" cellpadding="3" id="printTable">
<tbody><tr>
<th>First Name</th>
<th>Last Name</th>
<th>Points</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
<tr>
<td>Adam</td>
<td>Johnson</td>
<td>67</td>
</tr>
</tbody></table>
One cheeky solution :
function printDiv(divID) {
//Get the HTML of div
var divElements = document.getElementById(divID).innerHTML;
//Get the HTML of whole page
var oldPage = document.body.innerHTML;
//Reset the page's HTML with div's HTML only
document.body.innerHTML =
"<html><head><title></title></head><body>" +
divElements + "</body>";
//Print Page
window.print();
//Restore orignal HTML
document.body.innerHTML = oldPage;
}
HTML :
<form id="form1" runat="server">
<div id="printablediv" style="width: 100%; background-color: Blue; height: 200px">
Print me I am in 1st Div
</div>
<div id="donotprintdiv" style="width: 100%; background-color: Gray; height: 200px">
I am not going to print
</div>
<input type="button" value="Print 1st Div" onclick="javascript:printDiv('printablediv')" />
</form>
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