【发布时间】:2020-03-06 22:58:33
【问题描述】:
在我的程序中,我正在尝试对某些页面进行 PDF 导出,但是当 HTML2Canvas 尝试处理我拥有的元素时遇到以下错误:
无法在克隆的 iframe 中找到元素
只有这个。这是我使用的代码:
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);
}
还有下载功能:
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();
});
}
“elementsToScreenshot”是一个 HTMLElements 数组,在 HTML 渲染中始终填充正确找到的元素,如下所示:
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
由于我使用 Angular 并且我需要一些动态设置的 id,所以 1,2 和 3 div 的 id 在 HTML 中是这样设置的:
<div [id]="'export-main-' + index"></div>
我的程序、跟踪器或其他 3rd 方注入器(如谷歌广告)中没有 iframe, 以前有没有其他人遇到过这个问题并且知道如何解决它?
编辑:也许这会有所帮助。这是可能触发错误的文件,因为我在那里发现了这个确切的错误:
https://github.com/niklasvh/html2canvas/blob/master/src/index.ts
【问题讨论】:
标签: javascript angular html2canvas