JavaScript调用打印功能时如何自定义页眉页脚替换默认URL
JavaScript打印自定义页眉页脚实现方案
核心原理
浏览器默认的页眉页脚是打印时自动生成的,我们需要先通过CSS关闭默认页眉页脚的显示,再插入自定义的页眉页脚元素,通过打印媒体查询控制其仅在打印场景下展示,固定在每页的对应位置。
步骤1:添加打印专用CSS
把下面的样式加到页面的<style>标签里:
/* 打印专用样式 */ @media print { /* 隐藏不需要打印的页面元素,比如打印按钮 */ body * { visibility: hidden; } #printSection, #printSection * { visibility: visible; } #printSection { position: absolute; left: 0; top: 0; width: 100%; } /* 关闭浏览器默认页眉页脚,预留自定义内容的边距 */ @page { size: A4; margin: 80px 20px 60px 20px; /* 上、右、下、左边距,根据页眉页脚高度调整 */ } /* 自定义页眉样式 */ .print-header { position: fixed; top: -70px; /* 对应@page的上边距,调整到合适位置 */ width: 100%; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid #eee; padding-bottom: 10px; } .print-header img { height: 40px; } /* 自定义页脚样式 */ .print-footer { position: fixed; bottom: -50px; /* 对应@page的下边距,调整到合适位置 */ width: 100%; text-align: center; font-size: 12px; color: #666; border-top: 1px solid #eee; padding-top: 10px; } /* 表格多页打印时表头重复显示 */ table thead { display: table-header-group; } }
步骤2:修改打印JS代码
在原有打印逻辑中插入自定义的页眉、页脚元素:
document.getElementById("btnPrint").onclick = function() { printElement(document.getElementById("myTable")); } function printElement(elem) { var domClone = elem.cloneNode(true); var $printSection = document.getElementById("printSection"); if (!$printSection) { $printSection = document.createElement("div"); $printSection.id = "printSection"; document.body.appendChild($printSection); } $printSection.innerHTML = ""; // 插入自定义页眉 var header = document.createElement("div"); header.className = "print-header"; header.innerHTML = ` <img src="你的logo地址" alt="logo"> <h3>自定义打印标题</h3> `; $printSection.appendChild(header); // 插入要打印的表格 $printSection.appendChild(domClone); // 插入自定义页脚 var footer = document.createElement("div"); footer.className = "print-footer"; footer.innerHTML = "自定义页脚内容,比如公司名称、打印时间等"; $printSection.appendChild(footer); // 确保内容加载完成后再打印,避免图片/样式丢失 setTimeout(() => { window.print(); // 打印完成后移除printSection,避免影响页面正常显示 $printSection.remove(); }, 100); }
注意事项
- 如果打印预览仍然显示默认的URL页眉页脚,可以在打印预览的「更多设置」中手动关闭「页眉和页脚」选项,主流Chrome、Edge、Firefox浏览器均支持该设置。
- 页眉中的logo如果是本地/内网资源,确保打印时资源可正常访问,也可以转成base64格式嵌入避免加载失败。
- 可根据实际需求调整CSS中边距、字体、颜色等样式参数。
内容的提问来源于stack exchange,提问作者ECROWN TECH
相关产品推荐
相关产品推荐

