UNPKG

zenprint

Version:

Document Printing Helper

37 lines (36 loc) 1.32 kB
// index.js module.exports = function printData(elementID, styleElement) { try { const tableContent = document.getElementById(elementID).innerHTML if (!tableContent) { throw new Error(`Element ${elementID} not found`) } const printFrame = document.createElement('iframe') printFrame.style.position = 'absolute' printFrame.style.width = '0' printFrame.style.height = '0' printFrame.style.border = 'none' document.body.appendChild(printFrame) const doc = printFrame.contentDocument || printFrame.contentWindow.document const head = document.createElement('head') head.innerHTML = document.head.innerHTML doc.open() doc.write(` <!DOCTYPE html> <html lang="en"> <head> </head> <body></body> </html> `) doc.head.appendChild(head) doc.head.appendChild(styleElement) doc.body.innerHTML = tableContent doc.close() printFrame.onload = async () => { await new Promise(resolve => setTimeout(resolve, 2000)) printFrame.contentWindow.print() document.body.removeChild(printFrame) } } catch (error) { console.error('Print Error:', error.message) } };