Html2canvas: DOMException: Falha ao definir a propriedade 'adoptedStyleSheets' em 'ShadowRoot': Não é permitido partilhar folhas de estilo construídas em vários documentos

Criado em 4 nov. 2019  ·  13Comentários  ·  Fonte: niklasvh/html2canvas

DOMException: Falha ao definir a propriedade 'adoptedStyleSheets' em 'ShadowRoot': Não é permitido partilhar folhas de estilo construídas em vários documentos

Comentários muito úteis

mesmo problema usando no angular 8 e iônico 4

Todos 13 comentários

Eu tenho o mesmo problema; Como lidar com isso ?

mesmo problema usando no angular 8 e iônico 4

Mesmo problema ionic4, como resolvê-lo?

Estou enfrentando o mesmo problema com o iônico 5 ... Alguém encontrou alguma solução?

Plano provisório de Yupeng em iônico 4

  • index.html
<body>
  <div id="html2canvas"></div>
  <app-root></app-root>
</body>
  • xxx.ts
const element = document.getElementById('html2canvas');
const targetElement = document.getElementById('target').cloneNode(true);
element.appendChild(targetElement);
this.html2canvas.html2canvas(element.firstChild).then((img) => {
    this.img = img;
    element.firstChild.remove();
}).catch((res) => {
    console.log(res);
});
  • Html2canvasService.service.ts
import {Injectable} from '@angular/core';
import {AlertService} from './alert.service';

declare let html2canvas;

@Injectable()
export class Html2canvasService {
    constructor(private alert: AlertService) {

    }

    public html2canvas(ele) {

        if (!ele) {
            return;
        }

        const option = {allowTaint: true, useCORS: true};
        return html2canvas(ele, option).then((canvas) => {
            if (canvas) {
                return canvas.toDataURL('image/png');
            }
            return null;
        }).catch((res) => {
            console.log(res);
            return res;
        });
    }
}

@ G-yanpeng Você pode, por favor, elaborar mais sua solução? Estou tentando fazer o mesmo para a versão iônica 4 angular8.

Obrigado!

Mesmo problema. Alguém encontrou alguma solução?

Obrigado!

@ G-yanpeng Você pode elaborar mais a sua solução? Estou tentando fazer o mesmo para a versão iônica 4 angular8.

Obrigado!

O Angular8 tem novas mudanças, o que faz com que o html2canvas não funcione corretamente. Então há esta solução temporária, deixe html2canvas trabalhar fora do angular, copie o dom que precisa gerar a imagem para a mesma camada da entrada angular (app-root) para evitar a influência causada pelo angular.

O Angular8 tem novas mudanças que fazem com que o html2canvas não funcione corretamente. Então há esta solução temporária para fazer o html2canvas funcionar fora do angular, copie o dom que precisa gerar a imagem para a mesma camada da entrada angular (app-root) para evitar o impacto do angular.
- pelo google tradutor

image

Você pode fornecer o código completo do arquivo do componente xxx.ts? Também encontramos o mesmo erro ao tentar exportar para .pdf. Exceto por esse erro, todo o resto está normal. Também consigo visualizar o arquivo .pdf.
Este é o meu código:
(Traduzido para o chinês usando o tradutor do Google)
`
import {Component, OnInit} de '@ angular / core';
importar {WcExpenditureCalcPipe} de'src / app / _pipes / wc-despesa-calc.pipe ';
// exportar para pdf
import {Router} de '@ angular / router';
import {ExportAsService, ExportAsConfig} from'ngx-export-as ';
importar {Platform} de '@ ionic / angular';
importar {FileOpener} de '@ ionic-native / file-opener / ngx';
importar {Arquivo} de '@ ionic-native / file / ngx';
importar {FileTransfer, FileTransferObject} de '@ ionic-native / file-transfer / ngx';

  @Component({
    selector: 'app-wc-estimate',
    templateUrl: './wc-estimate.page.html',
    styleUrls: ['./wc-estimate.page.scss'],
    providers: [WcExpenditureCalcPipe]
  })
  export class WcEstimatePage implements OnInit {
    dataEntered: any;
    wcEstimate: any;

    // export config
    storageDirectory: any;

    exportAsConfig: ExportAsConfig = {
      type: 'pdf', // the type you want to download
      elementId: 'myDiv', // the id of html/table element
      options: {
        margin: 15,
        jsPDF: {
          orientation: 'portrait',
          format: 'a4',
          unit: 'mm'
        },
        pdfCallbackFn: this.pdfCallbackFn // to add header and footer
      },
    }
    constructor(
      public router: Router,
      private exportAsService: ExportAsService,
      private transfer: FileTransfer,
      private file: File,
      private platform: Platform,
      private fileOpener: FileOpener,
      private wcExpenditureCalcPipe: WcExpenditureCalcPipe
    ) {
      this.platform.ready().then(() => {
        if (!this.platform.is('cordova')) {
          return false;
        }

        if (this.platform.is('ios')) {
          this.storageDirectory = this.file.externalDataDirectory;
        }
        else if (this.platform.is('android')) {
          this.storageDirectory = this.file.externalDataDirectory;
        }
        else {
          return false;
        }
      });
    }

    ngOnInit() {
      this.dataEntered = JSON.parse(localStorage.getItem('DataEntered'));
      this.getValues(this.dataEntered);
    }
    getValues(dataEntered: any) {
      this.wcEstimate = this.wcExpenditureCalcPipe.getWCE(dataEntered)
      console.log(this.wcEstimate);
    }

    // export PDF
    export(event) {
      const fileTransfer: FileTransferObject = this.transfer.create();

      this.exportAsService.get(this.exportAsConfig).subscribe((data: any) => {
        const fileName = 'PReport ' + this.dataEntered.Project_Name + ' - WC Estimate.pdf';
        fileTransfer.download(data, this.storageDirectory + fileName).then((entry) => {
          this.fileOpener.open(entry.toURL(), 'application/pdf').then(() => {
          }).catch(e => {
            console.log('Error opening file', e);
          });
        }, (error) => {
          console.log('error ' + JSON.stringify(error));
        });
      });
      event.preventDefault();
    }
    pdfCallbackFn(pdf: any) {
      // example to add page number as footer to every page of pdf
      const noOfPages = pdf.internal.getNumberOfPages();
      for (let i = 1; i <= noOfPages; i++) {
        pdf.setPage(i);
        pdf.text('WC Estimate', 15, 10)
        pdf.text('Page ' + i + ' of ' + noOfPages, 15, pdf.internal.pageSize.getHeight() - 10);
      }
    }

    //Edit report 
    editClick(event: any) {
      localStorage.setItem('isEdit', 'true');
      this.router.navigateByUrl('/dashboard/landing');

    }
    //done click 
    doneClick(event: any) {
      this.router.navigateByUrl('/dashboard/review');

    }
    // exit click 
    exitClick(event: any) {
      this.router.navigateByUrl('/dashboard/entry-point');
    }

  }

`
O evento platform.ready não é realmente necessário. Eu estava tentando adicionar a pasta 'Download' se for android e a pasta 'Documentos' se for iOS.

