当前位置:首页 > 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>

添加打印按钮:

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

打印时可能需要调整边距和缩放比例:

vue实现打印图片

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中实现文章锚点定位可以通过多种方式完成,以下是几种常见的方法: 使用原生HTML锚点 通过HTML的id属性和<a>标签的href属性实现锚点跳转。在Vu…

vue实现 弹窗

vue实现 弹窗

Vue 实现弹窗的基本方法 使用 Vue 实现弹窗可以通过多种方式,包括组件化、指令、插件等。以下是几种常见的实现方法。 组件化实现弹窗 创建一个独立的弹窗组件,通过 props 控制显示与隐藏。…

vue 实现templateurl

vue 实现templateurl

在 Vue 中,templateUrl 是 Angular 中的一个概念,用于指定外部 HTML 文件作为模板。Vue 本身不直接支持 templateUrl,但可以通过以下方法实现类似功能: 使用…

vue实现等级选择

vue实现等级选择

实现等级选择的方法 在Vue中实现等级选择功能,可以通过多种方式完成,以下是几种常见的实现方法: 使用v-for渲染星级选择 通过v-for指令循环渲染星级图标,结合点击事件实现等级选择:…

vue实现页面定位

vue实现页面定位

Vue 实现页面定位的方法 在 Vue 中实现页面定位通常可以通过以下几种方式完成,包括使用原生 JavaScript 的 scrollIntoView 方法、Vue Router 的滚动行为配置,以…

vue实现http拦截

vue实现http拦截

Vue 实现 HTTP 拦截 在 Vue 项目中,通常通过 Axios 实现 HTTP 拦截功能,用于统一处理请求和响应。以下是具体实现方法: 安装 Axios 通过 npm 或 yarn 安装 A…