diff --git a/demo/demo13.js b/demo/demo13.js index b68348b1c8..6ce1ddd04e 100644 --- a/demo/demo13.js +++ b/demo/demo13.js @@ -11,6 +11,7 @@ paragraph.addRun(dateText); doc.addParagraph(paragraph); var exporter = new docx.LocalPacker(doc); -exporter.packPdf('My Document'); +exporter.packPdf('My Document').then(() => { + console.log('Document created successfully at project root!'); +}); -console.log('Document created successfully at project root!'); diff --git a/src/export/packer/local.ts b/src/export/packer/local.ts index 1ebf8787ec..27bba0ae69 100644 --- a/src/export/packer/local.ts +++ b/src/export/packer/local.ts @@ -19,7 +19,9 @@ export class LocalPacker implements IPacker { public async pack(filePath: string): Promise { filePath = filePath.replace(/.docx$/, ""); - const zipData = await this.packer.compile().generateAsync({ type: "base64" }) as string; + const zip = await this.packer.compile(); + const zipData = await zip.generateAsync({ type: "base64" }) as string; + await this.writeToFile(`${filePath}.docx`, zipData); } @@ -29,7 +31,8 @@ export class LocalPacker implements IPacker { const fileName = path.basename(filePath, path.extname(filePath)); const tempPath = path.join(os.tmpdir(), `${fileName}.docx`); - const zipData = await this.packer.compile().generateAsync({ type: "base64" }) as string; + const zip = await this.packer.compile(); + const zipData = await zip.generateAsync({ type: "base64" }) as string; await this.writeToFile(tempPath, zipData); const text = await this.pdfConverter.convert(tempPath); diff --git a/src/export/packer/next-compiler.ts b/src/export/packer/next-compiler.ts index baecd72ae7..b8ddaf2b82 100644 --- a/src/export/packer/next-compiler.ts +++ b/src/export/packer/next-compiler.ts @@ -1,3 +1,4 @@ +import * as fs from "fs"; import * as JSZip from "jszip"; import * as xml from "xml"; @@ -31,7 +32,7 @@ export class Compiler { this.formatter = new Formatter(); } - public compile(): JSZip { + public async compile(): Promise { const zip = new JSZip(); const xmlifiedFileMapping = this.xmlifyFile(this.file); @@ -46,13 +47,10 @@ export class Compiler { zip.file(xmlifiedFile.path, xmlifiedFile.data); } - // for (const data of file.Media.array) { - // this.archive.append(data.stream, { - // name: `word/media/${data.fileName}`, - // }); - - // zip.file(`word/media/${data.fileName}`, ) - // } + for (const data of this.file.Media.array) { + const mediaData = await this.readFile(data.path); + zip.file(`word/media/${data.fileName}`, mediaData); + } return zip; } @@ -114,4 +112,17 @@ export class Compiler { }, }; } + + private readFile(path: string): Promise { + return new Promise((resolve, reject) => { + fs.readFile(path, (err, data) => { + if (err) { + reject(); + return; + } + + resolve(data); + }); + }); + } }