前端打印(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>
相关推荐
子兮曰3 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰3 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
前端小万3 天前
写公众号赚了 3000 块后,我做了一款叫 "一键成稿" 的软件
前端·微信小程序
爱勇宝3 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
三十而立洋3 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
卡布鲁3 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
李少兄3 天前
JavaScript 隐式全局变量解析
javascript
汉堡大王95273 天前
Jev:不是聊天机器人, 而是一个智能 if 语句
前端·人工智能·后端
梦想很大很大3 天前
从运行事实到回归证据:Workrun 的 Telemetry 与 Evaluation 实践
前端·人工智能·后端
计算机魔术师3 天前
Meta Muse agent 接入 Shopify 的 Shop Pay 实现代理式购物
前端