当前位置:首页 > VUE

vue 实现打印页面

2026-03-08 14:26:58VUE

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

配置打印对象:

data() {
  return {
    printObj: {
      id: 'printContent',
      popTitle: '打印标题', // 打印窗口标题
      extraCss: 'https://example.com/print.css', // 额外CSS
      extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>' // 额外head标签
    }
  }
}

使用 window.print() 原生方法

创建打印方法:

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

添加打印按钮:

<button @click="printPage">打印页面</button>

使用媒体查询设置打印样式:

@media print {
  .no-print {
    display: none;
  }
  body {
    padding: 0;
    margin: 0;
  }
}

使用 iframe 实现局部打印

创建打印方法:

printPartial() {
  const printContent = document.getElementById('printArea').innerHTML
  const originalContent = document.body.innerHTML

  document.body.innerHTML = printContent
  window.print()
  document.body.innerHTML = originalContent
}

添加打印区域和按钮:

<div id="printArea">
  <!-- 需要打印的内容 -->
</div>
<button @click="printPartial">打印局部内容</button>

使用第三方库 html2canvas 和 jsPDF

安装依赖:

npm install html2canvas jspdf --save

实现导出PDF功能:

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

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

添加内容区域和按钮:

<div id="pdfContent">
  <!-- 需要转换为PDF的内容 -->
</div>
<button @click="exportPDF">导出PDF</button>

注意事项

打印样式应通过 @media print 媒体查询专门设置,确保打印效果符合预期

对于复杂页面,建议只打印必要内容,隐藏导航栏、侧边栏等不需要打印的元素

测试不同浏览器的打印兼容性,Chrome、Firefox 和 Edge 可能有细微差异

vue 实现打印页面

打印前可以通过 window.onafterprint 和 window.onbeforeprint 事件添加回调函数

标签: 页面vue
分享给朋友:

相关文章

vue实现div

vue实现div

Vue 实现 DIV 元素的方法 在 Vue 中实现 DIV 元素可以通过多种方式,以下是几种常见的实现方法: 使用模板语法 在 Vue 的模板中直接使用 HTML 的 <div> 标签…

vue实现后退

vue实现后退

Vue 实现后退功能的方法 在 Vue 中实现后退功能通常可以通过以下几种方式完成,具体取决于应用场景和需求。 使用 window.history API 通过原生 JavaScript 的 win…

vue路由实现

vue路由实现

Vue 路由实现 Vue Router 是 Vue.js 的官方路由管理器,用于构建单页面应用(SPA)。以下是 Vue Router 的基本实现步骤和核心功能。 安装 Vue Router 通过…

vue实现节流

vue实现节流

vue实现节流的方法 在Vue中实现节流(throttle)功能,通常用于限制高频事件的触发频率,例如滚动、输入或按钮点击。以下是几种常见的实现方式: 使用Lodash的throttle函数 安装L…

vue  实现tab

vue 实现tab

实现 Tab 切换功能 在 Vue 中实现 Tab 切换功能可以通过动态组件或条件渲染完成。以下是两种常见方法: 使用 v-if 或 v-show 实现条件渲染 通过绑定 currentTab 变量…

vue轮播实现

vue轮播实现

Vue 轮播实现方法 使用第三方库(推荐) 安装 swiper 或 vue-awesome-swiper 库,快速实现功能丰富的轮播效果。 以 vue-awesome-swiper 为例: npm…