@ravimallya
Atualizei o conteúdo em html2canvasservice.service.ts, mas não acho que isso vá te ajudar. Deve-se notar que usando este esquema temporário, as imagens podem ser geradas normalmente, mas a exceção de lançamento ainda será relatada.
Talvez você possa tentar a geração de PDF usando JSPDF e html2canvas.

Plano provisório de Yupeng em iônico 4

  • index.html
<body>
  <div id="html2canvas"></div>
  <app-root></app-root>
</body>
  • xxx.ts
const element = document.getElementById('html2canvas');
const targetElement = document.getElementById('target').cloneNode(true);
element.appendChild(targetElement);
this.html2canvas.html2canvas(element.firstChild).then((img) => {
    this.img = img;
    element.firstChild.remove();
}).catch((res) => {
    console.log(res);
});
  • Html2canvasService.service.ts
import {Injectable} from '@angular/core';
import {AlertService} from './alert.service';

declare let html2canvas;

@Injectable()
export class Html2canvasService {
    constructor(private alert: AlertService) {

    }

    public html2canvas(ele) {

        if (!ele) {
            return;
        }

        const option = {allowTaint: true, useCORS: true};
        return html2canvas(ele, option).then((canvas) => {
            if (canvas) {
                return canvas.toDataURL('image/png');
            }
            return null;
        }).catch((res) => {
            console.log(res);
            return res;
        });
    }
}

Muito obrigado! Ótima solução alternativa!

Plano provisório de Yupeng em iônico 4

  • index.html
<body>
  <div id="html2canvas"></div>
  <app-root></app-root>
</body>
  • xxx.ts
const element = document.getElementById('html2canvas');
const targetElement = document.getElementById('target').cloneNode(true);
element.appendChild(targetElement);
this.html2canvas.html2canvas(element.firstChild).then((img) => {
    this.img = img;
    element.firstChild.remove();
}).catch((res) => {
    console.log(res);
});
  • Html2canvasService.service.ts
import {Injectable} from '@angular/core';
import {AlertService} from './alert.service';

declare let html2canvas;

@Injectable()
export class Html2canvasService {
    constructor(private alert: AlertService) {

    }

    public html2canvas(ele) {

        if (!ele) {
            return;
        }

        const option = {allowTaint: true, useCORS: true};
        return html2canvas(ele, option).then((canvas) => {
            if (canvas) {
                return canvas.toDataURL('image/png');
            }
            return null;
        }).catch((res) => {
            console.log(res);
            return res;
        });
    }
}

Recebo o seguinte erro: "ERROR TypeError: html2canvas não é uma função" na seguinte chamada de função do serviço:

return html2canvas(ele, option).then((canvas) => {
    if (canvas) {
        return canvas.toDataURL('image/png');
    }
    return null;
})

Plano provisório de Yupeng em iônico 4

  • index.html
<body>
  <div id="html2canvas"></div>
  <app-root></app-root>
</body>
  • xxx.ts
const element = document.getElementById('html2canvas');
const targetElement = document.getElementById('target').cloneNode(true);
element.appendChild(targetElement);
this.html2canvas.html2canvas(element.firstChild).then((img) => {
    this.img = img;
    element.firstChild.remove();
}).catch((res) => {
    console.log(res);
});
  • Html2canvasService.service.ts
import {Injectable} from '@angular/core';
import {AlertService} from './alert.service';

declare let html2canvas;

@Injectable()
export class Html2canvasService {
    constructor(private alert: AlertService) {

    }

    public html2canvas(ele) {

        if (!ele) {
            return;
        }

        const option = {allowTaint: true, useCORS: true};
        return html2canvas(ele, option).then((canvas) => {
            if (canvas) {
                return canvas.toDataURL('image/png');
            }
            return null;
        }).catch((res) => {
            console.log(res);
            return res;
        });
    }
}

Isso funciona muito bem. Muito obrigado pela solução. Com elementos nativos iônicos (como texto de íon, ícone de íon dentro do elemento a ser copiado), isso não está funcionando. Mas mudei meus elementos iônicos para html. Agora está funcionando perfeitamente.

Esta página foi útil?
0 / 5 - 0 avaliações