在el-image组件的预览中添加打印功能(自定义功能)

思路:给图片添加点击事件,通过js获取预览的工具栏,在工具栏中添加自定义按钮及事件

1、html 中 image标签

<el-image

style="width: 139px;

height: 89px"

:src="fileUrl"

:preview-src-list="[fileUrl]"

@click="handleImageClick(fileUrl)" //添加点击事件

/>

2、再点击事件中,通过js操作dom,添加自定义按钮事件

handleImageClick(fileUrl) {

this.$nextTick(() => {

const viewer = document.querySelector('.el-image-viewer__wrapper') //工具栏的dom

if (viewer) {

// 防止重复添加

if (!document.querySelector('.custom-print-btns')) {

const btn = document.createElement('button') //创建按钮

btn.className = 'custom-print-btns' //按需设计样式

btn.innerHTML = '<i class="el-icon-printer"></i>'

btn.onclick = () => this.printImage(fileUrl) //点击按钮触发事件

const btnGroup = viewer.querySelector('.el-image-viewer__actions__inner')

if (btnGroup) {

btnGroup.appendChild(btn) //在工具中添加按钮

}

}

}

})

},

3、添加后的图

4、打印事件

printImage(fileUrl) {

const printWindow = window.open('', '_blank')

printWindow.document.write(`

<html>

<head>

<title>打印图片</title>

<style>

body { text-align: center; margin: 0; padding: 0; }

img { max-width: 100%; max-height: 100vh; margin: auto; }

</style>

</head>

<body>

<img src="${fileUrl}" />

<script>

window.onload = function() {

setTimeout(function() {

window.print();

window.close();

}, 200);

}

<\/script>

</body>

</html>

`)

printWindow.document.close()

},

5、结果图

相关推荐
wenzhangli77 小时前
Ooder A2UI 核心架构深度解析:WEB 拦截层的设计与实现
前端·架构
前端百草阁7 小时前
【前端性能优化全链路指南】从开发编写到构建运行的多维度实践
前端·性能优化
神探小白牙8 小时前
eCharts 多系列柱状图增加背景图
javascript·ecmascript·echarts
女生也可以敲代码8 小时前
AI时代下的50道前端开发面试题:从基础到大模型应用
前端·面试
ZhengEnCi8 小时前
M5-markconv自定义CSS样式指南 📝
前端·css·python
IT_陈寒8 小时前
SpringBoot自动配置的坑差点让我加班到天亮
前端·人工智能·后端
xingpanvip8 小时前
星盘接口开发文档:星相日历接口指南
android·开发语言·前端·css·php·lua
@PHARAOH8 小时前
WHAT - GitLens supercharged 插件
前端
TT模板9 小时前
苹果cms整合西瓜播放器XGplayer插件支持跳过片头尾
前端·html5
Wect9 小时前
React 性能优化精讲
前端·react.js·性能优化