当前位置:首页 > VUE

vue实现html打印功能

2026-02-23 23:19:29VUE

使用window.print()实现基础打印

在Vue中可以直接调用浏览器原生打印功能:

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

在模板中添加按钮触发:

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

打印特定区域内容

创建打印专用的隐藏容器:

<div class="print-area" ref="printContent">
  <!-- 需要打印的内容 -->
</div>
<div class="no-print">
  <!-- 不打印的内容 -->
</div>

通过CSS控制打印样式:

@media print {
  .no-print {
    display: none;
  }
  .print-area {
    display: block !important;
  }
}

使用vue-print-nb插件

安装插件:

npm install vue-print-nb --save

全局或局部引入:

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

// 或局部使用
directives: {
  print: Print
}

模板中使用:

<div id="printMe">
  <!-- 打印内容 -->
</div>
<button v-print="'#printMe'">打印</button>

自定义打印样式

创建单独的打印样式表:

@media print {
  body * {
    visibility: hidden;
  }
  .print-container, .print-container * {
    visibility: visible;
  }
  .print-container {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
  }
}

处理分页和布局

使用CSS控制分页:

@media print {
  .page-break {
    page-break-after: always;
  }
  table {
    page-break-inside: avoid;
  }
}

打印前数据处理

在打印前处理数据:

printWithData() {
  this.$nextTick(() => {
    const printContent = this.$refs.printContent.innerHTML
    const originalContent = document.body.innerHTML
    document.body.innerHTML = printContent
    window.print()
    document.body.innerHTML = originalContent
  })
}

使用iframe实现静默打印

创建iframe打印方法:

silentPrint(html) {
  const iframe = document.createElement('iframe')
  iframe.style.display = 'none'
  document.body.appendChild(iframe)
  const doc = iframe.contentWindow.document
  doc.open()
  doc.write(html)
  doc.close()

  iframe.contentWindow.onload = () => {
    iframe.contentWindow.print()
    document.body.removeChild(iframe)
  }
}

处理图片打印问题

确保图片加载完成:

vue实现html打印功能

printWithImages() {
  const images = this.$refs.printContent.getElementsByTagName('img')
  let loaded = 0

  Array.from(images).forEach(img => {
    if (img.complete) {
      loaded++
    } else {
      img.onload = () => {
        loaded++
        if (loaded === images.length) {
          this.printPage()
        }
      }
    }
  })

  if (loaded === images.length) {
    this.printPage()
  }
}

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

相关文章

vue单选实现

vue单选实现

Vue 单选实现 在 Vue 中实现单选功能可以通过多种方式完成,以下是几种常见的方法: 使用 v-model 绑定单选按钮 通过 v-model 绑定一个变量,可以实现单选效果。当用户选择不同的选…

vue实现路径

vue实现路径

Vue 实现路径的方法 在 Vue 中实现路径管理通常涉及 Vue Router 的使用,以下是一些常见的实现方法: 安装 Vue Router 通过 npm 或 yarn 安装 Vue Route…

vue实现openoffice

vue实现openoffice

Vue 中集成 OpenOffice 的实现方法 在 Vue 项目中集成 OpenOffice 通常需要通过后端服务或现有库实现文档的预览和编辑功能。以下是几种常见的实现方式: 使用 OnlyOff…

vue实现文章滚动

vue实现文章滚动

Vue 实现文章滚动效果 使用 CSS 实现基础滚动 通过 CSS 的 overflow 和 height 属性控制滚动区域,适用于静态内容滚动。在 Vue 模板中定义固定高度的容器,内容超出后自动滚…

vue实现左右布局

vue实现左右布局

实现左右布局的方法 在Vue中实现左右布局可以通过多种方式完成,以下是几种常见的方法: 使用Flexbox布局 Flexbox是一种现代的CSS布局方式,可以轻松实现左右布局。 <t…

vue实现饼图

vue实现饼图

使用 ECharts 实现 Vue 饼图 安装 ECharts 依赖 npm install echarts --save 在 Vue 组件中引入 ECharts import * as echa…