eKoopmans / html2pdf.js

Client-side HTML-to-PDF rendering using pure JS.
MIT License
4.04k stars 1.37k forks source link

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

Open Prasadgws opened 1 year ago

Prasadgws commented 1 year ago

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?

yurass13 commented 1 year ago

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.

geraldo commented 1 year ago
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.

yurass13 commented 1 year ago
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.