首页 > 解决方案 > HTML 到 Docx 的角度

问题描述

我有一个要保存为 .docx 文件的 HTML 片段。目前,我得到了一个扭曲的结果,其中内容没有很好地获取并且没有正确定位。

下面是我的代码库

var html = document.getElementById("demo1").innerHTML;

    var blob = new Blob(['\ufeff', html], {
      type: 'application/msword'
    });

    // Specify link url
    var url = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(html);

    // Specify file name
    // String filename = 'document.doc';

    // Create download link element
    var downloadLink = document.createElement("a");

    document.body.appendChild(downloadLink);

    if (navigator.msSaveOrOpenBlob) {
      navigator.msSaveOrOpenBlob(blob, 'document.doc');
    }
    else {
      // Create a link to the file
      downloadLink.href = url;

      // Setting the file name
      downloadLink.download = 'document.doc';

      //triggering the function
      downloadLink.click();
    }

    document.body.removeChild(downloadLink);
  }


  changePerPageItems(e) {
    this.perPageItems = e.target.value;
  }

有什么需要改变的。或者也赞赏任何新方法。

标签: javascripthtmldocxdoc

解决方案


实现这一点的一种简单方法(根据我)是使用 docx.js

我添加了简单的示例并链接到示例和文档

https://stackblitz.com/edit/angular-afvxtz

https://docx.js.org/#/

TS 文件:

import { Component } from '@angular/core';
import { Packer } from 'docx';
import { saveAs } from 'file-saver/FileSaver';

import { DocumentCreator } from './cv-generator';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';

  public download(): void {
    const documentCreator = new DocumentCreator();
    const doc = documentCreator.create();
    doc.createParagraph("Test heading1, bold and italicized").heading1();
    doc.createParagraph("Some simple content");
    const packer = new Packer();

    packer.toBlob(doc).then(blob => {
      console.log(blob);
      saveAs(blob, "example.docx");
      console.log("Document created successfully");
    });
  }
}

cv-generator.ts 文件:

import { Document, Paragraph, Packer, TextRun } from 'docx';


export class DocumentCreator {
  create() {
    const title = 'EXECUTIVE SUMMARY';
    const document = new Document();
    document.addParagraph(new Paragraph(title).title());
    document.addParagraph(this.createHeading('Exception Overview'));
    return document;
  }
  createHeading(text) {
    return new Paragraph(text).heading1().thematicBreak();
  }
}

HTML:

<button class="em-primary-button" (click)="download()">Download file</button>

学分:阿西夫·卡里姆·贝拉尼


推荐阅读