Loading

How to convert PDF file pages to PNG images-node.js

How to convert PDF file  pages to PNG images-node.js

I am going to show you a step by step guide about how to create a node express js project & write a rest API which will take a pdf file path as request params & convert that all pdf pages to png images. Let's Start

Prerequisite

  • node >= 12.x
  • graphicsmagick
  • ghostscript

We will use the pdf2pic package to convert the pdf pages to png image - https://www.npmjs.com/package/pdf2pic

  1. Install the node.js from the node.js official website https://nodejs.org/en/download/ by downloading the LTS version

node.PNG

  1. Open the command prompt and create your project folder go to that folder
    mkdir myapp
    cd myapp
  2. Install the initial project by running
    npm init 
  3. 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.
  4. 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.

app.js file

var express = require("express");
var router = express.Router();
const { fromPath } = require("pdf2pic");
const pdf = require("pdf-page-counter");
const fs = require("fs");
var app = express();
app .get("/pdfpng", function (req, res, next) {
    const { filename } = req.query;
    const options = {
        density: 100,
        saveFilename: "file",
        savePath: "./public/uploads",
        format: "png",
        width: 600,
        height: 600,
    };
    const storeAsImage = fromPath(
        `./public/uploads/${filename}`,
        options
    );
    let dataBuffer = fs.readFileSync(
        `./public/uploads/${filename}`
    );
    pdf(dataBuffer).then(function (data) {
        for (
            var pageToConvertAsImage = 1;
            pageToConvertAsImage <= data.numpages;
            pageToConvertAsImage++
        ) {
            storeAsImage(pageToConvertAsImage).then((resolve) => {
                return resolve;
            });
        }
        res.send({ filename: filename });
    });

});
  1. listen to node application at port 3200
    app.listen(3200, function () {
    console.log('App listening on port 3200!');
    });
  2. run the node application
    node app 
  3. Open the browser & type the route path with pdf file name http://localhost:3200/api/pdfToPng/?filename=sample.pdf

That's it goto to the uploads folder you will find that all pdf pages have png images that have successfully converted. In the next Article, I will show you how to write a REST API to read that converted images & return all images with images path as a JSON object. Thanks for reading the article.

Related Articles

Leave a Reply

Comments