前端打印(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>
相关推荐
程序员与背包客_CoderZ1 小时前
Node.js异步编程——Callback回调函数实现
前端·javascript·node.js·web
非凡ghost1 小时前
Pale Moon:速度优化的Firefox定制浏览器
前端·firefox
清灵xmf2 小时前
从 Set、Map 到 WeakSet、WeakMap 的进阶之旅
前端·javascript·set·map·weakset·weakmap
11054654012 小时前
11、参数化三维产品设计组件 - /设计与仿真组件/parametric-3d-product-design
前端·3d
爱笑的林羽2 小时前
Mac M系列 安装 jadx-gui
前端·macos
运维@小兵2 小时前
vue使用路由技术实现登录成功后跳转到首页
前端·javascript·vue.js
肠胃炎2 小时前
React构建组件
前端·javascript·react.js
邝邝邝邝丹2 小时前
React学习———React.memo、useMemo和useCallback
javascript·学习·react.js
酷爱码2 小时前
HTML5表格语法格式详解
前端·html·html5
hello_ejb32 小时前
聊聊JetCache的缓存构建
java·前端·缓存