javascript - 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;
}
有什么需要改变的。或者也赞赏任何新方法。
解决方案
实现这一点的一种简单方法(根据我)是使用 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>
学分:阿西夫·卡里姆·贝拉尼
推荐阅读
- gdb - GDB:在调用函数之前显示函数的参数
- sql - SQL数据库中如何统计每个用户ID的出现次数
- substrate - 基板官方安装指南
- python - Flask ImportError:无法在heroku上导入名称'app'
- python - [Errno 2]:即使文件存在,也没有此类文件或目录错误
- javascript - 当我尝试向其添加 ++ 运算符时,它在 JS 中不起作用
- clojure - 如何避免 Clojure 中嵌套的“for”函数?
- typescript - 为什么这里有“隐式任何返回类型”错误?
- r - 用 ggplot2 绘制环境函数
- python - 如何根据python脚本中的标签值($VARIABLE)“获取”某些环境变量