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
Prerequisites
- 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
- Install the node.js from the node.js official website https://nodejs.org/en/download/ by downloading the LTS version
2. Open the command prompt and create your project folder go to that folder
mkdir myapp && cd myapp
3. Install the initial project by running
npm init
4. 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.
5. 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
});
});
});
6. Listen to node application at port 3200
app.listen(3200, function () {
console.log('App listening on port 3200!');
});
7. Run the node application
node app
8. 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.
Originally published at https://www.codinghub.net.