Convert PDF to PNG Node.JS

10,454

Updated Answer

I think it all comes out at the end because Ghostscript is actually doing the work on behalf of IM. You may need to check how many pages there are in your PDF and then do a loop if you want fine-grained control.

# Get number of pages in "a.pdf"
pages=$(identify a.pdf | wc -l)

# Alternative, faster way of getting number of pages - pdfinfo is part of Poppler package
pages=$(pdfinfo a.pdf | grep "^Pages")

for all pages 0 .. (pages-1)
   convert a.pdf[$page] page-${page}.png
done

Original Answer

Not sure I 100% understand what you want, but I think it is something like this...

Say you have a 20-page PDF, called input.pdf. If you print the scene number, whose escape sequence is %s, like this

convert input.pdf -format "%s\n" -write info: z%d.png

you will get this:

Output

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

and these files:

ls z*
z0.png  z10.png z12.png z14.png z16.png z18.png z2.png  z4.png  z6.png  z8.png
z1.png  z11.png z13.png z15.png z17.png z19.png z3.png  z5.png  z7.png  z9.png
Share:
10,454
Hiero
Author by

Hiero

Updated on June 04, 2022

Comments

  • Hiero
    Hiero almost 2 years

    I'm building a Node.js application to convert PDF to PNGs and display on the user page.

    The app will work like this:

    1. User uploads a PDF to the server
    2. Server converts the PDFs pages to individual PNGs
    3. Display PNGs on the User page

    I found a great package called Node ImageMagick https://github.com/rsms/node-imagemagick but Its not a perfect fit.

    Some things like -monitor flag from ImageMagick doesn't work but doesn't work on vanilla node.js as well:

    var exec = require('child_process').exec;
    
    exec('convert -monitor myFile.pdf myFile.png', function(error, stdout, stderr) {
        console.log('converting is done');
    });
    

    The thing I want to achieve is that the converting function to return the name of the files converted like: myFile-0.png, myFile-1.png.

    The solution I wanted to implement was to make a directory with the name of the PDF and convert the PNGs there like:

       exec('convert myFile.pdf myFile/myFile.png', function(error, stdout, stderr) {
            console.log('converting is done');
        });
    

    Then read the content of that directory and send to the user the names of files and the paths.

    Is this a good solution?

    Can someone explain me how to achieve this goal?