Converting PDFs, .AI, .PSD files to PNG and keeping transparency with ImageMagick

167 Views Asked by At

I am trying to convert any file to a PNG with transparency if the original file has transparency, of course. This works with a transparent PNG but I can't get it to work with with a PDF, AI, or PSD file. Everything just converts with a white background. I have scoured the internet looking for a solution with no luck. Any help is appreciated!

const im = gm.subClass({ imageMagick: '7+' });

im(f.filepath)
  .background('none')
  .write(`public/upload/${f.newFilename}.png`, (err) => {
    if (err) {
      console.error('Error converting file:', err);
    } else {
      console.log('File converted successfully!');
    }
  });
1

There are 1 best solutions below

0
Yogev Neumann On

I was not able to reproduce your problem.

I was able to create a PNG file with transparent background from a PDF file (with transparent background) using your snippet.

Versions:

$ nodejs --version
v12.22.9
$ npm list --depth=0 | grep -iE "(ima|gm|gs|sm)"
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]

The code:

const gm = require('gm').subClass({ imageMagick: '7+' });
gm(`./test.pdf`)
  .background('none')
  .write(`./test.png`, (err) => {
      if (err) {
        console.error('Error converting file:', err);
      } else {
        console.log('File converted successfully!');
      }
  });

So either the problem is with the input files or the versions that you are using.