diff --git a/demo/85-template-document.ts b/demo/85-template-document.ts index d219170491..43e345b0b0 100644 --- a/demo/85-template-document.ts +++ b/demo/85-template-document.ts @@ -1,8 +1,10 @@ // Simple template example // Import from 'docx' rather than '../build' if you install from npm import * as fs from "fs"; -import { fromDocx } from "../build"; +import { Paragraph, patchDocument, TextRun } from "../build"; -fromDocx(fs.readFileSync("demo/template.docx")).then((doc) => { +patchDocument(fs.readFileSync("demo/assets/simple-template.docx"), { + children: [new Paragraph("ff"), new TextRun("fgf")], +}).then((doc) => { fs.writeFileSync("My Document.docx", doc); }); diff --git a/demo/assets/simple-template.docx b/demo/assets/simple-template.docx new file mode 100644 index 0000000000..c9afe4f66d Binary files /dev/null and b/demo/assets/simple-template.docx differ diff --git a/demo/template.docx b/demo/template.docx deleted file mode 100644 index fd05df5947..0000000000 Binary files a/demo/template.docx and /dev/null differ diff --git a/src/templater/from-docx.ts b/src/templater/from-docx.ts index cec1a84877..b17bbf1f90 100644 --- a/src/templater/from-docx.ts +++ b/src/templater/from-docx.ts @@ -1,16 +1,27 @@ import * as JSZip from "jszip"; import { xml2js, ElementCompact, js2xml } from "xml-js"; +import { replacer } from "./replacer"; // 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 => { +export interface PatchDocumentOptions { + readonly children: any[]; +} + +export const patchDocument = async (data: InputDataType, options: PatchDocumentOptions): Promise => { const zipContent = await JSZip.loadAsync(data); const map = new Map(); + console.log(options); for (const [key, value] of Object.entries(zipContent.files)) { const json = toJson(await value.async("text")); + if (key === "word/document.xml") { + console.log(json); + replacer(json, options); + } + map.set(key, json); } diff --git a/src/templater/replacer.ts b/src/templater/replacer.ts new file mode 100644 index 0000000000..830c0a5054 --- /dev/null +++ b/src/templater/replacer.ts @@ -0,0 +1,15 @@ +import { Paragraph, TextRun } from "@file/paragraph"; +import { ElementCompact } from "xml-js"; +import { PatchDocumentOptions } from "./from-docx"; + +export const replacer = (json: ElementCompact, options: PatchDocumentOptions): ElementCompact => { + for (const child of options.children) { + if (child instanceof Paragraph) { + console.log("is para"); + } else if (child instanceof TextRun) { + console.log("is text"); + } + } + + return json; +};