Files
docx-js/ts/export/packer/local.ts

54 lines
1.9 KiB
TypeScript
Raw Normal View History

2016-05-26 15:08:34 +01:00
import * as fs from "fs";
2017-12-05 00:16:21 +00:00
import * as os from "os";
import * as path from "path";
import * as util from "util";
2017-09-30 18:15:33 +01:00
2017-03-08 21:54:52 +00:00
import { Document } from "../../docx/document";
import { Media } from "../../media";
2017-03-08 21:54:52 +00:00
import { Numbering } from "../../numbering";
import { Properties } from "../../properties";
2017-03-09 23:32:52 +00:00
import { Styles } from "../../styles";
2017-09-30 18:15:33 +01:00
import { IPackOptions } from "./pack-options";
2017-03-08 21:54:52 +00:00
import { Packer } from "./packer";
2017-12-05 00:16:21 +00:00
import { PdfConvertWrapper } from "./pdf-convert-wrapper";
2017-03-08 21:54:52 +00:00
2016-03-31 18:03:16 +01:00
export class LocalPacker extends Packer {
2016-05-26 15:08:34 +01:00
private stream: fs.WriteStream;
2017-12-05 00:16:21 +00:00
private pdfConverter: PdfConvertWrapper;
2016-05-26 15:08:34 +01:00
constructor(document: Document, styles?: Styles, properties?: Properties, numbering?: Numbering, media?: Media) {
super(document, styles, properties, numbering, media);
2017-12-05 00:16:21 +00:00
this.pdfConverter = new PdfConvertWrapper();
2016-03-31 18:03:16 +01:00
}
2016-05-26 15:08:34 +01:00
2017-12-05 00:16:21 +00:00
public pack(filePath: string): void {
filePath = filePath.replace(/.docx$/, "");
this.stream = fs.createWriteStream(`${filePath}.docx`);
super.compile(this.stream);
2016-05-26 15:08:34 +01:00
}
2017-12-05 00:16:21 +00:00
public async packPdf(filePath: string): Promise<void> {
filePath = filePath.replace(/.pdf$/, "");
const fileName = path.basename(filePath, path.extname(filePath));
const tempPath = path.join(os.tmpdir(), `${fileName}.docx`);
this.stream = fs.createWriteStream(tempPath);
await super.compile(this.stream);
const text = await this.pdfConverter.convert(tempPath);
// const writeFile = util.promisify(fs.writeFile); --use this in future, in 3 years time. Only in node 8
// return writeFile(`${filePath}.pdf`, text);
return new Promise<void>((resolve, reject) => {
fs.writeFile(`${filePath}.pdf`, text, (err) => {
if (err) {
reject(err);
return;
}
resolve();
});
});
}
2017-03-08 21:54:52 +00:00
}