HTML2Canvas generating blank image in Ionic4 angular proj. No error in console. Same code generates proper image in plain html/javascript

前端 未结 1 398
被撕碎了的回忆
被撕碎了的回忆 2021-01-06 23:09

I have html2canvas installed and imported in home.page.ts in my Ionic4 angular test project. I have a plain 100px X 100px, yellow background div with a single line of text.

1条回答
  •  北海茫月
    2021-01-06 23:40

    https://www.npmjs.com/package/dom-to->image works better than html2canvas https://www.npmjs.com/package/jspdf ->if you need to save to pdf

    page.ts

    import * as jsPDF from 'jspdf'; 
    import domtoimage from 'dom-to-image';
    
    captureScreen() {
      const div = document.getElementById('pdfContent');
      const divHeight = div.clientHeight;
      const divWidth = div.clientWidth;
      const options = { background: 'white', width: divWidth, height: divHeight };
    
      domtoimage.toPng(div, options).then((imgData) => {
        const doc = new jsPDF('p', 'mm', [divWidth, divHeight]);
        const imgProps = doc.getImageProperties(imgData);
        const pdfWidth = doc.internal.pageSize.getWidth();
        const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
        doc.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
        doc.save('pdfDocument.pdf');
      });
    

    page.html

    
      
    
    
    

    Testing this to pdf

    worked on ionic 5 (see more here image-in-ionic4-angular)

    Note: current version of jsPDF is giving errors. This is npm install jspdf@1.5.3 --save working ok

    You can see the example here of the site:

    and of the generated pdf

    0 讨论(0)
提交回复
热议问题