Document to PDF Conversion - A Step-by-Step Guide Using Node.js and ApyHub API
Published: 2024-01-09 08:13:37

## Introduction

One common thing that developers come across frequently when building their applications is converting documents from one format to another. We have also seen that the most popular of these conversions is no other than converting Word documents to PDFs.

To help developers select the right tools we have explored the benefits of [converting Documents to PDFs](https://apyhub.com/blog/convert-docx-to-pdf-using-api), [comparison between the available top tools](https://apyhub.com/blog/exploring-top-document-conversion-apis), and ways you can convert documents to PDFs including [SmallPDF](https://smallpdf.com/), and [Cloudconvert](https://cloudconvert.com/).

We also looked at Cloud-based APIs as a possible way to do document conversions: In this context, we saw how providers like [ApyHub](https://apyhub.com/catalog) or [ConvertAPI](https://www.convertapi.com/) can be particularly beneficial.

In this article, we will further discuss how to effectively use the **[ApyHub Convert Doc to PDF](https://apyhub.com/utility/converter-doc-pdf)** API using NodeJS.

This tutorial aims to be quite straightforward and consists of 7 simple steps.

### 1. Install the required libraries:

To install all the required dependencies, run this command on the terminal of your project folder.

```bash
npm install axios
```

Once we run `npm install` in the terminal, the command triggers the installation of the specified dependencies listed in the project's package.json file. The following dependencies are commonly installed.

**Axios**: A popular HTTP client library for making HTTP requests in Node.js. It simplifies the process of sending HTTP requests and handling responses. In this case, axios is used to make a POST request to the Document Conversion API, sending the file URL and output file name.

### 2. Create a new file:

The next step is to create a new file; for example, create a file **`convertDocToPDF.js`** and add the following code to import the required libraries we installed.:

```jsx
const axios = require('axios');
```

### 3. Define a function to convert the Docx. file to PDF:

This function encapsulates the logic for making the API request to convert a Word document to a PDF API, preparing the necessary document URL for the conversion, and handling potential errors during the conversion process. We will need `apy-token` which you can find in [documentation](https://apyhub.com/utility/converter-doc-pdf).

```jsx
import axios from "axios";

async function convertDocToPDF(docURL, outputFileName) {
  const apiURL = 'https://api.apyhub.com/convert/word-url/pdf-url';
  const requestData = {
    url: docURL // URL of the Word document
  };
  const options = {
    method: 'POST',
    url: apiURL,
    params: {output: `${outputFileName}.pdf`, landscape: 'false'},
    headers: {
      'apy-token': 'YOUR_APY_TOKEN', // Replace with your Unique apy-token
      'Content-Type': 'application/json'
    },
    data: requestData
  };

  try {
    const response = await axios.request(options);
    console.log("PDF conversion successful! Here's the PDF URL:", response.data);
    return response.data; // Or handle it as you need
  } catch (error) {
    console.error("An error occurred during the conversion:", error.message);
    throw error; // Or handle the error as needed
  }
}
```

### 4. Invoke the convertDocToPDF function:

After invoking the `convertDocToPDF` function, pass the Word document URL and the desired output filename as arguments. This function sends a request to the Document Conversion API, which converts the Word document to a PDF and returns the URL of the converted PDF. The successful conversion URL is logged to the console. If there is an error during the conversion process, it is caught and the error message is logged to the console.

```jsx
const docURL = '***** PROVIDE THE URL OF DOC *****'; // Replace with your document URL
const outputFilename = '***** PROVIDE THE OUTPUT FILE NAME *****'; // Replace with your desired output PDF file name

convertDocToPDF(docURL, outputFilename)
     .then((pdfUrl) => {
       console.log('PDF conversion successful! PDF URL:', pdfUrl);
     })
     .catch((error) => {
       console.error('Error:', error.message);
     });
```

### 5. Save the file and execute the script

Save the file open your terminal, navigate to the project directory, and run the following command to execute the script:

```bash
node convertDocToPDF.js
```

### 6. Send a request to the API

The script will send a request to the API, convert the docx file, and save it as the provided file name`${outputFilename}.pdf` in your project directory. That's it! You have successfully created functionality to convert documents to PDF using the ApyHub API.

And that's it! Was easy right?

Keep in mind that ApyHub also has similar conversion APIs. For example, some APIs help you convert [spreadsheets to PDFs](https://apyhub.com/utility/converter-spreadsheet-pdf), [presentations to](https://apyhub.com/utility/converter-presentation-pdf) PDFs, and [apply watermarks to PDFs,](https://apyhub.com/utility/pdf-stamp-watermark) which can help depending on your use case.