javascriptpdf-generationjspdfhtml2canvashtml2pdf

html2pdf won't print hidden div after unhiding it?


I'm trying to create a PDF with html2pdf. I want html2pdf to capture a div that's hidden, and to do this, I'm attempting to briefly "un-hide" my div while the PDF is creating, then "re-hide" the div once the PDF has generated:

function generatePDF() {
    // Choose the element that our invoice is rendered in.
    const element = document.getElementById("nodeToRenderAsPDF");
    // Display the PDF div
    $(element).css("display", "block");
    // Choose the element and save the PDF for our user.
    html2pdf(element);
    //Hide the PDF div
    $(element).css("display", "none");
}

But when the PDF prints, my div is not there. I believe I tried re-hiding the div with a callback function provided by html2pdf at one point, and it worked; however, my hidden div would appear on the screen briefly (0.5-1 second) while the PDF generated before disappearing. I can't have that happen. Also, I'm not much of a fan of placing the div far out of the viewport to compensate for the hiding issue as I've heard this method conflicts with some browsers.

Any ideas for how I may be able to fix this? Any help is extremely appreciated. Thanks!


Solution

  • You can use cloneNode to create clone of element and use it for PDF creation. This cloned element will not be visible unless you append it to document.

    Below code will create a clone of your element, change it's display property, then use this cloned element to create pdf, and finally remove this cloned element.

    function generatePDF() {
    
        // Choose the element that our invoice is rendered in.
        const element = document.getElementById("nodeToRenderAsPDF");
    
        // clone the element
        var clonedElement = element.cloneNode(true);
    
        // change display of cloned element 
        $(clonedElement).css("display", "block");
    
        // Choose the clonedElement and save the PDF for our user.
        html2pdf(clonedElement);
    
        // remove cloned element
        clonedElement.remove();
    }