Cannot read property OwnerDocument of undefined

Running into this error,

Uncaught (in promise) TypeError: Cannot read property ‘ownerDocument’ of undefined,

and I believe it may have to do with how I pass the element object ID. Can someone tell me if my syntax looks correct?

//Create PDf from HTML…

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";
    });
}
<button type="submit" onclick="CreatePDFfromHTML('calResult')" />Download</button>

Answer

You don’t need the [0] accessor in your call to html2canvas. The div element does not have a 0 property, so [0] returns 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>

Leave a Reply

Your email address will not be published. Required fields are marked *