diff --git a/src/pdfUtils.js b/src/pdfUtils.js index 763a1e6..56cbf6e 100644 --- a/src/pdfUtils.js +++ b/src/pdfUtils.js @@ -2,35 +2,47 @@ * PDF conversion utilities loaded on demand so headless startup * does not require ESM-only pdf-to-img at module load time. */ +import { createRequire } from 'node:module' +import { pathToFileURL } from 'node:url' + +const require = createRequire(import.meta.url) + +// Bare dynamic import() fails in pkg snapshots with "Invalid host defined options". +async function importPackage(name) { + const packagePath = require.resolve(name) + return import(pathToFileURL(packagePath).href) +} + export async function convertPDFToImage(pdfInput, options = {}) { const [{ pdf }, sharp] = await Promise.all([ - import('pdf-to-img'), - import('sharp') + importPackage('pdf-to-img'), + importPackage('sharp') ]) try { - let scale = options.scale || 2 + const { width, height, page_numbers, scale = 2, ...pdfOnlyOptions } = + options const pdfOptions = { scale, - ...options + ...pdfOnlyOptions } const document = await pdf(pdfInput, pdfOptions) const outputImages = [] if ( - options.page_numbers && - Array.isArray(options.page_numbers) && - options.page_numbers.length > 0 + page_numbers && + Array.isArray(page_numbers) && + page_numbers.length > 0 ) { - for (const pageNum of options.page_numbers) { + for (const pageNum of page_numbers) { let image = await document.getPage(pageNum) - if (options.width || options.height) { + if (width || height) { const resizeOptions = {} - if (options.width) resizeOptions.width = options.width - if (options.height) resizeOptions.height = options.height + if (width) resizeOptions.width = width + if (height) resizeOptions.height = height image = await sharp.default(image).resize(resizeOptions).toBuffer() } @@ -40,10 +52,10 @@ export async function convertPDFToImage(pdfInput, options = {}) { for await (const image of document) { let processedImage = image - if (options.width || options.height) { + if (width || height) { const resizeOptions = {} - if (options.width) resizeOptions.width = options.width - if (options.height) resizeOptions.height = options.height + if (width) resizeOptions.width = width + if (height) resizeOptions.height = height processedImage = await sharp.default(image) .resize(resizeOptions) .toBuffer()