如何将编辑器内容导出为图像

How to export editor content as image

我正在使用 ngx-quill 创建模板设计器,我希望能够将编辑器的内容导出为图像。我可以将内容成功导出为 HTML 和 PDF,但找不到将其导出为图像的方法。

您必须使用 html2canvas,因为 Quill 不提供任何将其内容导出为图像的内置方法。

您唯一需要做的就是在 quill-editor 元素上添加引用:

<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>

并在您的组件中捕获它,然后处理并渲染图像:

  @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

因此对于此内容:

您将获得以下导出图像:

P.S.: 不要忘记添加到 yarn add html2canvasyarn add --dev @types/html2canvas.