当前位置:首页 > VUE

vue页面实现打印功能

2026-01-22 04:38:11VUE

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

在Vue组件中直接调用浏览器原生打印API是最简单的方式。通过window.print()会触发浏览器打印对话框,打印当前页面全部内容。

<template>
  <div>
    <button @click="handlePrint">打印页面</button>
    <div class="print-content">需要打印的内容区域</div>
  </div>
</template>

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

<style>
@media print {
  /* 隐藏不需要打印的元素 */
  button {
    display: none;
  }

  /* 调整打印样式 */
  .print-content {
    font-size: 12pt;
  }
}
</style>

使用vue-print-nb插件

安装专门的Vue打印插件可以更灵活地控制打印内容:

npm install vue-print-nb --save

在项目中使用:

import Print from 'vue-print-nb'

Vue.use(Print)

模板中使用v-print指令:

<template>
  <div>
    <button v-print="printObj">打印指定区域</button>
    <div id="printArea">
      <!-- 需要打印的内容 -->
    </div>
  </div>
</template>

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

打印样式优化

通过CSS媒体查询专门设置打印样式:

@media print {
  body * {
    visibility: hidden;
  }

  #printSection, #printSection * {
    visibility: visible;
  }

  #printSection {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
  }

  /* 移除背景色和图片 */
  * {
    background-color: transparent !important;
    color: #000 !important;
    background-image: none !important;
  }

  /* 调整边距 */
  @page {
    size: A4;
    margin: 0;
  }
}

打印分页控制

使用CSS控制打印分页:

.page-break {
  page-break-after: always;
}

.avoid-break {
  page-break-inside: avoid;
}

生成PDF打印

使用html2pdf.js等库生成PDF:

vue页面实现打印功能

import html2pdf from 'html2pdf.js'

export default {
  methods: {
    generatePDF() {
      const element = document.getElementById('pdf-content')
      const opt = {
        margin: 1,
        filename: 'document.pdf',
        image: { type: 'jpeg', quality: 0.98 },
        html2canvas: { scale: 2 },
        jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
      }

      html2pdf().from(element).set(opt).save()
    }
  }
}

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

相关文章

vue实现页面分页

vue实现页面分页

Vue实现页面分页的方法 使用Element UI的分页组件 Element UI提供了现成的分页组件el-pagination,适合快速集成。以下是一个示例代码: <template>…

jquery页面跳转

jquery页面跳转

jQuery 页面跳转方法 使用 jQuery 实现页面跳转可以通过多种方式完成,以下是几种常见的方法: 使用 window.location.href 通过修改 window.location.h…

vue实现反馈页面

vue实现反馈页面

Vue 实现反馈页面的方法 表单组件设计 使用 Vue 的 v-model 实现表单数据双向绑定,创建包含输入框、下拉框和提交按钮的基础表单结构。表单字段通常包括用户姓名、联系方式、反馈类型和详细内容…

php实现评论功能

php实现评论功能

数据库设计 创建评论表(示例结构): CREATE TABLE `comments` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id`…

实现js页面跳转页面跳转页面

实现js页面跳转页面跳转页面

使用 window.location.href 实现跳转 通过修改 window.location.href 属性,可以直接跳转到目标 URL。这种方法会触发页面刷新,并在浏览器历史记录中留下记录。…

h5实现页面3d切换

h5实现页面3d切换

使用CSS 3D变换实现基础效果 在HTML5中实现3D页面切换,可以通过CSS的transform属性结合3D变换函数。创建一个包含多个页面的容器,通过调整transform-style和persp…