How to Convert DOCX to PDF in Node.js and Python

Turning a Word document into a PDF looks like a one-line job until you try it on a server. The first package you find usually needs Microsoft Word installed, the second only extracts the text, and the third wants you to run a full office suite inside your container. This guide shows the short path in both Node.js and Python, then covers the details that decide whether the PDF looks right: fonts, errors and volume.

Why this is harder than it should be

A DOCX file is not a page description. It is a zipped bundle of XML that says "this paragraph, this style, this table", and it is the word processor that decides where each line breaks and where each page ends. To get a faithful PDF you need a real layout engine, and that leaves three practical options:

  • Automate Microsoft Word. This is what the Python docx2pdf package does. It works on a Windows or macOS desktop with Word installed, and not on a Linux server, in Docker or in a serverless function.
  • Run a headless office suite yourself. It works, but you now operate it: a large container image, one conversion per process, fonts to install, stuck processes to kill, and security patches to follow, because document parsers are a well-known attack surface (see file converter library vulnerabilities).
  • Call a conversion API. Your code sends the file and gets the PDF back. Someone else runs the layout engine, keeps it patched and scales it.

Pure JavaScript and pure Python libraries can read a DOCX, but none of them reproduce Word's pagination well enough for contracts, invoices or anything a customer will print. The rest of this guide uses the API route, with the official PrivConvert clients.

Python

Install the client and set your key. New accounts can start a free trial of 25 conversions without a card.

pip install privconvert
export PRIVCONVERT_API_KEY=pk_live_...

Converting a file on disk:

from privconvert import PrivConvert

pc = PrivConvert()  # reads PRIVCONVERT_API_KEY

result = pc.convert("word-to-pdf", "contract.docx")
result.save("contract.pdf")

The file argument also accepts bytes or an open binary file, which is what you want inside a web app. A complete FastAPI endpoint that takes an upload and returns the PDF:

from fastapi import FastAPI, HTTPException, UploadFile
from fastapi.responses import Response
from privconvert import PrivConvert, ConversionFailedError, UnsupportedTypeError

app = FastAPI()
pc = PrivConvert()

@app.post("/documents/to-pdf")
def to_pdf(file: UploadFile):
    try:
        result = pc.convert("word-to-pdf", file.file.read(), filename=file.filename)
    except UnsupportedTypeError:
        raise HTTPException(415, "Please upload a Word document.")
    except ConversionFailedError:
        raise HTTPException(422, "This document could not be converted.")
    return Response(result.content, media_type="application/pdf")

The document never touches your disk either: it goes from the request body to the API and the PDF goes straight back to the user.

Node.js

The Node.js client has no runtime dependencies and ships TypeScript types. Install it from the tagged GitHub release:

npm install github:toprivHQ/privconvert-node#v0.3.0
export PRIVCONVERT_API_KEY=pk_live_...

Converting a file on disk:

import { PrivConvert } from "privconvert";

const pc = new PrivConvert(); // reads PRIVCONVERT_API_KEY

const result = await pc.convert("word-to-pdf", "contract.docx");
await result.save("contract.pdf");

An Express route that accepts an upload and responds with the PDF. Multer keeps the upload in memory, and the client accepts the Buffer directly:

import express from "express";
import multer from "multer";
import { PrivConvert, ConversionFailedError, UnsupportedTypeError } from "privconvert";

const app = express();
const upload = multer({ storage: multer.memoryStorage() });
const pc = new PrivConvert();

app.post("/documents/to-pdf", upload.single("file"), async (req, res) => {
  try {
    const result = await pc.convert("word-to-pdf", req.file.buffer, {
      filename: req.file.originalname,
    });
    res.type("application/pdf").send(result.content);
  } catch (err) {
    if (err instanceof UnsupportedTypeError) return res.status(415).send("Please upload a Word document.");
    if (err instanceof ConversionFailedError) return res.status(422).send("This document could not be converted.");
    throw err;
  }
});

Without a client library

The clients are thin wrappers over one HTTP request, so any language works. It is a multipart POST with the file in a field called file, and the PDF comes back as the response body:

