Tengo un problema al implementar la funcionalidad de impresión en mi aplicación. Tengo una función de JavaScript que se supone que debe imprimir el contenido de un div en particular cuando hago clic en el botón Imprimir. Cada vez que hago clic en el botón de impresión, la funcionalidad de impresión funciona pero hace que la ventana principal se congele. Intenté agregar una ventana. cerrar también, pero no pareció funcionar. Alguna idea de cómo solucionar este problema o alguna alternativa sobre cómo imprimir los contenidos específicos. Cualquier otro método que pruebe termina desplazando todos los elementos de ese div hacia la izquierda.
Función a continuación
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>Gracias.
Esto funciona para mí ... Tal vez te encuentres con un problema diferente ...
<!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>