How to Convert CSV to PDF from Uploaded File (Node for CSV to PDF API in JavaScript using PDF.co Web API
CSV is a very common file format for data storage and transfer. On the other hand PDF is a standard format for printing documents hence mostly reports are stored in PDF format digitally. Often we need to create PDF report based on the data stored in CSV format. PDF.co provides an easy-to-use API endpoint /v1/pdf/convert/from/csv to convert PDF to CSV format.
In this article we’ll review NodeJS code snippet for creating PDF to CSV. You can also refer to the Source Code at this location.
PDF.co Web API: the Web API with a set of tools for document 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 CSV file const SourceFile = "./sample.csv"; // 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 CSV FILE TO PDF convertCsvToPdf(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 convertCsvToPdf(apiKey, uploadedFileUrl, destinationFile) { // Prepare URL for `CSV To PDF` API call let queryPath = `/v1/pdf/convert/from/csv`; // 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(); }
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 program is self-explanatory, and we’ve also seen the output, let’s review important code snippets a bit.
Initially we’re injecting all necessary package dependencies such as https, path and fs. We’re also injecting external libraries such as requst. We’re also preparing necessary information for the API call such as PDF.co API Key (API_KEY), Input file path (SourceFile) and Destination file path (DestinationFile).
We can divide this program into two local parts, first we’re uplaoding source file to PDF.co Cloud and getting the public URL; secondly, we’re using this public URL for PDF and processing CSV to PDF conversion.
PDF.co API endpoint /v1/file/upload/get-presigned-url is used to get a pre-signed URL of the source file. In the request we’re passing the input PDF file name where as in response it’s returning a public URL (data.url) along with the pre-signed URL (data.presignedUrl). This Pre-signed URL is used to upload the actual source file with PUT request. After the source file is uplaoded to a pre-signed URL public URL (data.url) now points to the source file. This public URL is temporary and only available for a few hours for security reasons.
The API endpoint /v1/pdf/convert/from/csv is used to create PDF from CSV file. In order to create PDF.co request we’re creating the JSON payload with minimal parameters such as the source file URL (url) and the result file path (name). The PDF.co API key is used in the request header (x-api-key) for authentication purposes. In reponse, PDF.co is responding with output PDF URL (data.url) which contains all CSV info as shown in the output.
In this sample, we’re using the basic request parameters to process CSV to PDF conversion. However, we can use advanced input parameters to optimize the request as per our needs. Please refer to this link to access PDF.co API documentation.
Please try this sample in your machine to get most of out this article. Thank you for reading!
VIDEO
ON-PREMISE OFFLINE SDK
See also:
ON-DEMAND REST WEB API
Get Your API Key
See also: