利用iframe实现局部打印(区域打印)
<template>
<div id="test-page">
<!-- 额外元素 -->
<div class="myInput"><el-input v-model="text"></el-input>{{ text }}</div>
<!-- 打印按钮 -->
<el-button @click="printPDF">打印pdf</el-button>
<!-- 打印元素 -->
<div id="print-box">
<div class="fwb">
测试数据1
<div v-html="htmlVal"></div>
</div>
<div class="fwb">
测试数据2
<div v-html="htmlVal"></div>
</div>
<div class="fwb">
测试数据3
<div v-html="htmlVal"></div>
</div>
<div class="fwb">
测试数据4
<div v-html="htmlVal"></div>
</div>
<div class="fwb">
测试数据5
<div v-html="htmlVal"></div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
text: "额外数据",
htmlVal:
'<img src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2Ftp09%2F210F2130512J47-0-lp.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1663148033&t=a570c0a0e3e61506d927150caae6acfe" alt="">',
};
},
methods: {
// 打印pdf
printPDF() {
// 获取打印DOM
let el = document.getElementById("print-box");
// 当前页面样式
let headDom = document.getElementsByTagName("head")[0];
// 创建iframe
let iframe = document.createElement("iframe");
// 设置iframe样式
iframe.setAttribute("id", "print-box");
iframe.setAttribute(
"style",
"position:absolute;width:0px;height:0px;left:-500px;top:-500px;"
);
// 在页面插入iframe
document.body.appendChild(iframe);
// 获取iframe内的html
let doc = iframe.contentWindow.document;
// 经需要打印的DOM插入iframe
let printMain = document.createElement("div");
printMain.setAttribute("id", "print-box");
printMain.innerHTML = el.innerHTML;
doc.body.appendChild(printMain);
// 设置iframe内的header,添加样式文件
doc.getElementsByTagName("head")[0].innerHTML = headDom.innerHTML;
// 关闭iframe
doc.close();
// 使iframe失去焦点
iframe.contentWindow.focus();
// 调用iframe的打印方法
iframe.contentWindow.print();
// 移除iframe
document.body.removeChild(iframe);
},
},
};
</script>
<style scope>
#test-page {
padding: 30px;
}
.fwb {
width: 300px;
margin: 20px 0;
border: solid 1px #999;
padding: 20px;
box-sizing: border-box;
font-size: 30px;
}
img {
margin-top: 10px;
width: 100%;
}
</style>
原文链接:https://blog.csdn.net/qq_36939013/article/details/108050247