node.jsexpressjspdf

PDF to Image in node


I am using node-express and need to convert pdf into image in the server side.
Pdf-poppler is not working in linux and pdf-image happens to be not working as well. Any alternate method how we can convert and save pdf to image in the backend.


Solution

  • Pdf-poppler use pdftocairo command provided by the poppler project. Since poppler did support Linux, you can install it by yourself.

    For example, on ubuntu

    apt-get install poppler-utils
    

    then call pdftocairo command using the code below from Pdf-poppler.

    const path = require('path');
    const {execFile} = require('child_process');
    const pdftocairoBin = '/usr/bin/pdftocairo';
    const FORMATS = ['png', 'jpeg', 'tiff', 'pdf', 'ps', 'eps', 'svg'];
    
    let defaultOptions = {
        format: 'jpeg',
        scale: 1024,
        out_dir: null,
        out_prefix: null,
        page: null
    };
    
    function pdf2image(file, opts) {
        return new Promise((resolve, reject) => {
            opts.format = FORMATS.includes(opts.format) ? opts.format : defaultOptions.format;
            opts.scale = opts.scale || defaultOptions.scale;
            opts.out_dir = opts.out_dir || defaultOptions.out_dir;
            opts.out_prefix = opts.out_prefix || path.dirname(file);
            opts.out_prefix = opts.out_prefix || path.basename(file, path.extname(file));
            opts.page = opts.page || defaultOptions.page;
    
            let args = [];
            args.push([`-${opts.format}`]);
            if (opts.page) {
                args.push(['-f']);
                args.push([parseInt(opts.page)]);
                args.push(['-l']);
                args.push([parseInt(opts.page)]);
            }
            if (opts.scale) {
                args.push(['-scale-to']);
                args.push([parseInt(opts.scale)]);
            }
            args.push(`${file}`);
            args.push(`${path.join(opts.out_dir, opts.out_prefix)}`);
    
            execFile(pdftocairoBin, args, {
                encoding: 'utf8',
                maxBuffer: 5000*1024,
                shell: false
            }, (err, stdout, stderr) => {
                if (err) {
                    reject(err);
                }
                else {
                    resolve(stdout);
                }
            });
        });
    };
    

    Usage of pdf2image function

    pdf2image('./input.pdf', {out_dir:'./', out_prefix:'ppp'});