mindee
Version:
Mindee Client Library for Node.js
67 lines (66 loc) • 2.01 kB
JavaScript
import path from "node:path";
import { BufferInput, MIMETYPES } from "../input/index.js";
import { MindeeError } from "../errors/index.js";
import { writeFile } from "fs/promises";
import { logger } from "../logger.js";
import { writeFileSync } from "node:fs";
export class ExtractedPdf {
constructor(pdfData, filename, pageIndexes) {
this.buffer = pdfData;
this.filename = filename;
this.pageCount = pageIndexes.length;
this.pageIndexes = pageIndexes;
}
/**
* Saves the document to a file.
*
* @param outputPath Path to save the file to.
*/
async saveToFileAsync(outputPath) {
const fileExt = path.extname(outputPath).toLowerCase();
if (fileExt !== ".pdf" && !MIMETYPES.has(fileExt)) {
outputPath += ".pdf";
}
try {
await writeFile(path.resolve(outputPath), this.buffer);
logger.info(`File saved successfully to ${path.resolve(outputPath)}.`);
}
catch (e) {
if (e instanceof TypeError) {
throw new MindeeError("Invalid path/filename provided.");
}
else {
throw e;
}
}
}
/**
* Saves the document to a file synchronously.
* @param outputPath
*/
saveToFile(outputPath) {
try {
writeFileSync(path.resolve(outputPath), this.buffer);
logger.info(`File saved successfully to ${path.resolve(outputPath)}.`);
}
catch (e) {
if (e instanceof TypeError) {
throw new MindeeError("Invalid path/filename provided.");
}
else {
throw e;
}
}
}
/**
* Return the file as a Mindee-compatible BufferInput source.
*
* @returns A BufferInput source.
*/
asInputSource() {
return new BufferInput({
buffer: this.buffer,
filename: this.filename,
});
}
}