Node.js Express Convert PNG JPG Images to Single PDF File Web App Using ImageMagick Library Deployed to Heroku 2020

Node.js Express Convert PNG JPG Images to Single PDF File Web App Using ImageMagick Library Deployed to Heroku 2020

 

 

 

 

Live Demo

 

You can see the live demo of the app right here

 

Get Started

 

In order to get started you need to install these dependencies which are listed below

 

npm init -y

 

npm i express

 

npm i multer

 

npm i nodemon

 

 

Now make the entry level file index.js and start a simple express server on port 3000 like this

 

 

const express = require("express");

const app = express();


const PORT = process.env.PORT || 3000;

app.get("/", (req, res) => {
  res.sendFile(__dirname + "/index.html");
});


app.listen(PORT, () => {
  console.log(`App is listening on Port ${PORT}`);
});

 

 

Now we will load the index.html for our user so that it can interact with the application. Copy paste the code inside the index.html file

 

 

index.html

 

 

<!DOCTYPE html>
<html>
  <head>
    <title>Images to PDF Web App in Node and Express</title>
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    />
  </head>
  <body>
      <div class="container">
          <br><br>
          <h1 class="text-center">
              Convert Image to PDF
          </h1>
          <br>
          <form action="/merge" method="post" enctype="multipart/form-data">
            <div class="form-group">
                <input type="file" name="files" multiple required class="form-control">
            </div>
            <div class="form-group">
                <button class="btn btn-danger btn-block">
                    Convert to PDF
                </button>
            </div>
        </form>
      </div>
</body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</html>

 

 

 

Creating Uploads Folder Dynamically

 

 

Now we will create the folders dynamically where we will store the mp3 files which will be processed by imagemagick and then it will be converted to a pitched file

 

 

const fs = require("fs");

 var list = ""


var dir = "public";
var subDirectory = "public/uploads";

if (!fs.existsSync(dir)) {
  fs.mkdirSync(dir);

  fs.mkdirSync(subDirectory);
}

 

 

 

Here for the very first time the node.js application loads it will check the condition if the folder public doesn’t exist then it will create this folder and also it will create the uploads folder inside the public folder as a subdirectory.

READ  Node.js Express Paytm Payment Gateway Integration Full Tutorial with Source Code 2020

 

 

 

Setting Public Folder as Static

 

 

Now in this block of code we will set the public folder as static so that it can store the mp3 files

 

 

app.use(express.static("public"));

 

 

 

Loading the BodyParser Middleware

 

 

BodyParser middleware is very much necessary for this application as we will processing the form data which is submitted by the user inside the index.html file. So for that you need to copy paste the below code inside index.js

 

 

const bodyParser = require("body-parser");

app.use(bodyParser.urlencoded({ extended: false }));

app.use(bodyParser.json());

 

 

 

Uploading Image Files to Server Using Multer

 

 

Now the comes the most important part of the application we need to first of all upload the images to the uploads folder before we can process them. So for this we will be using a famous library of node called multer to do this task. Copy paste this block of code to upload files inside node.

 

 

const path = require("path");
const multer = require("multer");

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "public/uploads");
  },
  filename: function (req, file, cb) {
    cb(
      null,
      file.fieldname + "-" + Date.now() + path.extname(file.originalname)
    );
  },
});

const imageFilter = function (req, file, cb) {
  if (
    file.mimetype == "image/png" ||
    file.mimetype == "image/jpg" ||
    file.mimetype == "image/jpeg"
  ) {
    cb(null, true);
  } else {
    cb(null, false);
    return cb(new Error("Only .png, .jpg and .jpeg format allowed!"));
  }
};

var upload = multer({ storage: storage, fileFilter: imageFilter });

 

 

Converting Image Files to Single PDF File

 

 

Now we will do the fun part of the application after we upload the images files on the server. We will issue a simple shell command inside our node.js application using a built in library of node called as child_process. So in this block of code we will use a special imagemagick command which will carry out this process for us automatically. All this code will be put inside the post request which the user makes inside the index.html form.

READ  Koa.js Adding HTTP Static Cache to App in Browser Using koa-static-cache Library Full Project For Beginners

 

 

app.post("/merge", upload.array("files", 1000), (req, res) => {
  list = "";
  if (req.files) {
    req.files.forEach((file) => {
      list += `${file.path}`;
      list += " ";
    });

    console.log(list);

    exec(`magick convert ${list} ${outputFilePath}`, (err, stderr, stdout) => {
      if (err) throw err;

      res.download(outputFilePath, (err) => {
        if (err) throw err;

        req.files.forEach((file) => {
          fs.unlinkSync(file.path);
        });

        fs.unlinkSync(outputFilePath);
      });
    });
  }
});

 

 

 

Deploy to Heroku

 

 

Watch the youtube video given above for this task and here you need this url which is given below to add a buildback inside heroku project to install imagemagick inside your project.

 

 

https://github.com/DuckyTeam/heroku-buildpack-imagemagick.git

 

 

 

 

DOWNLOAD SOURCE CODE

 

 

 

Leave a Reply