Search code examples
angularquillngx-quill

How to export editor content as image


I am using ngx-quill to create a template designer and I want to be able to export the content of the editor as an image. I can successfully export the content as HTML and PDF but couldn't find a way to export it as an image.


Solution

  • You have to use html2canvas, since Quill doesn't provide any built-in way to export its content as an image.

    The only thing you need to do is to add a reference on your quill-editor element:

    <quill-editor #screen 
                  format="html" 
                  [modules]="quillConfig" 
                  placeholder="Some text...">
    </quill-editor>
    
    <div class="btn btn-primary" 
         (click)="downloadImage()">DL</div>
    
    <div id="download">
      <img #canvas>
      <a #downloadLink></a>
    </div>
    

    And catch it in your component, then process and render the image:

      @ViewChild('screen') screen: ElementRef;
      @ViewChild('canvas') canvas: ElementRef;
      @ViewChild('downloadLink') downloadLink: ElementRef;
    
      downloadImage(){
        html2canvas(document.querySelector('.ql-editor')).then(canvas => {
          this.canvas.nativeElement.src = canvas.toDataURL();
          this.downloadLink.nativeElement.href = canvas.toDataURL('image/png');
          this.downloadLink.nativeElement.download = 'marble-diagram.png';
          this.downloadLink.nativeElement.click();
        });
      }
    

    Here is a working example with html2canvas and ngx-quill

    So for this content:

    editor view

    You'll get the following exported image:

    the exported image

    P.S.: Don't forget to add to yarn add html2canvas and yarn add --dev @types/html2canvas.