Files
docx-js/src/export/packer/compiler.ts

81 lines
2.2 KiB
TypeScript
Raw Normal View History

2017-12-06 01:03:14 +00:00
import * as archiver from "archiver";
import * as express from "express";
import * as fs from "fs";
import * as path from "path";
import * as xml from "xml";
import { File } from "file";
2017-12-06 01:03:14 +00:00
import { Formatter } from "../formatter";
const TEMPLATE_PATH = path.resolve(__dirname, "../../../template");
export class Compiler {
protected archive: archiver.Archiver;
private formatter: Formatter;
2017-12-15 02:15:44 +00:00
constructor(private file: File) {
2017-12-06 01:03:14 +00:00
this.formatter = new Formatter();
this.archive = archiver.create("zip", {});
this.archive.on("error", (err) => {
throw err;
});
}
public async compile(output: fs.WriteStream | express.Response): Promise<void> {
this.archive.pipe(output);
this.archive.glob("**", {
cwd: TEMPLATE_PATH,
});
this.archive.glob("**/.rels", {
cwd: TEMPLATE_PATH,
});
2018-01-16 00:43:00 +00:00
const xmlDocument = xml(this.formatter.format(this.file.Document), true);
2017-12-15 02:15:44 +00:00
const xmlStyles = xml(this.formatter.format(this.file.Styles));
const xmlProperties = xml(this.formatter.format(this.file.Properties), {
2017-12-06 01:03:14 +00:00
declaration: {
standalone: "yes",
encoding: "UTF-8",
},
});
2017-12-15 02:15:44 +00:00
const xmlNumbering = xml(this.formatter.format(this.file.Numbering));
2018-01-10 00:29:17 +00:00
const xmlRelationships = xml(this.formatter.format(this.file.Relationships));
2017-12-06 01:03:14 +00:00
this.archive.append(xmlDocument, {
name: "word/document.xml",
});
this.archive.append(xmlStyles, {
name: "word/styles.xml",
});
this.archive.append(xmlProperties, {
name: "docProps/core.xml",
});
this.archive.append(xmlNumbering, {
name: "word/numbering.xml",
});
2018-01-10 00:29:17 +00:00
this.archive.append(xmlRelationships, {
name: "word/_rels/document.xml.rels",
});
2017-12-15 02:15:44 +00:00
for (const data of this.file.Media.array) {
2017-12-06 01:03:14 +00:00
this.archive.append(data.stream, {
2018-01-22 00:53:22 +00:00
name: `word/media/${data.fileName}`,
2017-12-06 01:03:14 +00:00
});
}
this.archive.finalize();
return new Promise<void>((resolve) => {
output.on("close", () => {
resolve();
});
});
}
}