# Python, with requests
r = requests.post(
    "https://privconvert.com/api/convert/word-to-pdf",
    headers={"Authorization": f"Bearer {API_KEY}"},
    files={"file": open("contract.docx", "rb")},
)
r.raise_for_status()
open("contract.pdf", "wb").write(r.content)

// Node.js 18+, with built-in fetch
const form = new FormData();
form.append("file", new Blob([await readFile("contract.docx")]), "contract.docx");
const r = await fetch("https://privconvert.com/api/convert/word-to-pdf", {
  method: "POST",
  headers: { Authorization: `Bearer ${API_KEY}` },
  body: form,
});
if (!r.ok) throw new Error((await r.json()).error.message);
await writeFile("contract.pdf", Buffer.from(await r.arrayBuffer()));

What the clients add on top: files above 90 MB are uploaded in parts automatically, short 429 and 503 responses are retried with the server's Retry-After, and errors arrive as typed exceptions. Clients for PHP and Go work the same way.

Fonts decide how faithful the PDF is

Most "the PDF looks different" reports come down to fonts. A DOCX usually names its fonts without containing them, so any machine that converts it, including your own, substitutes a similar font when the original is missing. A slightly wider substitute changes line breaks, and changed line breaks change the page count.

If you control the templates, either use widely available fonts or embed them in the document (in Word: File, Options, Save, "Embed fonts in the file"). More layout pitfalls and fixes are in Word to PDF formatting tips.

Errors worth handling

Three outcomes are worth turning into a clear message for your user, because retrying them never helps:

  • 415 unsupported_type: the file is not really a Word document. Files are checked by their content, not their extension, so a renamed PDF or image is refused here. Old .rtf and .odt files have their own tools (rtf-to-pdf, odt-to-pdf).
  • 422 conversion_failed: the file was read but could not be converted, usually because it is damaged or password-protected.
  • 413 file_too_large: above your plan's size limit.

Rate limits and busy responses are a different category, and the clients already retry the short ones. If you write your own loop, which API errors to retry explains the difference between the two kinds of 429.

Many documents, or long ones

For a folder of documents, send up to 20 files in one request and get a ZIP back. A batch counts as one request against your per-minute limit:

zip_result = pc.convert_batch("word-to-pdf", ["a.docx", "b.docx", "c.docx"])
zip_result.save("pdfs.zip")
if zip_result.partial:
    print(zip_result.failed_count, "files failed, see PRIVCONVERT-ERRORS.txt in the ZIP")

For long documents, or when you do not want a web request waiting on a conversion, submit the file as an async job and collect the PDF later by polling or webhook. Webhooks vs polling covers which to pick, and converting thousands of files covers large runs.

What happens to the document

Contracts, payslips and medical letters are exactly the documents people convert to PDF, so it matters where they go. PrivConvert processes each file in memory and streams the PDF back in the same response. Nothing is written to disk, nothing is kept afterwards, and there is no stored copy to delete or to leak. The details are in a file conversion API that does not store files.

FAQ

Can I convert DOCX to PDF in Python without Microsoft Word?

Yes. The docx2pdf package drives an installed copy of Microsoft Word, so it only works on Windows and macOS desktops. On a Linux server or in a container, either run a headless office suite yourself or send the file to a conversion API. With the PrivConvert Python client it is one call: pc.convert("word-to-pdf", "file.docx").

Is there a pure JavaScript library that converts DOCX to PDF?

Not one that keeps the layout. Pure JavaScript libraries can read the text and basic formatting of a DOCX, but page layout (pagination, tables, headers, footers, fonts) needs a real layout engine. That is why Node.js projects usually call an office suite or an API.

Why does my PDF use different fonts than the Word document?

A DOCX file usually references fonts by name without containing them. If the converting machine does not have that font, a similar one is substituted, which can change line breaks and page count. Embedding fonts in Word (File > Options > Save > Embed fonts) or using widely available fonts avoids it.

What happens to the document after conversion?

With PrivConvert the file is processed in memory and the PDF is streamed back in the response. Nothing is written to disk and no copy is kept, so there is nothing to delete afterwards.

How do I convert many DOCX files at once?

Send up to 20 files in one batch request and get a ZIP back, or submit each file as an async job and collect the results by polling or webhook. A batch costs one slot of the per-minute rate limit.

Developer resources:
Official SDKs Error reference Plans & free trial Word to PDF online