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
})
}