Home > Enterprise >  PDF to Image in node
PDF to Image in node

Time:10-06

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.

CodePudding user response:

may be you can try this bro:

  1. Create an uploads folder & copy the sample.pdf file which you want to convert as png. since here I am only going to show you how to convert the pdf to png I am using the pdf as a static path you need to upload that pdf file via REST API.
  2. Now open your app.js OR index.js file & paste the below code we are using the pdf2pic packages to covert the pdf pages to png images.

or you visit this link: https://codinghub.medium.com/how-to-convert-pdf-file-pages-to-png-images-node-js-dccec010bf13

CodePudding user response:

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'});
  • Related