当前位置:首页 > VUE

vue 实现打印功能

2026-01-17 02:19:29VUE

使用 vue-print-nb 插件

安装 vue-print-nb 插件:

npm install vue-print-nb --save

在 main.js 中引入并注册插件:

import Print from 'vue-print-nb'
Vue.use(Print)

在模板中添加打印按钮和目标区域:

<button v-print="printObj">打印</button>
<div id="printContent">
  <!-- 需要打印的内容 -->
</div>

在组件中定义 printObj:

data() {
  return {
    printObj: {
      id: 'printContent',
      popTitle: '打印标题'
    }
  }
}

使用 window.print() 方法

创建一个打印方法:

vue 实现打印功能

methods: {
  handlePrint() {
    window.print()
  }
}

添加打印按钮:

<button @click="handlePrint">打印</button>

使用 CSS 控制打印样式:

@media print {
  body * {
    visibility: hidden;
  }
  #printArea, #printArea * {
    visibility: visible;
  }
  #printArea {
    position: absolute;
    left: 0;
    top: 0;
  }
}

使用 iframe 实现打印

创建打印方法:

vue 实现打印功能

printByIframe(content) {
  const iframe = document.createElement('iframe')
  iframe.style.display = 'none'
  document.body.appendChild(iframe)

  const doc = iframe.contentWindow.document
  doc.write(content)
  doc.close()

  iframe.contentWindow.focus()
  iframe.contentWindow.print()

  setTimeout(() => {
    document.body.removeChild(iframe)
  }, 100)
}

调用打印方法:

<button @click="printByIframe('<h1>打印内容</h1>')">打印</button>

使用 html2canvas 和 jsPDF 生成 PDF

安装依赖:

npm install html2canvas jspdf --save

创建导出方法:

import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'

exportPDF() {
  const element = document.getElementById('printArea')
  html2canvas(element).then(canvas => {
    const imgData = canvas.toDataURL('image/png')
    const pdf = new jsPDF()
    pdf.addImage(imgData, 'PNG', 0, 0)
    pdf.save('document.pdf')
  })
}

添加导出按钮:

<button @click="exportPDF">导出PDF</button>
<div id="printArea">
  <!-- 要导出的内容 -->
</div>

标签: 功能vue
分享给朋友:

相关文章

vue实现付款

vue实现付款

Vue 实现付款功能 在 Vue 中实现付款功能通常需要集成第三方支付网关(如支付宝、微信支付、Stripe 等)。以下是常见的实现方法: 集成支付宝/微信支付 安装必要的依赖(如 axios 用于…

vue实现拍照

vue实现拍照

Vue实现拍照功能 在Vue中实现拍照功能通常需要结合浏览器的MediaDevices API和Canvas元素。以下是具体实现方法: 安装依赖(可选) 如果需要更简单的封装,可以安装vue-web…

vue vnode实现

vue vnode实现

Vue VNode 实现原理 VNode(Virtual Node)是 Vue 的核心概念之一,用于描述真实 DOM 的轻量级虚拟表示。VNode 的实现涉及以下关键点: VNode 的基本结构 V…

vue实现suspense

vue实现suspense

Vue 3 中实现 Suspense Suspense 是 Vue 3 引入的一个内置组件,用于处理异步依赖的加载状态。它允许在等待异步组件或异步数据加载时显示一个后备内容(fallback),直到异…

vue实现复选

vue实现复选

Vue 实现复选框 在 Vue 中实现复选框可以通过 v-model 指令绑定数据,同时结合 input 元素的 type="checkbox" 属性来实现。以下是几种常见的实现方式: 单个复选框…

vue实现素材

vue实现素材

Vue 实现素材的方法 使用 Vue 组件管理素材 在 Vue 项目中,可以通过组件化的方式管理素材。创建一个专门的组件来加载和显示素材,例如图片、视频或音频文件。组件可以接收素材的路径或 URL 作…