work on docx patcher

This commit is contained in:
Dolan Miu
2023-02-16 20:17:48 +00:00
parent ffd998cbf5
commit c206d23480
5 changed files with 31 additions and 3 deletions

View File

@ -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);
});

Binary file not shown.

Binary file not shown.

View File

@ -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<Buffer> => {
export interface PatchDocumentOptions {
readonly children: any[];
}
export const patchDocument = async (data: InputDataType, options: PatchDocumentOptions): Promise<Buffer> => {
const zipContent = await JSZip.loadAsync(data);
const map = new Map<string, ElementCompact>();
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);
}

15
src/templater/replacer.ts Normal file
View File

@ -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;
};