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";
|
2017-09-30 18:15:33 +01:00
|
|
|
|
2017-03-08 21:54:52 +00:00
|
|
|
import { Document } from "../../docx/document";
|
2017-03-26 20:57:43 +01:00
|
|
|
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-12-06 01:03:14 +00:00
|
|
|
import { Compiler } from "./compiler";
|
|
|
|
import { IPacker } from "./packer";
|
2017-12-05 00:16:21 +00:00
|
|
|
import { PdfConvertWrapper } from "./pdf-convert-wrapper";
|
2017-03-08 21:54:52 +00:00
|
|
|
|
2017-12-06 01:03:14 +00:00
|
|
|
export class LocalPacker implements IPacker {
|
2016-05-26 15:08:34 +01:00
|
|
|
private stream: fs.WriteStream;
|
2017-12-05 00:16:21 +00:00
|
|
|
private pdfConverter: PdfConvertWrapper;
|
2017-12-06 01:03:14 +00:00
|
|
|
private packer: Compiler;
|
2016-05-26 15:08:34 +01:00
|
|
|
|
2017-03-26 20:57:43 +01:00
|
|
|
constructor(document: Document, styles?: Styles, properties?: Properties, numbering?: Numbering, media?: Media) {
|
2017-12-05 00:16:21 +00:00
|
|
|
this.pdfConverter = new PdfConvertWrapper();
|
2017-12-06 01:03:14 +00:00
|
|
|
this.packer = new Compiler(document, styles, properties, numbering, media);
|
2016-03-31 18:03:16 +01:00
|
|
|
}
|
2016-05-26 15:08:34 +01:00
|
|
|
|
2017-12-06 01:32:57 +00:00
|
|
|
public async pack(filePath: string): Promise<void> {
|
2017-12-05 00:16:21 +00:00
|
|
|
filePath = filePath.replace(/.docx$/, "");
|
|
|
|
|
|
|
|
this.stream = fs.createWriteStream(`${filePath}.docx`);
|
2017-12-06 01:32:57 +00:00
|
|
|
await this.packer.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);
|
2017-12-06 01:03:14 +00:00
|
|
|
await this.packer.compile(this.stream);
|
2017-12-05 00:16:21 +00:00
|
|
|
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
|
|
|
}
|