当前位置:首页 > VUE

vue页面实现打印功能

2026-02-22 19:39:23VUE

使用 window.print() 方法

在 Vue 组件中直接调用浏览器原生打印 API,适合简单打印需求。通过 window.print() 触发浏览器打印对话框。

<template>
  <div>
    <div id="printContent">
      <!-- 需要打印的内容 -->
      <h1>打印标题</h1>
      <p>打印内容示例</p>
    </div>
    <button @click="handlePrint">打印</button>
  </div>
</template>

<script>
export default {
  methods: {
    handlePrint() {
      window.print();
    }
  }
}
</script>

<style>
@media print {
  /* 隐藏非打印内容 */
  body * {
    visibility: hidden;
  }
  #printContent, #printContent * {
    visibility: visible;
  }
  /* 调整打印布局 */
  #printContent {
    position: absolute;
    left: 0;
    top: 0;
  }
}
</style>

使用 vue-print-nb 插件

安装第三方插件 vue-print-nb 提供更便捷的打印功能,支持指定打印区域和自定义配置。

npm install vue-print-nb --save

在 Vue 项目中注册插件:

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

组件中使用方式:

<template>
  <div>
    <div id="printArea">
      <!-- 打印内容 -->
      <table>
        <tr><th>名称</th><th>值</th></tr>
        <tr><td>项目</td><td>示例</td></tr>
      </table>
    </div>
    <button v-print="printConfig">打印表格</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      printConfig: {
        id: 'printArea',
        popTitle: '打印标题',  // 打印页眉
        extraCss: 'https://example.com/print.css',  // 额外CSS
        extraHead: '<meta http-equiv="Content-Language" content="zh-cn">'  // 额外HEAD
      }
    }
  }
}
</script>

使用 html2canvas + jsPDF 生成PDF打印

需要先安装依赖库:

npm install html2canvas jspdf --save

实现代码示例:

<template>
  <div>
    <div ref="printRef">
      <!-- 复杂打印内容 -->
      <div v-for="item in list" :key="item.id">
        {{ item.name }}: {{ item.value }}
      </div>
    </div>
    <button @click="exportToPDF">导出PDF并打印</button>
  </div>
</template>

<script>
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'

export default {
  data() {
    return {
      list: [
        { id: 1, name: '项目A', value: 100 },
        { id: 2, name: '项目B', value: 200 }
      ]
    }
  },
  methods: {
    async exportToPDF() {
      const element = this.$refs.printRef
      const canvas = await html2canvas(element, {
        scale: 2,  // 提高分辨率
        logging: false,
        useCORS: true
      })

      const pdf = new jsPDF('p', 'mm', 'a4')
      const imgData = canvas.toDataURL('image/png')
      const imgWidth = 210  // A4纸宽度
      const pageHeight = 297  // A4纸高度
      const imgHeight = canvas.height * imgWidth / canvas.width

      let heightLeft = imgHeight
      let position = 0

      pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight)
      heightLeft -= pageHeight

      while (heightLeft >= 0) {
        position = heightLeft - imgHeight
        pdf.addPage()
        pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight)
        heightLeft -= pageHeight
      }

      pdf.save('report.pdf')
      // 如需直接打印
      // pdf.autoPrint()
      // window.open(pdf.output('bloburl'))
    }
  }
}
</script>

打印样式优化技巧

为获得更好的打印效果,需要在 CSS 中设置打印专用样式:

@media print {
  /* 隐藏不需要打印的元素 */
  .no-print {
    display: none !important;
  }

  /* 确保链接显示完整URL */
  a[href^="http"]:after {
    content: " (" attr(href) ")";
  }

  /* 分页控制 */
  .page-break {
    page-break-after: always;
  }

  /* 背景颜色和图像 */
  * {
    -webkit-print-color-adjust: exact !important;
    print-color-adjust: exact !important;
  }

  /* 调整边距 */
  @page {
    size: auto;
    margin: 10mm;
  }
}

服务端打印方案

对于需要精确控制打印格式的场景,可考虑服务端生成打印文档:

// 后端API示例(Node.js)
const express = require('express')
const puppeteer = require('puppeteer')

const app = express()
app.get('/print', async (req, res) => {
  const browser = await puppeteer.launch()
  const page = await browser.newPage()
  await page.goto('http://your-frontend-url/print-view')
  const pdf = await page.pdf({
    format: 'A4',
    printBackground: true,
    margin: { top: '20mm', right: '20mm', bottom: '20mm', left: '20mm' }
  })
  await browser.close()

  res.contentType('application/pdf')
  res.send(pdf)
})

前端调用方式:

this.$axios.get('/print', { responseType: 'blob' })
  .then(response => {
    const blob = new Blob([response.data], { type: 'application/pdf' })
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = 'document.pdf'
    link.click()
  })

vue页面实现打印功能

标签: 页面功能
分享给朋友:

相关文章

vue实现名字查找功能

vue实现名字查找功能

实现名字查找功能 在Vue中实现名字查找功能,可以通过多种方式完成。以下是几种常见的实现方法: 使用v-model和computed属性 创建一个输入框,使用v-model绑定输入的值,通过com…

h5能实现的功能

h5能实现的功能

H5能实现的功能 H5(HTML5)是一种现代的网页技术标准,具备丰富的功能和特性,适用于多种场景。以下是H5能够实现的主要功能: 多媒体支持 H5原生支持音频和视频播放,无需依赖Flash等插件。…

vue 实现 功能

vue 实现 功能

Vue.js 是一个流行的前端框架,用于构建用户界面和单页应用程序。以下是一些常见的 Vue 功能实现方法: 数据绑定 Vue 的核心特性之一是数据绑定,可以通过 v-model 指令实现双向数据绑…

php实现linux关机重启功能

php实现linux关机重启功能

通过PHP执行Linux关机或重启命令 PHP可以通过exec()、shell_exec()或system()等函数调用系统命令实现关机或重启功能,但需注意权限问题。 使用exec函数执行命令 //…

jquery页面

jquery页面

jQuery 页面操作指南 jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互的操作。以下是 jQuery 在页面中的常见使用方法…

uniapp实现支付功能

uniapp实现支付功能

支付功能实现概述 在UniApp中实现支付功能通常需要对接第三方支付平台(如微信支付、支付宝支付等)。以下是基于微信支付和支付宝支付的通用实现流程。 微信支付实现步骤 1. 配置支付权限 在微信开…