UNPKG

mindee

Version:

Mindee Client Library for Node.js

102 lines (101 loc) 3.69 kB
import { Buffer } from "node:buffer"; import { MindeeError } from "../errors/index.js"; import { writeFileSync } from "node:fs"; import { writeFile } from "fs/promises"; import path from "node:path"; import { BufferInput, MIMETYPES } from "../input/index.js"; import { logger } from "../logger.js"; import { loadOptionalDependency } from "../dependency/index.js"; /** * Generic class for image extraction. */ export class ExtractedImage { constructor(buffer, fileName, pageId, elementId) { this.buffer = Buffer.from(buffer); this.filename = fileName; this.pageId = pageId; this.elementId = elementId; } /** * Saves the document to a file. * * @param outputPath Path to save the file to. */ async saveToFileAsync(outputPath) { const fileExt = path.extname(outputPath).toLowerCase(); if (!MIMETYPES.has(fileExt)) { throw new MindeeError(`Unsupported file extension: ${fileExt}`); } try { let outputBuffer = this.buffer; if (fileExt !== ".pdf") { const popplerImport = await loadOptionalDependency("node-poppler", "Image Processing"); const poppler = popplerImport.default || popplerImport; const popplerInstance = new poppler.Poppler(); const options = { firstPageToConvert: 1, lastPageToConvert: 1, singleFile: true, }; if (fileExt === ".png") { options.pngFile = true; } else if (fileExt === ".jpg" || fileExt === ".jpeg") { options.jpegFile = true; } else if (fileExt === ".tiff" || fileExt === ".tif") { options.tiffFile = true; } const result = await popplerInstance.pdfToCairo(this.buffer, undefined, options); outputBuffer = Buffer.from(result, "latin1"); } await writeFile(path.resolve(outputPath), outputBuffer); 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; } } } /** * Attempts to saves the document to a file synchronously. * Throws an error if the file extension is not supported or if the file could not be saved to disk for some reason. * * @param outputPath Path to save the file to. */ saveToFile(outputPath) { const fileExt = path.extname(outputPath).toLowerCase(); if (fileExt !== ".pdf") { throw new MindeeError(`Unsupported file extension: ${fileExt}. For image formats, use saveToFileAsync() instead.`); } else { 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, }); } }