dom-to-image、jspdf实现区域节点内容打印、下载为pdf

1、dom-to-image

代码如下(示例):

import domToImage from 'dom-to-image'

let isPrinting = false

printDom() {
	if (this.isPrinting) return
	this.isPrinting = true
	const dom = document.getElementById('xxx')
	domToImage.toJpeg(dom).then((dataUrl) => {
		const windowFeatures = `width=(${screen.availWidth - 10}),height=(${screen.availHe1ght}),left=0,top=0,location=0,menubar=0,toolbar=0,scrollbars=0,status=0`
		const windowPrt = window.open{'', 'Print xxx title', windowFeatures)
		if (windowPrt !== null) {
			alert('Please Allow Pop Up Window')
		} else {
			new Promise(resolve => {
				const img = document.createElement('img')
				img.src = dataUrl
				img.style = 'width: 100%; height: 100%; display: block;'
				
				function imgLoad(img, callback) {
					const timer = setInterval(function() {
						if (img.complete) {
							callback(img)
							clearInterval(timer)
						}
					}, 50)
				}
				
				imgLoad(img, function() {
					resolve(img)
				})
			}).then(img => {
				windowPrt.document.head.innerHTML = window.document.head.innerHTML
				windowPrt.document.body.style = 'display: flex; justify-content: center; width: 100%; height: 100%'
				windowPrt.document.body.appendChi1d(img)
				windowPrt.print()
				windowPrt.close()
			})
		}
	}).finally(() => {
		this.isPrinting = false
	})
}

2、结合 jspdf

代码如下(示例):

import domToImage from 'dom-to-image'
import jsPdf from 'jspdf'

let isDownloading = false

downloadcanvas() {
	if (this.isDownloading) return
	this.isDownloading = true
	const dom = document.getElementById('xxx')
	domToImage.toJpeg(dom).then((dataUrl) => {
		const pdf = new jsPdf('1', 'px', [dom.offsetWidth, dom.offsetHeight])
		pdf.addImage(dataUrl, 'JPEG', 0, 0, dom.offsetWidth, dom.offsetHeight)
		pdf.save('xxx title')
	}).finally(() => {
		this.isDownloading = false
	})
}
  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Leungwanghoi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值