added media class and packer to handle it

This commit is contained in:
Dolan
2017-03-25 21:50:33 +00:00
parent 30b21217a9
commit 5db2503e7b
2 changed files with 55 additions and 1 deletions

View File

@ -2,6 +2,7 @@ import * as archiver from "archiver";
import * as path from "path"; import * as path from "path";
import * as xml from "xml"; import * as xml from "xml";
import { Document } from "../../docx"; import { Document } from "../../docx";
import { Media } from "../../media";
import { Numbering } from "../../numbering"; import { Numbering } from "../../numbering";
import { Properties } from "../../properties"; import { Properties } from "../../properties";
import { Styles } from "../../styles"; import { Styles } from "../../styles";
@ -24,6 +25,7 @@ export abstract class Packer {
lastModifiedBy: "Un-named", lastModifiedBy: "Un-named",
}), }),
private numbering: Numbering = new Numbering(), private numbering: Numbering = new Numbering(),
private media: Media = new Media(),
) { ) {
this.formatter = new Formatter(); this.formatter = new Formatter();
this.archive = archiver.create("zip", {}); this.archive = archiver.create("zip", {});
@ -54,8 +56,14 @@ export abstract class Packer {
const xmlDocument = xml(this.formatter.format(this.document)); const xmlDocument = xml(this.formatter.format(this.document));
const xmlStyles = xml(this.formatter.format(this.style)); 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)); const xmlNumbering = xml(this.formatter.format(this.numbering));
this.archive.append(xmlDocument, { this.archive.append(xmlDocument, {
name: "word/document.xml", name: "word/document.xml",
}); });
@ -72,6 +80,12 @@ export abstract class Packer {
name: "word/numbering.xml", name: "word/numbering.xml",
}); });
for (const data of this.media.array) {
this.archive.append(data.stream, {
name: `media/${data.fileName}`,
});
}
this.archive.finalize(); this.archive.finalize();
} }
} }

40
ts/media/index.ts Normal file
View File

@ -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<string, IData>;
constructor() {
this.map = new Map<string, IData>();
}
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<IData>();
this.map.forEach((data) => {
array.push(data);
});
return array;
}
}