Files
docx-js/src/export/packer/packer.ts

66 lines
2.0 KiB
TypeScript
Raw Normal View History

import { Stream } from "stream";
import { File } from "@file/file";
2023-06-01 02:05:35 +01:00
import { strFromU8 } from "fflate";
import { Compiler } from "./next-compiler";
/**
* Use blanks to prettify
*/
2022-07-05 05:06:32 +01:00
export enum PrettifyType {
NONE = "",
WITH_2_BLANKS = " ",
WITH_4_BLANKS = " ",
2022-06-19 00:31:36 +01:00
WITH_TAB = "\t",
}
export class Packer {
2022-08-17 18:52:19 +02:00
public static async toString(file: File, prettify?: boolean | PrettifyType): Promise<string> {
2023-06-01 02:05:35 +01:00
const zip = await this.compiler.compile(
file,
prettify === true ? PrettifyType.WITH_2_BLANKS : prettify === false ? undefined : prettify,
);
return strFromU8(zip);
2022-08-17 18:52:19 +02:00
}
2022-07-05 05:06:32 +01:00
public static async toBuffer(file: File, prettify?: boolean | PrettifyType): Promise<Buffer> {
2023-06-01 02:05:35 +01:00
const zip = await this.compiler.compile(
file,
prettify === true ? PrettifyType.WITH_2_BLANKS : prettify === false ? undefined : prettify,
);
return Buffer.from(zip.buffer);
}
2022-07-05 05:06:32 +01:00
public static async toBase64String(file: File, prettify?: boolean | PrettifyType): Promise<string> {
2023-06-01 02:05:35 +01:00
const zip = await this.compiler.compile(
file,
prettify === true ? PrettifyType.WITH_2_BLANKS : prettify === false ? undefined : prettify,
);
2023-06-01 02:05:35 +01:00
return Promise.resolve(strFromU8(zip));
}
2022-07-05 05:06:32 +01:00
public static async toBlob(file: File, prettify?: boolean | PrettifyType): Promise<Blob> {
2023-06-01 02:05:35 +01:00
const zip = await this.compiler.compile(
file,
prettify === true ? PrettifyType.WITH_2_BLANKS : prettify === false ? undefined : prettify,
);
2023-06-01 02:05:35 +01:00
return new Blob([zip.buffer]);
}
2019-08-07 22:12:14 +01:00
2022-09-19 20:48:50 +01:00
public static toStream(file: File, prettify?: boolean | PrettifyType): Stream {
2023-05-01 20:37:39 +01:00
const zip = this.compiler.compile(file, prettify === true ? PrettifyType.WITH_2_BLANKS : prettify === false ? undefined : prettify);
2023-06-01 02:05:35 +01:00
const stream = new Stream();
2023-06-05 00:33:43 +01:00
zip.then((z) => {
stream.emit("data", z);
stream.emit("end");
});
2023-06-01 02:05:35 +01:00
return stream;
}
2019-08-07 22:12:14 +01:00
private static readonly compiler = new Compiler();
}