html2canvas is throwing error when passing the element to it in LWC

205 Views Asked by At

I am trying to create the snapshot of LWC using html2canvas but it is throwing me error that 'element is not attached to document'. Please find below LWC code I am using : I am also using the highchart to render chart in LWC & with chart I am also looking to get the snapshot of the all things in the main container

<template>
    <lightning-card>
        <div class="chartContainer">
            <div class="container" lwc:dom="manual"></div>
            <div class="testc">
                <p>Any text content goes here........ </p>
                <p>Test</p>
            </div>
        </div>
        <lightning-button label="Download PDF" onclick={generatePDF}></lightning-button>
    </lightning-card>   
</template>

import { LightningElement } from 'lwc';
import {loadScript} from 'lightning/platformResourceLoader';
import highchart from '@salesforce/resourceUrl/HighChart';
import html2canvas from '@salesforce/resourceUrl/html2canvas';
import jsPDF from '@salesforce/resourceUrl/jsPDF';

export default class ChartForm extends LightningElement {   
    renderedCallback(){
        Promise.all([            
            loadScript(this,highchart),
            loadScript(this,html2canvas),
            loadScript(this,jsPDF+'/jspdf.umd.min.js'),
        ]).then(()=>{            
            this.renderChart();            
        }).catch(error=>{
            console.log('Error loading High chart'+error);
        });
    }
    renderChart(){
        window.Highcharts.chart(this.template.querySelector('.container'),{
            chart:{
                type: 'column'
            },
            title:{
                text: 'HighChart Snapshot'
            },
            xAxis:{
                categories:['Col1', 'Col2', 'Col3'],
                gridLinewidth: 1,
                linewidth: 0
            },
            yAxis:{
                title:{
                    text: 'Amount (in Millions)'
                }
            },
            series:[{
                name : 'Col Name',
                data:[631,727,800] 
            }
        });
    }

    generatePDF(){
        let elem = this.template.querySelector('.chartContainer');
        console.log('ele ==>'+elem);
        try{
        window.html2canvas(elem).then(function (canvas) {
            console.log('inside script');
            const imgData = canvas.toDataURL('image/png');
            const imgWidth = (canvas.width * 20) / 120;
            const imgHeight = (canvas.height * 20) / 120;
            const { jsPDF } = window.jspdf;
            const pdf = new jsPDF("p", "mm", "a4");
            pdf.addImage(imgData, 'PNG', 5, 5, imgWidth, imgHeight);
            pdf.save("highchart.pdf");
        });
    }catch(error){
        console.log('error==>'+error);
    }   
    }
}
0

There are 0 best solutions below