65 lines
2.1 KiB
JavaScript
65 lines
2.1 KiB
JavaScript
/**
|
|
* Print HTML content using iframe approach
|
|
* @param {string} htmlContent - Complete HTML string to print
|
|
* @param {string} additionalStyles - Optional additional CSS styles
|
|
* @returns {Promise<void>}
|
|
*/
|
|
export async function printHtml(htmlContent, additionalStyles = '') {
|
|
return new Promise((resolve, reject) => {
|
|
try {
|
|
// Create hidden iframe
|
|
const iframe = document.createElement('iframe');
|
|
iframe.style.position = 'absolute';
|
|
iframe.style.width = '0px';
|
|
iframe.style.height = '0px';
|
|
iframe.style.border = 'none';
|
|
iframe.style.visibility = 'hidden';
|
|
document.body.appendChild(iframe);
|
|
|
|
const doc = iframe.contentWindow.document;
|
|
doc.open();
|
|
|
|
// Write the complete HTML content
|
|
doc.write(htmlContent);
|
|
|
|
// Add additional styles if provided
|
|
if (additionalStyles) {
|
|
doc.write(`<style>${additionalStyles}</style>`);
|
|
}
|
|
|
|
doc.close();
|
|
|
|
// Handle print completion
|
|
iframe.contentWindow.onafterprint = () => {
|
|
document.body.removeChild(iframe);
|
|
resolve();
|
|
};
|
|
|
|
// Wait for content to load before printing
|
|
iframe.contentWindow.onload = () => {
|
|
console.log('Print content loaded');
|
|
setTimeout(() => {
|
|
iframe.contentWindow.focus();
|
|
iframe.contentWindow.print();
|
|
}, 300); // Allow rendering delay
|
|
};
|
|
|
|
} catch (error) {
|
|
console.error('Error in printHtml:', error);
|
|
reject(error);
|
|
}
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Print template with data binding
|
|
* @param {object} template - Template object with elements and page config
|
|
* @param {object} data - Data object for binding
|
|
* @returns {Promise<void>}
|
|
*/
|
|
export async function printTemplate(template, data = {}) {
|
|
const { generateHtml } = await import('./exportToHtml');
|
|
const html = generateHtml(template, data);
|
|
return printHtml(html);
|
|
}
|