Issue
In my program, I am trying to do a PDF export of some pages, but I encountered the following error when HTML2Canvas tries to process the elements that I have:
Unable to find element in cloned iframe
And only this. This is the code I use:
public exportToPdf(
selectedFilter: SelectedFilter,
currentTime: string,
idOfExportDiv: string[]
): void {
this.addClassToMainDiv();
const elementsToScreenshot: HTMLElement[] = [];
for (let index = 0; index < idOfExportDiv.length; index++) {
elementsToScreenshot.push(document.getElementById(idOfExportDiv[index]));
}
const fileName = 'export-' + currentTime + '.pdf';
this.download(elementsToScreenshot, fileName, selectedFilter, currentTime);
}
And the download function:
download(elementById: HTMLElement[], name, selectedFilter: SelectedFilter, currentTime: string) {
const html2canvasPromises: Promise<unknown>[] = [];
for (let index = 0; index < elementById.length; index++) {
html2canvasPromises.push(
html2canvas(elementById[index], {
useCORS: true
}).then(canvas => {
const image = canvas.toDataURL();
const imagePromise = this.addImage(image);
return imagePromise;
})
);
}
Promise.all(html2canvasPromises)
.then(content => {
this.removeClassFromMainDiv();
this.downloadPdf(selectedFilter, currentTime, name, content);
this.pdfCreated.next(true);
this.loadingSpinnerService.close();
})
.catch(error => {
console.error('Image conversion error', 'Failed to screenshot and download provided elements', {
error: error
});
this.removeClassFromMainDiv();
this.pdfCreated.next(true);
this.loadingSpinnerService.close();
});
}
The "elementsToScreenshot" is an array of HTMLElements that is always filled with the correct found elements inside the HTML rendering, which look like this:
0: div#main-screen-export-div.m-l-20.m-top-15.wrapper-comp
1: div#export-main-0.d-flex.w-100.ng-star-inserted
2: div#export-main-1.d-flex.w-100.ng-star-inserted
3: div#export-main-2.d-flex.w-100.ng-star-inserted
Since I use Angular and I need some dynamically set ids, the ids of the 1,2 and 3 divs are set like this in HTML:
<div [id]="'export-main-' + index"></div>
I have no iframes in my program, trackers, or other 3rd party injectors like google ads, Did anyone else encounter this problem before and knows how to fix it?
EDIT: Maybe this proves helpful. This is the file where the error probably triggers, since I found this exact error in there:
https://github.com/niklasvh/html2canvas/blob/master/src/index.ts
Solution
I found the issue in the end
The nesting of the HTML looked like this:
<div data-html2canvas-ignore="true">
<div>
<div id="export-main-0"></div>
</div>
</div>
The issue was that one of the parent divs had that data-html2canvas-ignore tag applied on it, which made the child div being undetectable by the html2canvas. Simply removing the ignore rule from the parent div made everything work again.
Answered By - Artyomska
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.