PC端直接打印功能(包括两张图片合并功能)
一、 效果图
二、demo代码
<template><div class="box"><divref="printContent"class="print-content"><div class="print-title">打印图片</div><imgclass="preview-image":src="mergedImage"alt="Merged Image"/></div><div class="btn" @click="handlePrint">打印</div></div></template><script lang="ts" setup>
import { onMounted, ref } from 'vue';
import image1 from '../../assets/images/cs.jpg'
import image2 from '../../assets/images/huang1.png'
const printContent = ref();
const codeImg = ref()
const photoUrl = ref()
const mergedImage = ref(null);
onMounted(() => {mergeImages()
})
// 打印
const handlePrint = () => {return new Promise((resolve) => {// 创建隐藏的iframeconst iframe = document.createElement('iframe');iframe.style.position = 'fixed';iframe.style.right = '0';iframe.style.bottom = '0';iframe.style.width = '0';iframe.style.height = '0';iframe.style.border = '0';// 插入DOMdocument.body.appendChild(iframe);// 获取打印内容const content = `<html><head><title>打印</title><style>@page { margin: 0; }body { margin: 1cm; }img { max-width: 100%!important; height: auto!important;}</style></head><body>${printContent.value.innerHTML}</body></html>`;// 写入内容const doc = iframe.contentWindow.document;doc.open();doc.write(content);doc.close();// 打印完成后清理iframe.contentWindow.onafterprint = () => {document.body.removeChild(iframe);closeModal();resolve();};// 触发打印setTimeout(() => {iframe.contentWindow.focus();iframe.contentWindow.print();}, 500);});
};
// 合并两张图片
const mergeImages = async () => {const img1 = new Image();const img2 = new Image();img1.src = image1img2.src = image2await new Promise((resolve) => {img1.onload = resolve;});await new Promise((resolve) => {img2.onload = resolve;});const canvas = document.createElement('canvas');canvas.width = img1.width;canvas.height = img1.height;const ctx: any = canvas.getContext('2d');ctx.drawImage(img1, 0, 0);// 假设头像位置在左上角,你可以根据需要调整位置// const avatarSize = 300; // 头像大小ctx.drawImage(img2, 230, 30, 425, 425); // 距离左边位置,距离上边位置,图片宽度,图片高度mergedImage.value = canvas.toDataURL('image/png');
};
</script>
<style lang="scss" scoped>
.box {width: 100%;height: 100%;box-sizing: border-box;padding: 20px;
}
@media print {/* 打印时隐藏所有内容 */body * {visibility: hidden !important;}/* 显示打印区域 */.print-content,.print-content * {visibility: visible !important;}/* 定位到页面顶部 */.print-content {position: absolute;left: 0;top: 0;width: 100% !important;}
}
.print-title {text-align: left;font-size: 28px;
}
.preview-image {width: 500px;
}
.btn{width: 80px;height: 44px;line-height: 44px;text-align: center;background-color: rgb(56, 68, 240);color: #fff;cursor: pointer;
}
</style>