75 lines
1.6 KiB
Vue
Raw Normal View History

2025-03-21 09:20:29 +08:00
<template>
2025-04-11 18:00:39 +08:00
<el-dialog :model-value="props.showes" @close="closeFun" width="70%">
<div ref="ceshiRef">
<ceshi id="ceshi" :data="props.listData"></ceshi>
</div>
2025-04-08 00:14:08 +08:00
<div class="btnList">
<el-button type="primary" @click="printElement">打印</el-button>
</div>
</el-dialog>
2025-03-21 09:20:29 +08:00
</template>
<script setup lang="ts">
2025-04-11 18:00:39 +08:00
import { defineProps, reactive, ref, nextTick, defineEmits } from 'vue';
2025-04-08 00:14:08 +08:00
import ceshi from './ceshi.vue';
import printJS from 'print-js';
2025-04-11 18:00:39 +08:00
import html2canvas from 'html2canvas';
2025-04-08 00:14:08 +08:00
2025-04-11 18:00:39 +08:00
const ceshiRef = ref();
const emits = defineEmits(['close']);
2025-03-21 09:20:29 +08:00
const props = defineProps({
2025-04-08 00:14:08 +08:00
listData: {
type: Array,
default: () => [],
},
showes: {
type: Boolean,
default: true,
},
2025-03-21 09:20:29 +08:00
});
const state = reactive({
2025-04-11 18:00:39 +08:00
snapshotUrl: '',
2025-03-21 09:20:29 +08:00
});
2025-04-11 18:00:39 +08:00
const closeFun = () => {
emits('close');
};
2025-04-08 00:14:08 +08:00
const printElement = () => {
2025-04-11 18:00:39 +08:00
captureSnapshot();
2025-04-08 00:14:08 +08:00
// 获取 DOM 元素的 HTML
nextTick(() => {
printJS({
2025-04-11 18:00:39 +08:00
printable: state.snapshotUrl,
type: 'image',
2025-04-08 00:14:08 +08:00
style: `
2025-04-11 18:00:39 +08:00
@page {
size: auto;
margin: 0mm;
}
body {
margin: 0;
padding: 36px;
}
2025-04-08 00:14:08 +08:00
`,
});
});
};
2025-04-11 18:00:39 +08:00
// 截图函数
const captureSnapshot = async () => {
// 使用 html2canvas 将 div 渲染为 Canvas
const canvas = await html2canvas(ceshiRef.value, {
allowTaint: true, // 允许跨域图片
useCORS: true, // 使用 CORS 加载图片
scale: 2, // 提高截图分辨率
width: ceshiRef.value.clientWidth,
height: ceshiRef.value.clientHeight,
});
state.snapshotUrl = canvas.toDataURL('image/png');
};
2025-03-21 09:20:29 +08:00
</script>
<style scoped lang="scss">
2025-04-08 00:14:08 +08:00
.btnList {
margin-top: 26px;
display: flex;
justify-content: center;
2025-03-21 09:20:29 +08:00
}
2025-04-08 00:14:08 +08:00
</style>