Uncaught (in promise) TypeError: Cannot read property ‘ownerDocument’ of null 报错详解
- 问题重述:在使用开发的时候使用vue页面转pdf的时候出现的。

- 首先在
/src
文件夹下创建一个htmlToPdf.js
文件
// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default {
install(Vue) {
Vue.prototype.getPdf = function () {//绑定全局方法
html2Canvas(document.querySelector('#pdfDom'), {//指定的需要转pdf的接结点位置
allowTaint: true
}).then(function (canvas) { //绘制canvas
let contentWidth = canvas.width
let contentHeight = canvas.height
let pageHeight = contentWidth / 592.28 * 841.89
let leftHeight = contentHeight
let position = 0
let imgWidth = 595.28
let imgHeight = 592.28 / contentWidth * contentHeight
let pageData = canvas.toDataURL('image/jpeg', 1.0)
let PDF = new JsPDF('', 'pt', 'a4')
if (leftHeight < pageHeight) {
PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
} else {
while (leftHeight > 0) {
PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
leftHeight -= pageHeight
position -= 841.89
if (leftHeight > 0) {
PDF.addPage()
}
}
}
PDF.save('title' + '.pdf')//导出pdf名字
})
}
}
import htmlToPdf from './htmlToPdf' //相对路径
Vue.use(htmlToPdf)
<template>
<!-- 给组件绑定id 这个位置不绑定就会出现如上的错误 -->
<el-container id="pdfDom">
<el-aside width="245px">
<div class="home-aside">
<img src="../assets/img/logo.png" alt="">
<span>test</span>
</div>
</el-aside>
<el-container>
<el-header height="90px">Header</el-header>
<el-main>Main</el-main>
</el-container>
<!-- 添加导出PDF按钮 -->
<el-button type="danger" @click="getPdf()">导出PDF</el-button>
</el-container>
</template>
- 问题解决: 如上就是没有给指定节点绑定id,才会出现报错。