Search code examples
javascriptcallbackhtml5-canvashtml2canvas

html2Canvas unable to retrieve the data url in time for pdf generation


I need help with assigning the data url I get from the html2canvas promise to the listingReportImg in the downloadPdf() function.

Expected Result:

listingReportImg = data:image/png;base64,iVBORw0KGgoAAAANSUhEUg ...

Logs

listingReportImg::  undefined

listing report uri:: 
data:image/png;base64,iVBORw0KGgoAAAANSUhEUg ...

listings.component.html

<button (click)="downloadPdf()">Print</button>

listings.component.ts

listingReportToDataUrl(){
    let listingReport = document.getElementById('listing-report');
    console.log("listingReport:: ", listingReport);
    html2canvas( listingReport, { useCORS: true } )
        .then(function (canvas) {
            let listingReportUri = canvas.toDataURL('image/png');
            console.log("listing report uri::", listingReportUri);
            return listingReportUri;
        });
}

downloadPdf(){
    let listingReportImg = this.listingReportToDataUrl();
    console.log("listingReportImg:: ", listingReportImg);
    pdfMake.createPdf(listingReport( listingReportImg )).download('test.pdf');
}

Solution

  • Having returned from your callbacks properly,

    listingReportToDataUrl(){
                const listingReport = document.getElementById('listing-report')
                return html2canvas( listingReport, { useCORS: true } )
                    .then((canvas) => {
                        return canvas.toDataURL('image/png')
                    })
        }
    

    you could,

    listingReportToDataUrl().then((listingReportImg  => {
        pdfMake.createPdf(listingReport( listingReportImg )).download('test.pdf')
    })