From 5db2503e7b119afb3f186f44e6465e4947aa01ab Mon Sep 17 00:00:00 2001 From: Dolan Date: Sat, 25 Mar 2017 21:50:33 +0000 Subject: [PATCH] added media class and packer to handle it --- ts/export/packer/packer.ts | 16 ++++++++++++++- ts/media/index.ts | 40 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 ts/media/index.ts diff --git a/ts/export/packer/packer.ts b/ts/export/packer/packer.ts index e45d1b45bd..8dc3bf30a8 100644 --- a/ts/export/packer/packer.ts +++ b/ts/export/packer/packer.ts @@ -2,6 +2,7 @@ import * as archiver from "archiver"; import * as path from "path"; import * as xml from "xml"; import { Document } from "../../docx"; +import { Media } from "../../media"; import { Numbering } from "../../numbering"; import { Properties } from "../../properties"; import { Styles } from "../../styles"; @@ -24,6 +25,7 @@ export abstract class Packer { lastModifiedBy: "Un-named", }), private numbering: Numbering = new Numbering(), + private media: Media = new Media(), ) { this.formatter = new Formatter(); this.archive = archiver.create("zip", {}); @@ -54,8 +56,14 @@ export abstract class Packer { const xmlDocument = xml(this.formatter.format(this.document)); const xmlStyles = xml(this.formatter.format(this.style)); - const xmlProperties = xml(this.formatter.format(this.properties), { declaration: { standalone: "yes", encoding: "UTF-8" } }); + const xmlProperties = xml(this.formatter.format(this.properties), { + declaration: { + standalone: "yes", + encoding: "UTF-8", + }, + }); const xmlNumbering = xml(this.formatter.format(this.numbering)); + this.archive.append(xmlDocument, { name: "word/document.xml", }); @@ -72,6 +80,12 @@ export abstract class Packer { name: "word/numbering.xml", }); + for (const data of this.media.array) { + this.archive.append(data.stream, { + name: `media/${data.fileName}`, + }); + } + this.archive.finalize(); } } diff --git a/ts/media/index.ts b/ts/media/index.ts new file mode 100644 index 0000000000..f07ad69de5 --- /dev/null +++ b/ts/media/index.ts @@ -0,0 +1,40 @@ +import * as fs from "fs"; +import * as path from "path"; + +interface IData { + referenceId: number; + stream: fs.ReadStream; + path: string; + fileName: string; +} + +export class Media { + private map: Map; + + constructor() { + this.map = new Map(); + } + + public getMedia(key: string): IData | undefined { + return this.map.get(key); + } + + public addMedia(key: string, filePath: string): void { + this.map.set(key, { + referenceId: this.map.values.length, + stream: fs.createReadStream(filePath), + path: filePath, + fileName: path.basename(filePath), + }); + } + + public get array(): IData[] { + const array = new Array(); + + this.map.forEach((data) => { + array.push(data); + }); + + return array; + } +}