vue+element实现单条打印、批量打印(图片)
winodw.print()方法
print() 方法用于打印当前窗口的内容。调用 print() 方法会产生一个打印预览弹框,让用户可以设置打印请求。最简单的打印就是直接调用window.print(),当然用 document.execCommand('print') 也可以达到同样的效果。默认打印页面中body里的所有内容。
<template> <div class="dashboard-container"> <el-button @click='allPrint'>批量打印</el-button> <el-table :data="tableData" style=" 100%" border @selection-change="handleSelectionChange"> <el-table-column type="selection" width="55"> </el-table-column> <el-table-column prop="id" label="id" width="180"> </el-table-column> <el-table-column label="图片" width="180"> <template slot-scope="scope"> <img :src="scope.row.src" class="table_img"> </template> </el-table-column> <el-table-column label="操作" width="100"> <template slot-scope="scope"> <el-button @click="print(scope.row)" type="text" size="small">打印</el-button> </template> </el-table-column> </el-table> <!--startprint--> <div id="printcontent" ref='printcontent'> <img :src="item.src" class="print_img" v-for="item in multipleSelection" :key='item.id' /> </div> <!--endprint--> </div> </template> <script> export default { data() { return { tableData: [{ id: 1, src:'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg' }, { id: 2, src:'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg' }, { id: 3, src:'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg' } ], multipleSelection: [], //存放将要打印的数据 } }, methods: { print(row={}) { if(row.src){ this.multipleSelection.push(row) } this.$nextTick(()=>{ var bdhtml=window.document.body.innerHTML; // 获取body的内容 var jubuData = document.getElementById("printcontent").innerHTML; //获取要打印的区域内容 window.document.body.innerHTML= jubuData; window.print(); // 调用浏览器的打印功能 window.document.body.innerHTML=bdhtml; // body替换为原来的内容 window.location.reload(); //刷新页面,如果不刷新页面再次点击不生效或打印使用新窗口实现打印 }) }, allPrint(){ this.print() }, handleSelectionChange(val) { this.multipleSelection = val; } } } </script> <style lang="scss"> .dashboard-container { .table_img { 50px; height: 50px; } #printcontent{ display: none; } } //使用媒体查询 设置预览时的样式 @media print{ @page { margin: 0; size: portrait; //设置打印布局portrait为纵向;landscape为横向 } #printcontent{ 100%; } .print_img{ display: block; 100%; height: 100%; margin: auto auto; } } </style>