/** * PDF conversion utilities loaded on demand so headless startup * does not require ESM-only pdf-to-img at module load time. */ export async function convertPDFToImage(pdfInput, options = {}) { const [{ pdf }, sharp] = await Promise.all([ import('pdf-to-img'), import('sharp') ]) try { let scale = options.scale || 2 const pdfOptions = { scale, ...options } const document = await pdf(pdfInput, pdfOptions) const outputImages = [] if ( options.page_numbers && Array.isArray(options.page_numbers) && options.page_numbers.length > 0 ) { for (const pageNum of options.page_numbers) { let image = await document.getPage(pageNum) if (options.width || options.height) { const resizeOptions = {} if (options.width) resizeOptions.width = options.width if (options.height) resizeOptions.height = options.height image = await sharp.default(image).resize(resizeOptions).toBuffer() } outputImages.push(image) } } else { for await (const image of document) { let processedImage = image if (options.width || options.height) { const resizeOptions = {} if (options.width) resizeOptions.width = options.width if (options.height) resizeOptions.height = options.height processedImage = await sharp.default(image) .resize(resizeOptions) .toBuffer() } outputImages.push(processedImage) } } return outputImages } catch (error) { console.error('Error converting PDF to image:', error) throw error } }