html2pdf.js icon indicating copy to clipboard operation
html2pdf.js copied to clipboard

How to show scrollable all contents of div in pdf using html2canvas

Open Prasadgws opened this issue 2 years ago • 3 comments

var element = document.getElementById('vb-content-MainDiv'); window.scrollTo(0,0)

    var opt = {
        margin:       0.3,
        filename:     'myfile.pdf',
        image:        { type: 'jpeg', quality: 3 },
        html2canvas:  { scale: 3,allowTaint: true, scale: 2, logging: true, dpi: 300, letterRendering: true, scrollY: -window.scrollY, scrollX: -window.scrollX },
       pagebreak: { mode: ['avoid-all', 'css', 'legacy'] },
        jsPDF:        { unit: 'in', format: 'letter', orientation: 'portrait',precision: '1' }
      };
    
    // choose the element and pass it to html2pdf() function and call the save() on it to save as pdf.
    html2pdf().set(opt).from(element).save();

I have tried the above solution can you please help out?

Prasadgws avatar May 25 '23 19:05 Prasadgws

I'm not sure if this is the right solution, but I got it like this:

function html2pdfRemoveOverflow(element, options = {},copy = true){
    let cp_elem;
    if (copy){
        cp_elem = element.cloneNode(true);
    }
    else{
        cp_elem = element
    }
    for (const child of cp_elem.children){
        if (child.style.overflow == 'hidden' || child.style.overflow == 'auto'){
            child.style.overflow == 'visible';
        }
        child.style.maxHeight='none';
        child.style.height='auto';
        html2pdfRemoveOverflow(child, options, false)
    }
    if (copy){
        html2pdf(cp_elem,options);
    }
};

You need just set overflow 'visible' and reset height in parents of your scrollable. If you know id or class of scrollable containers you just need replace recursion by cycle of target containers.

yurass13 avatar Jun 08 '23 07:06 yurass13

child.style.maxHeight='auto';

Thanks for the hint. The only thing I would change is to set max-height to unset, as auto is not valid.

geraldo avatar Jul 19 '23 09:07 geraldo

child.style.maxHeight='auto';

Thanks for the hint. The only thing I would change is to set max-height to unset, as auto is not valid.

Thanks for your clarification! I have modified the example accordingly. I hope this helps those who encounter a similar problem in the future.

yurass13 avatar Jul 19 '23 10:07 yurass13