vue实现打印图片
使用vue-html-to-paper插件
安装插件:
npm install vue-html-to-paper
在main.js中引入并配置:
import VueHtmlToPaper from 'vue-html-to-paper';
Vue.use(VueHtmlToPaper);
组件中使用:
this.$htmlToPaper('printContainer', {
name: '_blank',
specs: ['fullscreen=yes','titlebar=yes','scrollbars=yes'],
styles: ['https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css']
});
使用window.print()方法
创建打印区域:
<div id="printArea">
<img src="your-image.jpg" alt="Print Image">
</div>
添加打印按钮:

methods: {
printImage() {
const printContent = document.getElementById('printArea');
const WindowObject = window.open('', "PrintWindow");
WindowObject.document.writeln(printContent.innerHTML);
WindowObject.document.close();
WindowObject.focus();
WindowObject.print();
WindowObject.close();
}
}
使用CSS媒体查询控制打印样式
添加打印样式:
@media print {
body * {
visibility: hidden;
}
#printArea, #printArea * {
visibility: visible;
}
#printArea {
position: absolute;
left: 0;
top: 0;
}
}
使用html2canvas和jsPDF库
安装依赖:
npm install html2canvas jspdf
实现代码:

import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
methods: {
async printWithCanvas() {
const element = document.getElementById('printArea');
const canvas = await html2canvas(element);
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF();
pdf.addImage(imgData, 'PNG', 0, 0);
pdf.save('print.pdf');
}
}
注意事项
图片需要完全加载后才能打印,可以在img标签上添加@load事件监听:
<img @load="imageLoaded = true" :src="imageUrl">
对于跨域图片,需要确保服务器允许CORS:
html2canvas(element, {
useCORS: true
});
打印时可能需要调整边距和缩放比例:
const pdf = new jsPDF({
orientation: 'portrait',
unit: 'mm',
format: 'a4'
});
const imgProps = pdf.getImageProperties(imgData);
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);






