How to convert PDF to PNG from uploaded file (node for PDF to image API in JavaScript using PDF.co Web API

When creating PDF-related solutions, one of the common requirements is to convert PDF pages to image format. There are many online tools available for this feature, but when we want to create a programming solution we need SDK or API for it. PDF.co provides a robust and secure API to convert PDF document to the image formats such as PNG, JPG, or TIFF.

In this article we’ll be reviewing NodeJS source code which converts PDF pages to PNG format images. You can easily copy-paste this code on your machine and play with it. You can also visit our GitHub repository to get this code and different variants of PDF to Image implementations in other languages.

Sounds interesting? Let’s get started!

PDF.co Web API: the Web API with a set of tools for documents manipulation, data conversion, data extraction, splitting and merging of documents. Includes image recognition, built-in OCR, barcode generation and barcode decoders to decode bar codes from scans, pictures and pdf.

On-demand (REST Web API) version:
 Web API (on-demand version)

On-premise offline SDK for Windows:
 60 Day Free Trial (on-premise)

app.js

      
/*jshint esversion: 6 */ var https = require("https"); var path = require("path"); var fs = require("fs"); // `request` module is required for file upload. // Use "npm install request" command to install. var request = require("request"); // The authentication key (API Key). // Get your own by registering at https://app.pdf.co/documentation/api const API_KEY = "***********************************"; // Source PDF file const SourceFile = "./sample.pdf"; // Comma-separated list of page indices (or ranges) to process. Leave empty for all pages. Example: '0,2-5,7-'. const Pages = ""; // PDF document password. Leave empty for unprotected documents. const Password = ""; // 1. RETRIEVE PRESIGNED URL TO UPLOAD FILE. getPresignedUrl(API_KEY, SourceFile) .then(([uploadUrl, uploadedFileUrl]) => { // 2. UPLOAD THE FILE TO CLOUD. uploadFile(API_KEY, SourceFile, uploadUrl) .then(() => { // 3. CONVERT UPLOADED PDF FILE TO PNG convertPdfToPng(API_KEY, uploadedFileUrl, Password, Pages); }) .catch(e => { console.log(e); }); }) .catch(e => { console.log(e); }); function getPresignedUrl(apiKey, localFile) { return new Promise(resolve => { // Prepare request to `Get Presigned URL` API endpoint let queryPath = `/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name=${path.basename(SourceFile)}`; let reqOptions = { host: "api.pdf.co", path: encodeURI(queryPath), headers: { "x-api-key": API_KEY } }; // Send request https.get(reqOptions, (response) => { response.on("data", (d) => { let data = JSON.parse(d); if (data.error == false) { // Return presigned url we received resolve([data.presignedUrl, data.url]); } else { // Service reported error console.log("getPresignedUrl(): " + data.message); } }); }) .on("error", (e) => { // Request error console.log("getPresignedUrl(): " + e); }); }); } function uploadFile(apiKey, localFile, uploadUrl) { return new Promise(resolve => { fs.readFile(SourceFile, (err, data) => { request({ method: "PUT", url: uploadUrl, body: data, headers: { "Content-Type": "application/octet-stream" } }, (err, res, body) => { if (!err) { resolve(); } else { console.log("uploadFile() request error: " + e); } }); }); }); } function convertPdfToPng(apiKey, uploadedFileUrl, password, pages) { // Prepare URL for `PDF To PNG` API call var queryPath = `/v1/pdf/convert/to/png`; // JSON payload for api request var jsonPayload = JSON.stringify({ password: password, pages: pages, url: uploadedFileUrl }); var reqOptions = { host: "api.pdf.co", method: "POST", path: queryPath, headers: { "x-api-key": apiKey, "Content-Type": "application/json", "Content-Length": Buffer.byteLength(jsonPayload, 'utf8') } }; // Send request var postRequest = https.request(reqOptions, (response) => { response.on("data", (d) => { response.setEncoding("utf8"); // Parse JSON response let data = JSON.parse(d); if (data.error == false) { // Download generated PNG files var page = 1; data.urls.forEach((url) => { var localFileName = `./page${page}.png`; var file = fs.createWriteStream(localFileName); https.get(url, (response2) => { response2.pipe(file) .on("close", () => { console.log(`Generated PNG file saved as "${localFileName}" file.`); }); }); page++; }, this); } else { // Service reported error console.log("readBarcodes(): " + data.message); } }); }) .on("error", (e) => { // Request error console.log("readBarcodes(): " + e); }); } // Write request data postRequest.write(jsonPayload); postRequest.end();

package.json

      
{ "name": "test", "version": "1.0.0", "description": "PDF.co", "main": "app.js", "scripts": { }, "keywords": [ "pdf.co", "web", "api", "bytescout", "api" ], "author": "ByteScout & PDF.co", "license": "ISC", "dependencies": { "request": "^2.88.2" } }

Output

Though this code snippet is self-explanatory and straight-forward, let’s review it briefly. We can logically divide this code snippet into three parts. First, we’re adding library references and gathering all necessary data. Second, we’re uploading the input file and getting its public URL. And lastly, we’re using this public URL and processing PDF to PNG conversation.

Initially all reference such as https, path, fs as well external reference such as request are loaded. We’re preparing necessary data such as API_KEY which is used for authenticating request at PDF.co server, SourceFile which as name suggests references source file path, Pages which indicates pages which needs to be converted to image format, etc.

In order to upload file to PDF.co cloud and getting public URL, we’re first getting pre-signed URL. This pre-signed URL is retrieved by API endpoint /v1/file/get-presigned-url. This API request returns with two URLs, one for pre-signed URL (data.presignedUrl) and other for public URL (data.url). We’re using this pre-signed URL to upload actual file using PUT request, logic of which is in uploadFile function. After uploading of file with PUT request is completed, public URL returned by GetPreSignedURL request points to this uploaded file. This URL is temporary and only available for few hours for security reasons.

PDF.co API endpoint /v1/pdf/convert/to/png is used to convert PDF pages to PNG image format. In the request we’re passing JSON payload containing input file URL, pages which needs to be converted, etc. In the request header we’re passing PDF.co API key named x-api-key, this API key is used for authentication of PDF.co request. Response contains URLs of PNG images. These PNG image URLs are downloaded and saved locally.

This is how easy to convert PDF pages to PNG image using PDF.co API endpoint. Practical makes programmer perfect! Please try this program in your machine to get more out of this article. Thank you for reading!

VIDEO

ON-PREMISE OFFLINE SDK

Get 60 Day Free Trial

See also:

ON-DEMAND REST WEB API

Get Your API Key

See also:

Related Pages:

Related Samples: