Vxe vue vxe-table 分享实现打印表格以及同时打印两张表
vxe-table 默认情况下支持单表打印。
在有些情况下,页面上同时有几张表,这时需要一次性打印出来。可以利用 Vxe 自带的分页打印功能,实现多张表同时打印。
效果
点击打印后自动调起预览,可以直接连接打印机或者导出PDF
代码
实现步骤,
第一步:渲染表格
第二步:通过表格实例的 getPrintHtml() 方法获取打印的 html,不管有几张表都行, 有几张表就调用几次。
第三步:将结构转成分页打印,调用 VxeUI.print 打印
<template>
<div>
<vxe-button @click="printEvent">同时打印2张表</vxe-button>
<vxe-table
border
height="300"
ref="table1Ref"
:data="tableData1">
<vxe-column field="id" title="ID" width="60"></vxe-column>
<vxe-column field="name" title="Name"></vxe-column>
<vxe-column field="sex" title="Sex"></vxe-column>
<vxe-column field="address" title="Address"></vxe-column>
</vxe-table>
<vxe-table
border
height="300"
ref="table2Ref"
:data="tableData2">
<vxe-column field="id" title="ID" width="60"></vxe-column>
<vxe-column field="role" title="Role"></vxe-column>
<vxe-column field="age" title="Age"></vxe-column>
</vxe-table>
</div>
</template>
<script setup>
import { ref } from 'vue'
import { VxeUI } from 'vxe-pc-ui'
const table1Ref = ref()
const table2Ref = ref()
const tableData1 = ref([
{ id: 10001, name: 'Test1', role: 'Develop', sex: 'Man', age: 28, address: 'test abc' },
{ id: 10002, name: 'Test2', role: 'Test', sex: 'Women', age: 22, address: 'Guangzhou' },
{ id: 10003, name: 'Test3', role: 'PM', sex: 'Man', age: 32, address: 'Shanghai' },
{ id: 10004, name: 'Test4', role: 'Designer', sex: 'Women', age: 24, address: 'Shanghai' }
])
const tableData2 = ref([
{ id: 10001, name: 'Test1', role: 'Develop', sex: 'Man', age: 28, address: 'test abc' },
{ id: 10002, name: 'Test2', role: 'Test', sex: 'Women', age: 22, address: 'Guangzhou' },
{ id: 10003, name: 'Test3', role: 'PM', sex: 'Man', age: 32, address: 'Shanghai' },
{ id: 10004, name: 'Test4', role: 'Designer', sex: 'Women', age: 24, address: 'Shanghai' },
{ id: 10005, name: 'Test5', role: 'PM', sex: 'Man', age: 29, address: 'Shanghai' },
{ id: 10006, name: 'Test6', role: 'Designer', sex: 'Women', age: 38, address: 'Shanghai' }
])
const printEvent = () => {
const $table1 = table1Ref.value
const $table2 = table2Ref.value
if ($table1 && $table2) {
Promise.all([
$table1.getPrintHtml().then(({ html }) => {
return {
headerHtml: '<div style="text-align: center;font-size: 28px;">第一张表</div>',
bodyHtml: html
}
}),
$table2.getPrintHtml().then(({ html }) => {
return {
headerHtml: '<div style="text-align: center;font-size: 28px;">第二张表</div>',
bodyHtml: html
}
})
]).then(pageBreaks => {
VxeUI.print({
title: '打印多张表',
showPageNumber: true,
pageBreaks
})
})
}
}
</script>