How to Optimize PDF from File (Node for PDF Optimization API in JavaScript and PDF.co Web API
PDF.co Web API: the Rest API that provides a set of data extraction functions, tools for document 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)
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"; // PDF document password. Leave empty for unprotected documents. const Password = ""; // Destination PDF file name const DestinationFile = "./result.pdf"; // Prepare request uri var query = `https://api.pdf.co/v1/pdf/optimize`; let reqOptions = { uri: query, headers: { "x-api-key": API_KEY }, formData: { name: path.basename(DestinationFile), password: Password, async: 'True', 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); console.log(`Job #${data.jobId} has been created!`); checkIfJobIsCompleted(data.jobId, data.url); }); function checkIfJobIsCompleted(jobId, resultFileUrl) { let queryPath = `/v1/job/check`; // JSON payload for api request let jsonPayload = JSON.stringify({ jobid: jobId }); let reqOptions = { host: "api.pdf.co", path: queryPath, method: "POST", headers: { "x-api-key": API_KEY, "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); console.log(`Checking Job #${jobId}, Status: ${data.status}, Time: ${new Date().toLocaleString()}`); if (data.status == "working") { // Check again after 3 seconds setTimeout(function () { checkIfJobIsCompleted(jobId, resultFileUrl); }, 3000); } else if (data.status == "success") { // Download PDF file var file = fs.createWriteStream(DestinationFile); https.get(resultFileUrl, (response2) => { response2.pipe(file) .on("close", () => { console.log(`Generated PDF file saved as "${DestinationFile}" file.`); }); }); } else { console.log(`Operation ended with status: "${data.status}".`); } }) }); // 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" } }
PDF.co Web API – Optimize PDF Async using JavaScript
In this tutorial, you will learn to optimize PDF from file async API in JavaScript using PDF.co Web API. We will use a sample PDF in this demo. First, open your Visual Studio Code editor. You can also use your favourite editor in JavaScript. Then enter the JavaScript sample code. You can get the JavaScript sample code in PDF.co API docs.
In line 13, add your API key. You can get the API key in your PDF.co dashboard. In line 17, input the source PDF file name. For line 21 type your desired output file name.
Then set async to true. Once you’re done setting up the code, let’s run the program. In your terminal type ‘npm install request’ module for file upload. Then type the ‘node app.js’ to see the result. Once the program runs successfully, it will return a job ID that you may use for a job check. As you can see, the output will be saved as ‘result.pdf’.
Let’s check the folder to see the result. Here’s the PDF document output that we successfully compressed and reduce its size.
Video Guide
ON-PREMISE OFFLINE SDK
See also:
ON-DEMAND REST WEB API
Get Your API Key
See also:
PDF-co-Web-API-JavaScript-Optimize-PDF-From-File-(Node-js)-Async-API.pdf