I am facing an issue implementing print functionality in my application. I have a javascript function that is supposed to print the contents of a particular div when I click on the print button. Anytime I click on the print button, the print functionality works but it causes the main window to freeze. I tried adding a window.close also but didn't seem to work. Any idea how to fix this issue or any alternative on how to print the specific contents. Any other method I try ends up shifting all the elements of that div to the left.
Function below
export const printDiv = (id: string) => {
let printContents = document.getElementById(id).innerHTML
let originalContents = document.body.innerHTML
document.body.innerHTML = printContents
window.print()
document.body.innerHTML = originalContents
}
HTML
<!DOCTYPE html>
<html>
<style>
table, th, td {
border:1px solid black;
}
</style>
<body>
<button onClick={() => printDiv("print")}>Print</button>
<table style="width:100%" id="print">
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
</table>
<p>This portion should not be included in the print page</p>
</body>
</html>
Thanks.
This works for me... Maybe you are running into different issue...
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border:1px solid black;
}
</style>
<script type="text/javascript">
printDiv = (id) => {
let originalContents = document.body.innerHTML
let printContents = document.getElementById(id).innerHTML
document.body.innerHTML = printContents
window.print()
document.body.innerHTML = originalContents
// window.close()
}
</script>
</head>
<body>
<button onclick="printDiv('print')">Print</button>
<table style="width:100%" id="print">
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
</table>
<p>This portion should not be included in the print page</p>
</body>
</html>