84 lines
2.9 KiB
TypeScript
Raw Normal View History

import * as PDFJS from 'pdfjs-dist';
2023-11-14 20:22:37 +01:00
import { PDFDocumentProxy as PDFJSDocument } from 'pdfjs-dist/types/src/display/api';
import { PDFDocument as PDFLibDocument } from 'pdf-lib';
import Joi from 'joi';
export class PdfFile {
2023-11-14 20:22:37 +01:00
private representation: Uint8Array | PDFLibDocument | PDFJSDocument;
originalFilename: string;
2023-11-12 16:57:53 +03:00
filename: string;
2023-11-14 20:22:37 +01:00
get uint8Array() : Promise<Uint8Array> {
switch (this.representation.constructor) {
case Uint8Array:
return new Promise((resolve, reject) => {
resolve(this.representation as Uint8Array);
});
case PDFLibDocument:
return (this.representation as PDFLibDocument).save();
case PDFJSDocument:
return (this.representation as PDFJSDocument).getData();
default:
throw Error("unhandeled PDF type");
}
}
set uint8Array(value: Uint8Array) {
this.representation = value;
}
2023-11-14 20:22:37 +01:00
get pdflibDocument() : Promise<PDFLibDocument> {
switch (this.representation.constructor) {
case PDFLibDocument: // PDFLib
return new Promise((resolve, reject) => {
resolve(this.representation as PDFLibDocument);
});
default:
return new Promise(async (resolve, reject) => {
resolve(PDFLibDocument.load(await this.uint8Array, {
updateMetadata: false,
}));
});
}
}
set pdflibDocument(value: PDFLibDocument) {
this.representation = value;
}
2023-11-14 20:22:37 +01:00
get pdfjsDocuemnt() : Promise<PDFJSDocument> {
switch (this.representation.constructor) {
case PDFJSDocument:
return new Promise((resolve, reject) => {
resolve(this.representation as PDFJSDocument);
});
default:
return new Promise(async (resolve, reject) => {
resolve(await PDFJS.getDocument(await this.uint8Array).promise);
});
}
}
2023-11-14 20:22:37 +01:00
set pdfjsDocuemnt(value: PDFJSDocument) {
this.representation = value;
}
constructor(originalFilename: string, representation: Uint8Array | PDFLibDocument | PDFJSDocument, filename?: string) {
this.originalFilename = originalFilename;
this.filename = filename ? filename : originalFilename;
2023-11-14 20:22:37 +01:00
this.representation = representation;
}
2023-11-14 20:22:37 +01:00
static fromMulterFile(value: Express.Multer.File): PdfFile {
return new PdfFile(value.originalname, value.buffer as Uint8Array)
}
2023-11-14 20:22:37 +01:00
static fromMulterFiles(values: Express.Multer.File[]): PdfFile[] {
return values.map(v => PdfFile.fromMulterFile(v));
}
}
2023-11-14 20:22:37 +01:00
export const PdfFileSchema = Joi.any().custom((value, helpers) => {
if (!(value instanceof PdfFile)) {
throw new Error('value is not a PdfFile');
}
return value;
2023-11-14 20:22:37 +01:00
}, "PdfFile validation");