簡體   English   中英

HTML 到 Docx 的角度

[英]HTML to Docx in angular

我有一個 HTML 片段,我想將其另存為 .docx 文件。 目前,我得到了一個扭曲的結果,其中內容沒有很好地獲取並且沒有正確定位。

下面是我的代碼庫

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

有什么需要改變的。 或者任何新方法也受到贊賞。

實現這一點的一種簡單方法(根據我的說法)是使用 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>

圖片來源:Asif Karim Bherani

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM