html2canvas and jsPDF image not being rendered

Viewed 341

Currently I am working on a little side project. My goal is the generate a PDF file (client side) from the bingo cards that I request from my web api. My web api returns the bingo cards as HTML tables and they are being rendered on the frontend. Currently I am using jsPDF together with html2canvas so that I can take a screenshot and add this image to the pdf file. Unfortunately I cannot figure out why my generated pdf remains empty. I tried to adjust the pdf width and height but that didn't help.

<div>
    <button mat-raised-button color="primary" type="button" (click)="this.downloadPDF()">Download PDF</button>
    <div id="bingocard-container" #bingocardsData>
        <div class="bingocard" *ngFor="let bingoCard of this.bingoCards">
            <div [ngStyle]="{'background-color': this.backgroundColor}" [innerHTML]="bingoCard.grid"></div>
        </div>
    </div>
</div>

When the user click the download pdf the file is being generated.

public downloadPDF(): void {
  let doc = new jsPDF('p', 'mm', this.bingoCardFormGroup.get('paperSize').value);
  const element = document.getElementById('bingocard-container');

  html2canvas(element).then(function (canvas) {
    let img = canvas.toDataURL('image/png');
    const imgProps= doc.getImageProperties(img);
    const pdfWidth = doc.internal.pageSize.getWidth();
    const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
    doc.addImage(img, 'PNG', 0, 0, pdfWidth, pdfHeight);
    doc.save('bingo-cards.pdf');
  });
}

The funny thing is that when I call html2canvas(document.body) the screenshot is taken properly and the pdf file indeed contains the desired outcome. Hopefully, someone can help

Edit
Today I stumbled upon a blog post about html2canvas which said that calling window.scroll(0, 0) before you capture the screenshots should fix the issue and luckily it did.

0 Answers
Related