You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
On nodejs, try to save as PNGs the pages of a pdf like the one provided
What is the expected behavior?
The saved PNGs should contain all the elements in the related page. Instead, images are missing. If the page is a single big image, the PNG is blank.
What went wrong?
Saved PNGs do not contain images. No errors or warning are thrown.
Link to a viewer
No response
Additional context
here is my code:
/** * Converts a PDF file to a series of images. * @param {Object} file - The file object containing input path and name * @param {string} destinationFolder - The folder where the converted images will be saved * @param {string} [outputFormat='avif'] - The desired output format (e.g., 'avif', 'webp') * @param {number} [resizeWidth] - Optional width to resize the images (only if original is larger) * @param {boolean} shouldRetainSubdirs - Whether to retain the subdirectory structure * @param {Window} mainWindow - The main window object for progress updates * @param {AbortSignal} signal - Signal for aborting the conversion * @returns {Promise<Object>} - A promise that resolves to an object with the output path */exportconstconvertPdfToImages=async(file,destinationFolder,outputFormat='avif',resizeWidth,shouldRetainSubdirs,mainWindow,signal)=>{// Create output directory if it doesn't existif(!fs.existsSync(destinationFolder)){fs.mkdirSync(destinationFolder,{recursive: true});}constpdfFilename=`${path.parse(file.name).name}`;constoutputDir=path.join(destinationFolder,shouldRetainSubdirs ? file.relativePath : '',pdfFilename)if(!fs.existsSync(outputDir)){fs.mkdirSync(outputDir,{recursive: true});}constcreatedFiles=[];// Track files created during conversiontry{// Load the PDF documentconstdata=newUint8Array(fs.readFileSync(file.inputPath));constloadingTask=pdfjsLib.getDocument({
data,useSystemFonts: true,maxImageSize: -1,enableXfa: true,background: 'white'});constpdfDocument=awaitloadingTask.promise;constnumPages=pdfDocument.numPages;console.log(`PDF loaded. Number of pages: ${numPages}`);letprogress=0;// Process each pagefor(letpageNumber=1;pageNumber<=numPages;pageNumber++){if(signal?.aborted){thrownewError('Conversion stopped by user');}constpage=awaitpdfDocument.getPage(pageNumber);constannotations=awaitpage.getAnnotations();console.log("annotations",annotations)constviewport=page.getViewport({scale: 3.0});// Higher scale for better quality// Create canvas and contextconstcanvasFactory=pdfDocument.canvasFactory;constcanvas=awaitcanvasFactory.create(viewport.width,viewport.height);// Render PDF page to canvasconstrenderContext={canvasContext: canvas.context,viewport: viewport,};constrenderTask=page.render(renderContext,);awaitrenderTask.promise;// Convert canvas to bufferletimageBuffer=awaitcanvas.canvas.encode("png");// Process with Sharp for resizing and format conversionletsharpInstance=sharp(imageBuffer);if(resizeWidth){sharpInstance=sharpInstance.resize(resizeWidth,null,{withoutEnlargement: true});}constoutputPath=path.join(outputDir,`page-${String(pageNumber).padStart(3,'0')}.${outputFormat}`);createdFiles.push(outputPath);// Track this file// Convert and save with abort handlingletpipeline=sharpInstance.toFormat(outputFormat);constabortPromise=newPromise((_,reject)=>{signal?.addEventListener('abort',()=>{pipeline.destroy();pipeline=null;reject(newError('Conversion stopped by user'));},{once: true});});awaitPromise.race([pipeline.toFile(outputPath),abortPromise]);page.cleanup();progress=(pageNumber/numPages*100).toFixed(1);mainWindow.webContents.send('onProgress',{type: 'progress',data: {file: file,progress: parseFloat(progress)}});}console.log('Conversion completed successfully!');return{outputPath: destinationFolder};}catch(error){// Give sharp a chance to finish up before cleaning upsetTimeout(()=>{cleanupConversion(outputDir,createdFiles);},100);console.error('Error during conversion:',error);throwerror;}}
Attach (recommended) or Link to PDF file
image-based-pdf-sample.pdf
Web browser and its version
Node.js (electron 31.7.3)
Operating system and its version
Windows 11 x64, MacOs arm64
PDF.js version
4.9.0
Is the bug present in the latest PDF.js version?
Yes
Is a browser extension
No
Steps to reproduce the problem
On nodejs, try to save as PNGs the pages of a pdf like the one provided
What is the expected behavior?
The saved PNGs should contain all the elements in the related page. Instead, images are missing. If the page is a single big image, the PNG is blank.
What went wrong?
Saved PNGs do not contain images. No errors or warning are thrown.
Link to a viewer
No response
Additional context
here is my code:
and my package.json:
could this be related to the recent canvas library change?
The text was updated successfully, but these errors were encountered: