Convert DOC To PDF From File (Node.js) | JavaScript | DOC To PDF APIByteScout PDF SDK

Convert DOC To PDF From File (Node.js) | JavaScript | DOC To PDF API

ConvertDocToPdfFromFile.js:

JavaScript
/*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 DOC or DOCX file
const SourceFile = "./sample.docx";
// Destination PDF file name
const DestinationFile = "./result.pdf";


// Prepare URL for `DOC To PDF` API call
var query = `https://api.pdf.co/v1/pdf/convert/from/doc`;
let reqOptions = {
    uri: query,
    headers: { "x-api-key": API_KEY },
    formData: {
        name: path.basename(DestinationFile),
        file: fs.createReadStream(SourceFile)
    }
};

// Send request
request.post(reqOptions, function (error, response, body) {
    if (error) {
        return console.error("Error: ", error);
    }

    // Parse JSON response
    let data = JSON.parse(body);
    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("Error: " + data.message);
    }
});