【问题标题】:Cannot read property OwnerDocument of undefined无法读取未定义的属性 OwnerDocument
【发布时间】:2021-03-08 20:58:17
【问题描述】:

遇到这个错误,

Uncaught (in promise) TypeError: Cannot read property 'ownerDocument' 的未定义,

我相信这可能与我传递元素对象 ID 的方式有关。谁能告诉我我的语法是否正确?

//从 HTML 创建 PDf...

function CreatePDFfromHTML(divName) {
    var HTML_Width = document.getElementById(divName).style.width;
    var HTML_Height = document.getElementById(divName).style.height;
    var top_left_margin = 15;
    var PDF_Width = HTML_Width + (top_left_margin * 2);
    var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
    var canvas_image_width = HTML_Width;
    var canvas_image_height = HTML_Height;

    var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;

    html2canvas(document.getElementById(divName)[0]).then(function (canvas) {
        var imgData = canvas.toDataURL("image/jpeg", 1.0);
        var pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
        pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height);
        for (var i = 1; i <= totalPDFPages; i++) {
            pdf.addPage(PDF_Width, PDF_Height);
            pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height * i) + (top_left_margin * 4), canvas_image_width, canvas_image_height);
        }
        pdf.save("Your_PDF_Name.pdf");
        document.getElementById(divName).style.visibility = "hidden";
    });
}
&lt;button type="submit" onclick="CreatePDFfromHTML('calResult')" /&gt;Download&lt;/button&gt;

【问题讨论】:

    标签: javascript html pdf


    【解决方案1】:

    您在调用html2canvas 时不需要[0] 访问器。 div 元素没有 0 属性,因此 [0] 返回 undefined。

    function CreatePDFfromHTML(divName) {
    
      // This is incorrect.
      console.log(document.getElementById(divName)[0]);
    
      // Use this instead.
      console.log(document.getElementById(divName));
    }
    <div id="calResult">Hello, World!</div>
    <button type="submit" onclick="CreatePDFfromHTML('calResult')">Download</button>

    【讨论】:

    • 谢谢你就是这样。我真的应该质疑 [0] 在那里
    猜你喜欢
    • 2023-03-08
    • 2022-01-26
    • 2013-07-09
    • 1970-01-01
    • 2020-06-12
    • 2020-04-06
    • 2020-10-30
    • 2019-10-09
    • 1970-01-01
    相关资源
    最近更新 更多