当前位置:首页 > 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-signature库可以快速实现签名功能。通过npm或yarn安装: npm install vue-signature --save # 或 ya…

vue实现多级组件

vue实现多级组件

实现多级组件的基本结构 在Vue中实现多级组件通常涉及父子组件嵌套,通过props向下传递数据,通过$emit向上传递事件。多级组件的核心是递归或动态组件渲染。 <!-- 父组件 Parent…

vue实现素材

vue实现素材

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

vue实现flvvideo

vue实现flvvideo

vue-flv-player 实现 FLV 视频播放 安装依赖包 npm install flv.js vue-flv-player 基础组件引入 <template> <v…

利用vue 实现

利用vue 实现

以下是利用 Vue 实现常见功能的几种方法,分为不同场景和技术要点: 数据绑定与响应式更新 Vue 的核心特性是数据绑定,通过 v-model 实现双向绑定: <template>…

前端vue实现概率

前端vue实现概率

Vue实现概率功能的方法 在Vue中实现概率功能通常涉及随机数生成和概率计算。以下是几种常见实现方式: 基础概率实现 使用Math.random()生成0到1之间的随机数,与设定概率比较:…