Simple import and export of document
This commit is contained in:
8
demo/85-template-document.ts
Normal file
8
demo/85-template-document.ts
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
// Simple template example
|
||||||
|
// Import from 'docx' rather than '../build' if you install from npm
|
||||||
|
import * as fs from "fs";
|
||||||
|
import { fromDocx } from "../build";
|
||||||
|
|
||||||
|
fromDocx(fs.readFileSync("demo/template.docx")).then((doc) => {
|
||||||
|
fs.writeFileSync("My Document.docx", doc);
|
||||||
|
});
|
BIN
demo/template.docx
Normal file
BIN
demo/template.docx
Normal file
Binary file not shown.
@ -5,3 +5,4 @@ export * from "./file";
|
|||||||
export * from "./export";
|
export * from "./export";
|
||||||
export * from "./import-dotx";
|
export * from "./import-dotx";
|
||||||
export * from "./util";
|
export * from "./util";
|
||||||
|
export * from "./templater";
|
||||||
|
42
src/templater/from-docx.ts
Normal file
42
src/templater/from-docx.ts
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
import * as JSZip from "jszip";
|
||||||
|
import { xml2js, ElementCompact, js2xml } from "xml-js";
|
||||||
|
|
||||||
|
// eslint-disable-next-line functional/prefer-readonly-type
|
||||||
|
type InputDataType = Buffer | string | number[] | Uint8Array | ArrayBuffer | Blob | NodeJS.ReadableStream;
|
||||||
|
|
||||||
|
export const fromDocx = async (data: InputDataType): Promise<Buffer> => {
|
||||||
|
const zipContent = await JSZip.loadAsync(data);
|
||||||
|
|
||||||
|
const map = new Map<string, ElementCompact>();
|
||||||
|
|
||||||
|
for (const [key, value] of Object.entries(zipContent.files)) {
|
||||||
|
const json = toJson(await value.async("text"));
|
||||||
|
map.set(key, json);
|
||||||
|
}
|
||||||
|
|
||||||
|
const zip = new JSZip();
|
||||||
|
|
||||||
|
for (const [key, value] of map) {
|
||||||
|
const output = toXml(value);
|
||||||
|
|
||||||
|
zip.file(key, output);
|
||||||
|
}
|
||||||
|
|
||||||
|
const zipData = await zip.generateAsync({
|
||||||
|
type: "nodebuffer",
|
||||||
|
mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||||
|
compression: "DEFLATE",
|
||||||
|
});
|
||||||
|
|
||||||
|
return zipData;
|
||||||
|
};
|
||||||
|
|
||||||
|
const toJson = (xmlData: string): ElementCompact => {
|
||||||
|
const xmlObj = xml2js(xmlData, { compact: false }) as ElementCompact;
|
||||||
|
return xmlObj;
|
||||||
|
};
|
||||||
|
|
||||||
|
const toXml = (jsonObj: ElementCompact): string => {
|
||||||
|
const output = js2xml(jsonObj);
|
||||||
|
return output;
|
||||||
|
};
|
1
src/templater/index.ts
Normal file
1
src/templater/index.ts
Normal file
@ -0,0 +1 @@
|
|||||||
|
export * from "./from-docx";
|
Reference in New Issue
Block a user