Files
docx-js/src/patcher/from-docx.ts

75 lines
2.0 KiB
TypeScript
Raw Normal View History

2023-02-08 03:18:11 +00:00
import * as JSZip from "jszip";
2023-02-18 20:36:24 +00:00
import { Element, js2xml } from "xml-js";
2023-02-25 19:33:12 +00:00
import { ParagraphChild } from "@file/paragraph";
import { FileChild } from "@file/file-child";
2023-02-16 20:17:48 +00:00
import { replacer } from "./replacer";
2023-02-17 10:38:03 +00:00
import { findLocationOfText } from "./traverser";
2023-02-18 20:36:24 +00:00
import { toJson } from "./util";
2023-02-08 03:18:11 +00:00
// eslint-disable-next-line functional/prefer-readonly-type
type InputDataType = Buffer | string | number[] | Uint8Array | ArrayBuffer | Blob | NodeJS.ReadableStream;
2023-02-25 19:33:12 +00:00
export enum PatchType {
DOCUMENT = "file",
PARAGRAPH = "paragraph",
2023-02-17 10:38:03 +00:00
}
2023-02-25 19:33:12 +00:00
type ParagraphPatch = {
readonly type: PatchType.PARAGRAPH;
readonly children: readonly ParagraphChild[];
};
type FilePatch = {
readonly type: PatchType.DOCUMENT;
readonly children: readonly FileChild[];
};
export type IPatch = {
readonly text: string;
} & (ParagraphPatch | FilePatch);
2023-02-17 10:38:03 +00:00
export interface PatchDocumentOptions {
readonly patches: readonly IPatch[];
2023-02-16 20:17:48 +00:00
}
export const patchDocument = async (data: InputDataType, options: PatchDocumentOptions): Promise<Buffer> => {
2023-02-08 03:18:11 +00:00
const zipContent = await JSZip.loadAsync(data);
2023-02-17 10:38:03 +00:00
const map = new Map<string, Element>();
2023-02-08 03:18:11 +00:00
for (const [key, value] of Object.entries(zipContent.files)) {
const json = toJson(await value.async("text"));
if (key.startsWith("word/")) {
2023-02-17 10:38:03 +00:00
for (const patch of options.patches) {
2023-02-18 20:36:24 +00:00
const renderedParagraphs = findLocationOfText(json, patch.text);
replacer(json, patch, renderedParagraphs);
2023-02-17 10:38:03 +00:00
}
2023-02-16 20:17:48 +00:00
}
2023-02-08 03:18:11 +00:00
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;
};
2023-02-17 10:38:03 +00:00
const toXml = (jsonObj: Element): string => {
2023-02-08 03:18:11 +00:00
const output = js2xml(jsonObj);
return output;
};