当前位置:首页 > 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() 方法

创建一个打印方法:

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 实现打印

创建打印方法:

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

添加导出按钮:

vue 实现打印功能

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

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

相关文章

vue点击实现排序

vue点击实现排序

实现点击排序的方法 在Vue中实现点击排序功能,可以通过以下几种方式完成: 使用计算属性结合排序方法 定义一个响应式数据存储排序状态,通过计算属性动态返回排序后的数组。点击事件切换排序状态。 d…

vue实现边框

vue实现边框

Vue 实现边框的方法 在 Vue 中实现边框效果可以通过多种方式完成,包括内联样式、CSS 类绑定、动态样式以及使用第三方 UI 库。以下是几种常见的实现方法。 内联样式绑定 使用 Vue 的 :…

vue实现级联

vue实现级联

Vue 实现级联选择器的方法 级联选择器(Cascader)是常见的表单组件,用于处理多层级联动数据选择(如省市区选择)。以下是几种实现方式: 基于 Element UI 的 el-cascader…

vue实现socket

vue实现socket

Vue 中实现 WebSocket 通信 在 Vue 项目中实现 WebSocket 通信可以通过原生 WebSocket API 或第三方库(如 socket.io-client)完成。以下是两种常…

vue实现画图

vue实现画图

Vue 实现画图功能 在 Vue 中实现画图功能通常需要结合 HTML5 的 <canvas> 元素或第三方库。以下是几种常见的方法: 使用原生 Canvas API 通过 Vue 直接…

vue 实现排序

vue 实现排序

Vue 实现排序的方法 使用计算属性实现排序 通过计算属性对数组进行排序,可以保持原始数据不变。示例代码展示了如何对列表按名称升序排序: <template> <div>…