vue+html2canvas 生成pdf报错
最近在使用html2canvas 生成pdf时,其中背景图是根据后台返回路径而动态生成的,
背景图片无法显示,而图片地址在浏览器中是可以打开显示出来的!
报错信息
js代码
import html2Canvas from 'html2canvas'import JsPDF from 'jspdf'
export default {
install(Vue, options) {
Vue.prototype.$getPdf = function (id, title) {
function getScrollWidth() {
var noScroll, scroll
var oDiv = document.createElement('DIV')
oDiv.style.cssText = 'position:absolute; top:-1000px; width:100px; height:100px; overflow:hidden;'
noScroll = document.body.appendChild(oDiv).clientWidth
oDiv.style.overflowY = 'scroll'
scroll = oDiv.clientWidth
document.body.removeChild(oDiv)
return noScroll - scroll
}
const SIZE = [595.28, 841.89] // a4宽高
let node = document.querySelector(`#${id}`)
let nodeW
if (getScrollWidth()) {
nodeW = node.clientWidth - (17 - getScrollWidth())
} else {
nodeW = node.clientWidth
}
// let nodeW = node.clientWidth
// 单页高度
let pageH = nodeW / SIZE[0] * SIZE[1]
let modules = node.children
for (let i = 0, len = modules.length; i < len; i++) {
let item = modules[i]
let beforeH = item.offsetTop
let afterH = beforeH + item.clientHeight
let currentPage = parseInt(beforeH / pageH)
if (currentPage !== parseInt(afterH / pageH)) {
let lastItemAftarH = modules[i - 1].offsetTop + modules[i - 1].clientHeight
let fill = pageH - lastItemAftarH % pageH
item.style.marginTop = fill + 'px'
}
}
html2Canvas(node, {
// allowTaint: true,
useCORS: true,//跨域设置
scale: 2,
}).then(function (canvas) {
let contentWidth = canvas.width
let contentHeight = canvas.height
let pageHeight = contentWidth / SIZE[0] * SIZE[1]
let leftHeight = contentHeight
let position = 0
// 横向页边距
let sidesway = 0
// html页面生成的canvas在pdf中图片的宽高
let imgWidth = SIZE[0] - sidesway * 2
let imgHeight = imgWidth / contentWidth * contentHeight
let pageData = canvas.toDataURL('image/jpeg', 1.0)
let PDF = new JsPDF('', 'pt', 'a4')
if (leftHeight < pageHeight) {
PDF.addImage(pageData, 'JPEG', sidesway, position, imgWidth, imgHeight)
} else {
while (leftHeight > 0) {
PDF.addImage(pageData, 'JPEG', sidesway, position, imgWidth, imgHeight)
leftHeight -= pageHeight
position -= SIZE[1]
if (leftHeight > 0) {
PDF.addPage()
}
}
}
PDF.save(title + '.pdf')
})
}
}
}
各位大神 ,请问有什么解决办法!
回答
应该是canvas使用图片跨域了,通常需要后端解决
图片跨域了,让存放图片的服务器设置一下就行,联系后端同学修改配置
以上是 vue+html2canvas 生成pdf报错 的全部内容, 来源链接: utcz.com/a/38233.html