// 整頁打印
window.print();
// 打印預覽(僅 IE 支援)
// document.execCommand('print', false, null);
/* 隱藏不需打印區域 */
@media print {
.no-print { display: none !important; }
.only-print { display: block !important; }
}
/* 頁面結構 */
需打印的內容
頁腳導航
function printArea(startMarker, endMarker) {
const html = document.body.innerHTML;
const start = html.indexOf(startMarker);
const end = html.indexOf(endMarker);
if (start === -1 || end === -1) return;
const printHtml = html.substring(start + startMarker.length, end);
const original = document.body.innerHTML;
document.body.innerHTML = printHtml;
window.print();
document.body.innerHTML = original; // 恢復(會丟失事件綁定,慎用)
}
function printElement(selector) {
const $el = $(selector).clone();
const iframe = $('
// 僅 IE 支援,需用戶允許 ActiveX
function setPageHeaderFooter(header, footer) {
try {
const wsh = new ActiveXObject('WScript.Shell');
const key = 'HKEY_CURRENT_USER\\Software\\Microsoft\\Internet Explorer\\PageSetup\\';
wsh.RegWrite(key + 'header', header || '');
wsh.RegWrite(key + 'footer', footer || '');
} catch (e) { console.warn('無權限修改頁眉頁腳'); }
}
@page {
margin: 2cm;
@top-center { content: "報表標題"; }
@bottom-center { content: "第 " counter(page) " 頁 / 共 " counter(pages) " 頁"; }
}
⚠️ 瀏覽器支援度有限,Chrome/Edge 較好,Firefox 部分支援。
/* 用戶需在打印預覽中勾選「背景圖形」 */
/* 強制建議(不一定生效) */
@media print {
* { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
}
const PrintUtil = {
printElement(selector, options = {}) {
const { title = '', styles = [], onBeforePrint, onAfterPrint } = options;
return new Promise(resolve => {
const iframe = document.createElement('iframe');
iframe.style.cssText = 'position:absolute;left:-9999px;';
document.body.appendChild(iframe);
const doc = iframe.contentDocument;
const content = document.querySelector(selector).outerHTML;
const cssLinks = Array.from(document.querySelectorAll('link[rel=stylesheet]'))
.map(l => ``).join('');
const styleTags = Array.from(document.querySelectorAll('style'))
.map(s => s.outerHTML).join('');
doc.write(`${cssLinks}${styleTags}${title} ${content}`);
doc.close();
const win = iframe.contentWindow;
onBeforePrint?.();
win.onload = () => {
win.focus();
win.print();
win.onafterprint = () => {
onAfterPrint?.();
setTimeout(() => { iframe.remove(); resolve(); }, 100);
};
};
});
}
};
// 使用
PrintUtil.printElement('#report', { title: '銷售報表' });