如何解决HTML 到 Docx 的角度
我有一个 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
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。