DEV Community

Mohamed Shafnas
Mohamed Shafnas

Posted on

PDFToImage PDF Box

Hi, I am working on a project where I want to convert the pdf file pages into png images then I am compressing the images using the imagemin with imageminpngquant plugin. the process is working fine when I am using the following command line code from the node js.

pdfConvert = spawn('java', [
                        '-jar',
                        `${pdfBoxPath}`,
                        'PDFToImage',
                        '-dpi',
                        dpi,
                        '-imageType',
                        'png',
                        '-outputPrefix',
                        `${rawPdfDir}/page-`,
                        `./${pdfFilePath}`,
                    ]);
Enter fullscreen mode Exit fullscreen mode

but when I want to convert only specfic pages I am using the following code and the image is also getting converted but while compressing it is showing cannot decode image for some images.

for (let i = 0; i < requiredPages.length; i++) {
                        // split the page ranges 
                        const range = requiredPages[i].trim().split('-');
                        const startPage = range[0];
                        const endPage = range[1] ? range[1] : range[0];

                        // console.log(`range -> ${range}`);
                        // console.log(`requiredPages -> ${requiredPages[i]}`);

                        pdfConvert = spawn('java', [
                            '-jar',
                            `${pdfBoxPath}`,
                            'PDFToImage',
                            '-dpi',
                            dpi,
                            '-imageType',
                            'png',
                            '-outputPrefix',
                            `${rawPdfDir}/page-`,
                            `./${pdfFilePath}`,
                            `-startPage`,
                            `${startPage}`,
                            `-endPage`,
                            `${endPage}`
                        ]);

                    }
Enter fullscreen mode Exit fullscreen mode

I am using the loop in this case.

Top comments (0)