How to convert DOCX to PDF using JavaScript

Table of contents

    Convert DOCX files to PDF using JavaScript and Nutrient DWS Processor API. This tutorial covers API setup, Node.js implementation with axios, and document processing workflows for automating DOCX-to-PDF conversion in your applications.
    How to convert DOCX to PDF using JavaScript
    Summary

    Convert DOCX to PDF using Nutrient’s JavaScript API. Create a free account, get API credentials, and implement conversion using axios and form-data. Combine with 30+ API tools for merging, watermarking, and page manipulation.

    Convert DOCX files to PDFs in JavaScript using Nutrient’s DOCX-to-PDF JavaScript API. The free plan includes 200 credits. Different operations consume different amounts of credits. Create a free account(opens in a new tab) to get your API key.

    It’s now possible to view and edit Word, Excel, and PowerPoint documents directly in the browser, without any server-side processing required.

    Why convert DOCX to PDF?

    Converting DOCX files to PDF is essential for workflows requiring document standardization and sharing. Common use cases include:

    • Document preservation — Convert Word documents to PDFs to preserve formatting, fonts, and layouts regardless of software or device used to view them.
    • Professional distribution — Share contracts, reports, and proposals in a universal format that maintains consistent appearance across all platforms.
    • Compliance and archiving — Create tamper-resistant records for legal compliance, audit trails, and long-term document storage.
    • Print-ready documents — Ensure documents print exactly as intended without formatting issues or missing fonts.
    • Version control — Lock document formatting to prevent accidental edits while allowing controlled review and approval processes.

    The DOCX-to-PDF API automates this process in your workflow.

    Nutrient DWS Processor API

    Converting DOCX to PDF is one of 30+ operations available through our PDF API tools. Combine DOCX-to-PDF conversion with other tools for complex workflows:

    Your account includes access to all PDF API tools.

    Step 1 — Creating a free account on Nutrient

    Go to our website(opens in a new tab), where you’ll see the page below, prompting you to create your free account.

    Free account Nutrient API

    Once you’ve created your account, you’ll be welcomed by a page showing an overview of your plan details.

    You’ll start with 200 credits to process, and you’ll be able to access all our PDF API tools.

    Step 2 — Obtaining the API key

    After you’ve verified your email, you can get your API key from the dashboard. In the menu on the left, click API keys. You’ll see the following page, which is an overview of your keys.

    Convert DOCX to PDF JavaScript API Key

    Copy the Live API key, because you’ll need this for the DOCX-to-PDF API.

    Step 3 — Setting up folders and files

    Now, create a folder called docx_to_pdf and open it in a code editor. For this tutorial, you’ll use VS Code as your primary code editor. Next, create two folders inside docx_to_pdf and name them input_documents and processed_documents.

    Copy your DOCX file to the input_documents folder and rename it to document.docx.You can use our demo document as an example.

    Then, in the root folder, docx_to_pdf, create a file called processor.js. This is the file where you’ll keep your code.

    Your folder structure will look like this:

    docx_to_pdf
    ├── input_documents
    | └── document.docx
    ├── processed_documents
    └── processor.js

    Step 4 — Installing dependencies

    To get started converting PDF pages, you first need to install the following dependencies:

    Use the command below to install both of them:

    Terminal window
    npm install axios
    npm install form-data

    Step 5 — Writing the code

    Now, open the processor.js file and paste the code below into it:

    // This code requires Node.js. Do not run this code directly in a web browser.
    const axios = require('axios')
    const FormData = require('form-data')
    const fs = require('fs')
    const formData = new FormData()
    formData.append('instructions', JSON.stringify({
    parts: [
    {
    file: "file"
    }
    ]
    }))
    formData.append('file', fs.createReadStream('input_documents/document.docx'))
    ;(async () => {
    try {
    const response = await axios.post('https://api.nutrient.io/build', formData, {
    headers: formData.getHeaders({
    'Authorization': 'Bearer YOUR_API_KEY_HERE'
    }),
    responseType: "stream"
    })
    response.data.pipe(fs.createWriteStream("processed_documents/result.pdf"))
    } catch (e) {
    const errorString = await streamToString(e.response.data)
    console.log(errorString)
    }
    })()
    function streamToString(stream) {
    const chunks = []
    return new Promise((resolve, reject) => {
    stream.on("data", (chunk) => chunks.push(Buffer.from(chunk)))
    stream.on("error", (err) => reject(err))
    stream.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")))
    })
    }

    Make sure to replace YOUR_API_KEY_HERE with your API key.

    Code explanation

    Here, you have a form variable that contains the instructions for the API. You’re using createReadStream to read the input file. You then have a function, axios.post(), that’ll make the POST request to the DOCX-to-PDF API.

    The response of the API is stored in the processed_documents folder.

    Output

    To execute the code, use the following command:

    node processor.js

    On the successful execution of the code, you’ll see a new processed file named result.pdf in the processed_documents folder.

    The folder structure will look like this:

    docx_to_pdf
    ├── input_documents
    | └── document.docx
    ├── processed_documents
    | └── result.pdf
    └── processor.js

    Additional resources

    Explore more ways to work with Nutrient API:

    Conclusion

    This tutorial covered converting DOCX files to PDF documents in JavaScript using the DOCX-to-PDF JavaScript API.

    You can integrate these functions into existing applications. The same API token enables other operations like merging documents, adding watermarks, and more. Sign up(opens in a new tab) for a free trial.

    FAQ

    Do I need a paid account to use Nutrient DWS Processor API?

    No. Start with a free account that provides 200 credits for processing documents. Different operations consume different amounts of credits, so you can process varying numbers of documents depending on the operations you use.

    Does Nutrient DWS Processor API preserve DOCX formatting when converting to PDF?

    Yes. Nutrient DWS Processor API maintains document formatting, including fonts, styles, images, tables, and page layouts. Complex elements like headers, footers, and embedded objects are preserved in the PDF output.

    Can I use this code in a web browser?

    No. This code requires Node.js and uses server-side modules like fs (file system). For browser-based DOCX processing, consider using Nutrient’s client-side document viewer which can display DOCX files directly without server-side conversion.

    Can I convert multipage DOCX documents to PDF?

    Yes. Nutrient DWS Processor API converts multipage DOCX documents to PDF while maintaining pagination, page breaks, and document structure across all pages.

    Jonathan D. Rhyne

    Jonathan D. Rhyne

    Co-Founder and CEO

    Jonathan joined PSPDFKit in 2014. As Co-founder and CEO, Jonathan defines the company’s vision and strategic goals, bolsters the team culture, and steers product direction. When he’s not working, he enjoys being a dad, photography, and soccer.

    Explore related topics

    FREE TRIAL Ready to get started?