vue实现页面打印

安装需要依赖

npm i html2canvas --save
npm i jspdf --save
npm i print-js --save

页面导入

import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
import printJS from 'print-js'

实现方法

// 纸张的边距
const margin = 30
// 先把需要打印的页面内容转为canvas,避免各种样式问题
const canvas = await html2canvas(this.$refs['content'])
// 计算canvas内容在A4纸张上的宽度和高度
// a4纸的尺寸[595.28, 841.89]
const imgWidth = 841.89 - margin * 2
const imgHeight = 841.89 / (canvas.width / canvas.height) - margin * 2
// 将canvas转换成图片地址
const pageData = canvas.toDataURL('image/jpeg', 1.0)
// 初始化pdf
// l:横向  p:纵向
// 测量单位("pt","mm", "cm", "m", "in" or "px")
const pdf = new jsPDF('l', 'pt', 'a4')
// 将图片写入pdf中
pdf.addImage(pageData, 'JPEG', margin, margin, imgWidth, imgHeight)
// pdf增加空白页
pdf.addPage()
// 打印pdf
printJS({
  printable: pdf.output('bloburi'),
  type: 'pdf',
  scanStyles: false,
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值