当前位置:首页 > VUE

vue实现打印图片

2026-02-18 00:07:49VUE

使用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>

添加打印按钮:

vue实现打印图片

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

实现代码:

vue实现打印图片

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);

标签: 图片vue
分享给朋友:

相关文章

vue实现视频会议

vue实现视频会议

使用 Vue 实现视频会议 技术选型 Vue.js 作为前端框架,结合 WebRTC 技术实现实时音视频通信。常用的库包括: peerjs:简化 WebRTC 的点对点连接。 socket.io:…

vue实现视窗

vue实现视窗

Vue 实现视窗功能 在 Vue 中实现视窗功能通常涉及监听浏览器窗口大小变化、响应式布局或创建自定义弹窗组件。以下是几种常见实现方式: 监听浏览器窗口大小变化 使用 Vue 的 mounted…

实现vue组件

实现vue组件

Vue 组件的基本实现 Vue 组件是 Vue.js 的核心特性之一,允许将 UI 拆分为独立、可复用的模块。以下是实现 Vue 组件的几种方式: 单文件组件 (SFC) 使用 .vue 文件格式…

vue实现switch

vue实现switch

Vue 实现 Switch 开关组件 在 Vue 中实现 Switch 开关组件可以通过自定义组件或使用现有 UI 库完成。以下是几种常见实现方式: 自定义 Switch 组件 创建一个基础…

vue页面实现

vue页面实现

Vue 页面实现方法 创建 Vue 组件 使用 Vue 单文件组件(SFC)方式创建页面,文件扩展名为 .vue。一个基本的 Vue 组件包含三个部分:模板(template)、脚本(script)和…

vue实现异步

vue实现异步

Vue 实现异步操作的常见方法 Vue 提供了多种方式来处理异步操作,包括数据获取、事件处理等场景。 使用 async/await 在 Vue 方法中可以直接使用 async/await 语法处理…