Search code examples
javascriptjspdf

Exporting each html classes to pdf file


I am trying to export html .class to merged pdf pages. Using this library: pdfMake

inside body there are two .content and I gave a4 styling..

.content {
    padding: 50px 0;
    width: 1000px;
    height: 842px;
}

and trying to export those elements to PDF.

UPDATED

function makePdf(){
    pages = document.querySelectorAll(".content")
    html2canvas(pages, {
        onrendered: function (canvas) {
            var data = canvas.toDataURL();
            var docDefinition = {
                content: [{
                    image: data,
                    width: 500
                }]
            };


            pdfMake.createPdf(docDefinition).download("document.pdf");
        }
    });
}

But the problem here. I can't export .content as a merged pdf pages. When I use it like this: html2canvas(pages, { it's export 2 merged pages but empty.

I tried to check it like this. html2canvas(pages[0], { then it's exporting one pdf file without a problem. but the second .content is not coming(of course...)

So I put it in forEach loop like below.

function makePdf(){
    pages = document.querySelectorAll(".content")
    pages.forEach(page => {
        html2canvas(page, {
            onrendered: function (canvas) {
                var data = canvas.toDataURL();
                var docDefinition = {
                    content: [{
                        image: data,
                        width: 500
                    }]
                };


                pdfMake.createPdf(docDefinition).download("table.pdf");
            }
        });
    })

}

But then it's exporting .content pdfs one by one. it's not merged...

I am a bit confused. How can I achieve merged pdf pages from .content


Solution

  • it nearly killed me but, in the end I solved the problem. used jsPDF library, instead of pdfMake.

    styles

    .content {
        margin: auto;
        padding: 50px 0;
        width: 1000px;
        height: auto;
    }
    

    script

    function makePdf(){
    
        pages = document.querySelectorAll(".content")
        let count = 0;
        pages.forEach(page => {
            html2canvas(page, {
                onrendered: function (canvas) {
                    // var data = canvas.toDataURL();
                    var data = canvas.toDataURL('image/png');
                    var imgWidth = pdf.internal.pageSize.getWidth();
                    pdf.addImage(data, 'PNG', '', '', imgWidth, 0);
                    pdf.addPage(page)
                    count++;
                    if (count === pages.length) {
                        pdf.save("document.pdf")                        
                    }
                }
            });
        }) //loop       
    } //fn.
    

    P.S: about the pdf page sizing, you should avoid using internal.pageSize.getHeight(); if you expect good resolution. just give it 0