前端打印(html)

目录

1.window.print()

2.使用插件print.js

1.window.print()

<template>

<div id="contenteBox">内容</div>

<button @click="printContent">打印</button>

</template>

<script>

export default{

data(){

return{}

},

methods:{

printContent(){

let contentDom=document.getElementById('contenteBox')

let html=`

<head>

<style lang='scss'>

#contenteBox{font-size:18px;background-color:#333}

<style>

</head>

<body>${contentDom.innerHTML}</body>

`

window.print()

}

}

}

</script>

let contentDom=document.getElementById('contenteBox') //获取id为contenteBox的dom元素

html //设置打印主体以及css样式

window.print() //打印

也可以let bodyContent = document.getElementById('contenteBox').innerHTML 通过 获取需要打印的元素

通过 document.body.innerHTML=bodyContent 把当前页面替换为打印内容HTML

window.print()打印 //记得最后还原页面

2.使用插件print.js

2.1 vue2

https://www.npmjs.com/package/print-js

复制代码
npm install print-js --save
复制代码
yarn add print-js
复制代码
import printJS from 'print-js'
复制代码
<template>
  <div>
    <button @click="printContent">打印</button>
    <div id="contenBox">
      <div>内容</div>
    </div>
  </div>
</template>

<script>
import printJS from 'print-js';

export default {
  methods: {
    printContent() {
      printJS({
        printable: 'contenBox',
        type: 'html',
        documentTitile:'打印',
        style: `
          #contenBox{
              color:#333,
              font-size:20px
          }
        `
      });
    }
  }
};
</script>

printable 文档来源

type 打印类型

documentTitle 打印显示的文档标题

style 自定义样式

2.2 vue3

复制代码
<template>
  <div>
    <button @click="printContent">打印</button>
    <div ref="contenBox">
      <div>内容</div>
    </div>
  </div>
</template>

<script>
import printJS from 'print-js';
let contenBox=ref()
function printContent() {
      printJS({
        printable: 'contenBox',
        type: 'html',
        documentTitile:'打印',
        style: `
          #contenBox{
              color:#333,
              font-size:20px
          }
        `
      });
    }
</script>
相关推荐
写代码的皮筏艇5 小时前
CSS中常使用的函数
前端·css
Cache技术分享6 小时前
261. Java 集合 - Java 开发必备:ArrayList 与 LinkedList 的选择攻略
前端·后端
涔溪6 小时前
深入了解 Node.js 性能诊断工具 Clinic.js 的底层工作原理
开发语言·javascript·node.js
Neptune16 小时前
js防抖技术:从原理到实践,如何解决高频事件导致的性能难题
前端·javascript
是你的小橘呀6 小时前
从爬楼梯到算斐波那契,我终于弄懂了递归和动态规划这俩 "磨人精"
前端·javascript·面试
m0_740043736 小时前
Vuex中commit和dispatch的核心区别
前端·javascript·html
草字6 小时前
css 按钮的脉冲光环动画,强调动画。
前端·css
BD_Marathon6 小时前
【JavaWeb】CSS_三大选择器
前端·css
jump6806 小时前
柯里化
前端
NeoInfra6 小时前
全面解读ThinkPHP 5.0:现代PHP框架的架构演进与安全实践
前端