之前有个VUE2版的实现方法:
VUE调用打印机打印页面_vue调用一体式打印机-CSDN博客
因为项目需要,现在要搞一个VUE3版的
大致的需求是:通过点击一个按钮,弹出一个对话框,然后对话框上有个打印按钮,点了后,会把需要打印的内容通过调用本地的打印机打印出来。
(吐槽一下那个AI啊,折腾了两个小时,一直离成功差那么一点点,让我装这个插件那个插件的。后来只能自己现学现用把代码改出来了。所以说人工智能顶替程序员的事不太靠谱。)
实现的方法:
1.先做一个print.js
javascript
export default {
mounted(el, binding) {
const content = binding.value;
console.log(`打印内容: ${content}`);
// 执行实际的打印逻辑
}
};
2.在man.js里注册一下
javascript
import printDirective from './directives/print'; // 确保路径正确
app.directive('print', printDirective);
3.在页面里调用
html的部分
html
<div id="app1">
<el-dialog v-model="dialogVisible" title="对话框" ref="dialogRef">
<div ref="printArea">
<p>{{ dialogContent }}</p>
<img :src="profileImageUrl" alt="Profile Image" @load="onImageLoad" />
<p>测试用的文字</p>
<table>
<tr>
<td>1</td>
<td>2</td>
</tr>
</table>
</div>
<template #footer>
<span class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="printDialogContent">打印</el-button>
</span>
</template>
</el-dialog>
<el-button @click="showDialog">显示对话框</el-button>
</div>
js的部分
javascript
// 对话框状态
const dialogVisible = ref(false);
// 对话框内容
const dialogContent = ref('这是要打印的内容');
// 图片路径
const profileImageUrl = 'https://via.placeholder.com/150';
// 对话框引用
const dialogRef = ref(null);
// 打印区域引用
const printArea = ref(null);
// 图片是否已加载完成
const imageLoaded = ref(false);
// 显示对话框
const showDialog = () => {
dialogVisible.value = true;
};
// 图片加载完成事件
const onImageLoad = () => {
imageLoaded.value = true;
};
// 打印对话框内容
const printDialogContent = () => {
if (dialogVisible.value && dialogRef.value && printArea.value) {
const printElement = printArea.value;
if (!imageLoaded.value) {
console.warn('图片尚未加载完成,请稍后重试。');
return;
}
const createPrintWindow = () => {
const newWindow = window.open('', '_blank'); // 创建一个新的空白窗口
if (newWindow) {
setTimeout(() => {
newWindow.document.write('<html><head><title>打印内容</title></head><body>');
newWindow.document.write(printElement.innerHTML);
newWindow.document.write('</body></html>');
newWindow.document.close();
// 触发打印
newWindow.print();
// 关闭窗口
newWindow.close();
}, 100); // 延迟100毫秒执行
} else {
console.error('无法打开新窗口');
}
};
createPrintWindow();
}
};
这里有个坑,因为主动打开窗口会被EDGE拦截,所以就延迟了100ms,如果用谷歌浏览器打开,就完全没这个问题。