How to Convert DOC to PDF from Uploaded File (Node for DOC to PDF API in JavaScript with PDF.co Web API
In this article we’ll take a look at transforming a word document file to PDF using PDF.co API Endpoint. Before we move to details let’s have a quick introduction of PDF.co.
PDF.co Web API is the REST API that provides a set of data extraction functions, tools for documents manipulation, splitting and merging of PDF files. Includes built-in OCR, images recognition, can generate and read barcodes from images, scans 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)
Check out these parts to convert DOC to PDF from the uploaded file (Node.js):
The following is the full nodejs source code.
Source Code
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 DOC or DOCX file const SourceFile = "./sample.docx"; // Destination PDF file name const DestinationFile = "./result.pdf"; // 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 DOC (DOCX) FILE TO PDF convertDocToPdf(API_KEY, uploadedFileUrl, DestinationFile); }) .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 convertDocToPdf(apiKey, uploadedFileUrl, destinationFile) { // Prepare URL for `DOC To PDF` API call let queryPath = `/v1/pdf/convert/from/doc`; // JSON payload for api request var jsonPayload = JSON.stringify({ name: path.basename(destinationFile), 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 PDF file var file = fs.createWriteStream(destinationFile); https.get(data.url, (response2) => { response2.pipe(file) .on("close", () => { console.log(`Generated PDF file saved as "${destinationFile}" file.`); }); }); } 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(); }
Now, let’s review the output GIF.
Output
Analysis
Now, let’s analyze the main logic of this program. We can logically divide this code into the following steps.
- Upload the input document to PDF.co and get the uploaded URL back
- Consume the PDF.co endpoint ‘/v1/pdf/convert/from/doc’ to get converted PDF
- Write the result PDF to the folder
Please note that PDF.co requires API key to be passed in the header for authenticating its requests. You can get your the PDF.co API Key by signing up here.
To get more out of this article, do try running this program code in your machine. Visit PDF.co documentations for more details.
VIDEO
ON-PREMISE OFFLINE SDK
See also:
ON-DEMAND REST WEB API
Get Your API Key
See also: