提示:小白也可以成功!!!
前言
前言:废话不多上代码
提示:复制粘贴即可使用 — 我也是大自然的搬运工
提示:以下是本篇文章正文内容,下面链接可供参考 (本文章所有内容根据下面两个链接而来)
参考链接1:window.print() 前端实现网页打印详解
参考链接2:window.print 添加页眉页脚
一、方法封装
封装:在utils下新建print.js文件。
export default function printHtml(html) {
const temp =
`
<div class="page-header" style="text-align: center"> I'm The Header</div>
<div class="page-footer">I'm The Footer</div>
<table>
<thead>
<tr>
<td>
<!--place holder for the fixed-position header-->
<div class="page-header-space"></div>
</td>
</tr>
</thead>
<tbody>
<tr>
<td>` +html + `</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<!--place holder for the fixed-position footer-->
<div class="page-footer-space"></div>
</td>
</tr>
</tfoot>
</table>`;
let style = getStyle();
let container = getContainer(temp);
document.body.appendChild(style);
document.body.appendChild(container);
getLoadPromise(container).then(() => {
window.print();
document.body.removeChild(style);
document.body.removeChild(container);
});
}
// 设置打印样式
function getStyle() {
let styleContent = `#print-container {
display: none;
width:1028px;
}
@media print {
body > :not(.print-container) {
display: none;
}
html,
body {
display: block !important;
}
#print-container {
display: block;
}
}
.page-header,
.page-header-space {
height: 100px;
}
.page-footer,
.page-footer-space {
height: 50px;
}
.page-footer {
position: fixed;
bottom: 0;
width: 100%;
border-top: 1px solid black;
/* for demo */
background: yellow;
/* for demo */
z-index:2000
}
.page-header {
position: fixed;
top: 0mm;
width: 100%;
border-bottom: 1px solid black;
/* for demo */
background: yellow;
/* for demo */
z-index:2000
}
.page {
page-break-after: always;
}
@page {
margin: 20mm
}
@media print {
thead {
display: table-header-group;
}
tfoot {
display: table-footer-group;
}
button {
display: none;
}
body {
margin: 0;
}
}
`;
let style = document.createElement("style");
style.innerHTML = styleContent;
return style;
}
// 清空打印内容
function cleanPrint() {
let div = document.getElementById("print-container");
if (!!div) {
document.querySelector("body").removeChild(div);
}
}
// 新建DOM,将需要打印的内容填充到DOM
function getContainer(html) {
cleanPrint();
let container = document.createElement("div");
container.setAttribute("id", "print-container");
container.innerHTML = html;
return container;
}
// 图片完全加载后再调用打印方法
function getLoadPromise(dom) {
let imgs = dom.querySelectorAll("img");
imgs = [].slice.call(imgs);
if (imgs.length === 0) {
return Promise.resolve();
}
let finishedCount = 0;
return new Promise(resolve => {
function check() {
finishedCount++;
if (finishedCount === imgs.length) {
resolve();
}
}
imgs.forEach(img => {
img.addEventListener("load", check);
img.addEventListener("error", check);
});
});
}
二、使用步骤
1.引入库
代码如下:
import printHtml from "@/utils/print.js"
export default {
methods: {
print() {
let printData = `<div>打印内容</div>`
printHtml(printData)
}
},
}
2.预览打印结果
打印图片如下(示例):
总结
提示:但如果是 vue 里的项目,重新赋值 innerHTML 会导致原来绑定在 dom 上的事件被清空,原有的事件失效,只有内容呈现但不可操作页面
可以用 location.reload() 重新加载页面。