3

I am attempting to convert pdf files into a preview icon jpg using the imagemagick library for NodeJS. I am trying to generate a preview of only the first page (for multi-page pdfs).

In the normal command line imagemagick program this can be done easily by saying "convert file.pdf[0] file.jpg"
where the [0] tells it to only convert the first page.

However I am not sure how to do that with this library. I tried concatenating [0] to the filename, but it just reads it as part of the real file name. Anyone know of a way around this using this library?

I had a look around for a while and found this, but they are not using this library. Convert PDF to PNG Node.JS

The specific library I am using is located here: https://www.npmjs.com/package/imagemagick

The code I am working with is below:

            let path = '/tmp/';
            let pageNumber = '[0]';
            let filePath =  path + fileId + fileName + pageNumber; 
            let imgFilePath = path + fileId + '.jpg';
            let writeStream = fs.createWriteStream(filePath);
            writeStream.on('error',err => {
              reject(err);
            });
            stream.pipe(writeStream);


              im.convert([
                filePath,
                '-background','white',
                '-alpha','remove',
                '-resize','192x192',
                '-quality','100',
                imgFilePath
              ],
kiwicomb123
  • 1,503
  • 21
  • 26

1 Answers1

1

The problem is that you are concatenating the [0] part onto the filename before you do the conversion. You should concatenate the [0] within the scope of the convert function like this:

            let path = '/tmp/';
            let filePath =  path + fileId + fileName;
            let imgFilePath = path + fileId + '.jpg';
            let writeStream = fs.createWriteStream(filePath);
            writeStream.on('error',err => {
              reject(err);
            });
            stream.pipe(writeStream);


              im.convert([
                filePath + '[0]',
                '-background','white',
                '-alpha','remove',
                '-resize','192x192',
                '-quality','100',
                imgFilePath
              ], 

This solution is tested working.

kiwicomb123
  • 1,503
  • 21
  • 26