DOCX to PDF in Node.js and Python: LibreOffice headless, and “soffice not found”.
To convert DOCX to PDF on a server, run LibreOffice headless: soffice --headless --convert-to pdf --outdir out quote.docx. XLSX and PPTX work the same way. Install it in the image your app runs in, give each conversion its own profile directory, install the fonts your documents use, and expect seconds per file, not milliseconds.
Facts checked
The command
LibreOffice opens the file the way its desktop app would and exports it with its PDF filter, so tables, headers, footers, page breaks and images come out close to what Word shows. On Debian and Ubuntu, the -nogui packages leave out the desktop parts. --outdir sets where the PDF goes; without it, LibreOffice writes to the working directory. The output keeps the input’s name with .pdf.
# Debian or Ubuntu: LibreOffice without its desktop parts, plus fonts that
# take the place of Arial, Times New Roman, Courier New and Calibri
sudo apt-get install -y --no-install-recommends \
libreoffice-writer-nogui libreoffice-calc-nogui libreoffice-impress-nogui \
fonts-liberation2 fonts-crosextra-carlito
# One file; the PDF is written to out/quote.pdf
soffice --headless --convert-to pdf --outdir out quote.docx
# With its own profile directory, so it can't collide with another conversion
soffice -env:UserInstallation=file:///tmp/lo-profile-1 --headless \
--convert-to pdf --outdir out quote.docx
# convert /srv/quote.docx as a Writer document -> /srv/out/quote.pdf using filter : writer_pdf_Export
# Spreadsheets and slides work the same way
soffice --headless --convert-to pdf --outdir out budget.xlsx deck.pptxWhat goes wrong on a server
- The profile directory. LibreOffice keeps a user profile, under the home directory by default, and one profile serves one running instance. We started three conversions at once with the same profile, twice: each time one exited with status 1 and wrote no PDF. With a profile each (
-env:UserInstallation=file:///tmp/...), all three worked. A read-only home directory fails too, which is why Lambda setups setHOME=/tmp. - One conversion per instance. Run one conversion per profile at a time. For parallel work, use several profiles, a small pool of workers, or a queue in front (background jobs).
- Fonts. A document set in Calibri or Arial on a server without those fonts gets substitutes, the text reflows and the page count can change. Install metric-compatible fonts (
fonts-crosextra-carlitofor Calibri,fonts-liberation2for Arial, Times New Roman and Courier New), or copy in fonts you hold a licence for and runfc-cache -f. - Cold start. Every new profile is created on first use. On our test machine, a one-page DOCX took about 8 seconds with a fresh profile each time and under 4 with libreoffice-convert’s
profileTemplateoption, which copies a ready profile. Keep the process or the profile warm if you convert often. - Timeouts and leftovers. Don’t let a stuck conversion hold the request. Kill it after a time limit, delete the temporary directory, and check that the PDF exists instead of trusting the exit status alone.
From Node.js: libreoffice-convert
The libreoffice-convert package writes the buffer to a temporary directory, runs soffice with a fresh profile for each call and reads the PDF back. It only looks in fixed install paths: on Linux /usr/bin/libreoffice, /usr/bin/soffice, /snap/bin/libreoffice, /opt/libreoffice/program/soffice and /opt/libreoffice7.6/program/soffice. Anywhere else, pass sofficeBinaryPaths. We ran this code against LibreOffice 26.8:
import fs from "node:fs";
import libre from "libreoffice-convert"; // npm install libreoffice-convert
// libreoffice-convert gives each call its own temporary LibreOffice profile.
function toPdf(input) {
return new Promise((resolve, reject) =>
libre.convertWithOptions(input, ".pdf", undefined, {
// It looks in fixed install paths, not in PATH: add yours if it's elsewhere.
sofficeBinaryPaths: process.env.SOFFICE ? [process.env.SOFFICE] : [],
execOptions: { timeout: 120_000 },
}, (err, pdf) => (err ? reject(err) : resolve(pdf))),
);
}
const pdf = await toPdf(fs.readFileSync("quote.docx"));
fs.writeFileSync("quote.pdf", pdf);From Python: subprocess
Python needs no library: call soffice with a profile inside a temporary directory, then read the file. docx2pdf is not an option on a server: it drives Microsoft Word and runs only on Windows and macOS. We ran this code against LibreOffice 26.8:
import os, pathlib, subprocess, tempfile
SOFFICE = os.environ.get("SOFFICE", "soffice")
def to_pdf(data: bytes, name: str = "input.docx") -> bytes:
with tempfile.TemporaryDirectory() as work:
src = pathlib.Path(work, name)
src.write_bytes(data)
profile = pathlib.Path(work, "profile").as_uri() # one profile per conversion
subprocess.run(
[SOFFICE, f"-env:UserInstallation={profile}", "--headless",
"--convert-to", "pdf", "--outdir", work, str(src)],
check=True, capture_output=True, timeout=120,
)
out = src.with_suffix(".pdf")
if not out.exists():
raise RuntimeError("LibreOffice wrote no PDF")
return out.read_bytes()
# pdf = to_pdf(open("quote.docx", "rb").read(), "quote.docx")“soffice not found” and “Could not find soffice binary”
Both mean LibreOffice isn’t installed where the code runs, or isn’t where the code looks. Installing the npm or pip package doesn’t install LibreOffice. In a container, check with soffice --version in the image. With libreoffice-convert, a LibreOffice outside the paths listed above needs sofficeBinaryPaths. If soffice runs but writes no PDF, look at the profile directory first (see above).
# libreoffice-convert (Node.js), when none of its paths exists
Error: Could not find soffice binary
# Check inside the image or on the server
soffice --versionOn Render, Railway, Lambda and Vercel
| Platform | What happens | Fix |
|---|---|---|
| Render (native runtime) † | LibreOffice isn’t among the tools Render’s native runtimes include | Deploy with a Dockerfile, such as the one below |
| Railway (Railpack) † † † † | LibreOffice isn’t in the image unless you add it to the final image | railpack.json: { "deploy": { "aptPackages": ["libreoffice-writer-nogui", "fonts-liberation2"] } }, or a Dockerfile |
| AWS Lambda † † † | A zip deploy is capped at 250 MB unzipped, layers included. The old 95 MB LibreOffice layer is “no longer maintained” | A container image (up to 10 GB) from public.ecr.aws/shelf/lambda-libreoffice-base. Its README recommends at least 3008 MB of memory and 45 seconds of timeout, with HOME=/tmp. Synchronous requests and responses are capped at 6 MB, so pass large files through S3 |
| Vercel functions † | 250 MB uncompressed (large functions up to 5 GB in beta), 2 GB of memory on Hobby, 4.5 MB request bodies by default | Vercel’s limits page covers Chromium, not LibreOffice, and the Lambda package asks for more memory (3008 MB) than Hobby allows. Convert elsewhere and call it, or use the pure-JS route below if its limits are acceptable |
† Competitor details come from each vendor’s own published pages on the dates shown; prices and plans change, so check the vendor before you decide. Render (native runtime) (2026-11-25) · Railway (Railpack) (2026-11-25) · Railway (Railpack) (2026-11-25) · Railway (Railpack) (2026-11-25) · Railway (Railpack) (2026-11-25) · AWS Lambda (2026-11-25) · AWS Lambda (2026-11-25) · AWS Lambda (2026-11-25) · Vercel functions (2026-11-25)
A Dockerfile for a Node app
On any host that builds from a Dockerfile, this gives the app LibreOffice for Word, Excel and PowerPoint files, and the replacement fonts. For Python, start from python:3.12-slim-bookworm with the same apt-get line.
FROM node:22-bookworm-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
libreoffice-writer-nogui libreoffice-calc-nogui libreoffice-impress-nogui \
fonts-liberation2 fonts-crosextra-carlito \
&& rm -rf /var/lib/apt/lists/*
# Fonts your documents use that you hold a licence for:
# COPY fonts/ /usr/share/fonts/truetype/custom/
# RUN fc-cache -f
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
# Fails the build if LibreOffice is missing
RUN soffice --version
CMD ["node", "server.js"]On AWS Lambda
@shelf/aws-lambda-libreoffice is the maintained route: a container image with LibreOffice and CJK and X11 fonts, plus a convertTo helper. This is its README’s example, shortened:
# Dockerfile: the container image @shelf/aws-lambda-libreoffice is built for
FROM public.ecr.aws/shelf/lambda-libreoffice-base:26.2-node22-x86_64
COPY ./ ${LAMBDA_TASK_ROOT}/
RUN pnpm install
CMD [ "handler.handler" ]
// handler.mjs: the input must already be in /tmp; the original is deleted afterwards
import { convertTo } from "@shelf/aws-lambda-libreoffice";
export const handler = async () => convertTo("document.docx", "pdf"); // returns /tmp/document.pdf
# Function settings from its README: HOME=/tmp, at least 3008 MB of memory,
# at least 45 seconds of timeout.Without LibreOffice: what the JavaScript libraries give up
The JavaScript and Python libraries we know of don’t lay a DOCX out the way Word does. Mammoth, the common choice, turns a DOCX into clean HTML from its structure, and its README says it does so “rather than attempting to exactly copy the styling (font, text size, colour, etc.)”. That suits documents you control, such as templates you designed for it. It doesn’t suit customer files that must look identical. We ran this on our test quote:
import mammoth from "mammoth"; // npm install mammoth
const { value: html } = await mammoth.convertToHtml({ path: "quote.docx" });
// <h1>Soumission 2026-118</h1><p>Réparation de l'élévateur, Québec. ...</p><table>...</table>
// Headings, paragraphs and the table survive; fonts, sizes, colours and page layout don't.
// Then render the HTML to PDF with a browser, or with the render service's pdf preset.| Approach | Fidelity | Where it runs |
|---|---|---|
| LibreOffice headless † † | Close to Word; differences come mostly from missing fonts | Any Linux with the packages, a container, or a Lambda container image |
| Gotenberg † | LibreOffice’s, behind an HTTP API (docker run --rm -p 3000:3000 gotenberg/gotenberg:9) | A container you run and keep up |
| mammoth, then HTML to PDF † | Structure only: headings, lists, tables, images, links. No page layout | Anywhere Node runs, including serverless |
| docx2pdf (Python) † | Word’s own | Windows or macOS with Microsoft Word installed |
Canner render service, convert | LibreOffice’s | A Canner project on Live or above |
† Competitor details come from each vendor’s own published pages on the dates shown; prices and plans change, so check the vendor before you decide. LibreOffice headless (2026-11-25) · LibreOffice headless (2026-11-25) · Gotenberg (2026-11-25) · mammoth, then HTML to PDF (2026-11-25) · docx2pdf (Python) (2026-11-25)
Or skip the binary: Canner’s render service
On a Canner project on Live or above, turn on Document rendering (PDF) in the project’s Services tab (or canner services on render), then redeploy. Your app gets CANNER_RENDER_SOCKET, a unix socket. The convert preset takes docx, xlsx, pptx, odt, ods, odp, rtf, doc, xls or ppt and returns a PDF made with LibreOffice. No package in your image, no profile directory, no cold start in your process.
The service runs on the same servers as your app, in Canada, with no network access, and keeps nothing: Canner counts usage and never records file names or content. This is the Node.js example from the services docs:
import net from "node:net";
export function render(input, preset, params = {}) {
return new Promise((resolve, reject) => {
const socket = net.connect(process.env.CANNER_RENDER_SOCKET);
const chunks = [];
socket.on("data", (d) => chunks.push(d));
socket.on("error", reject);
socket.on("close", () => {
const reply = Buffer.concat(chunks);
const end = reply.indexOf(10); // the header line ends at the first newline
if (end < 0) return reject(new Error("no reply"));
const head = JSON.parse(reply.subarray(0, end).toString());
if (!head.ok) return reject(new Error(`${head.code}: ${head.error}`));
resolve({ ...head, data: reply.subarray(end + 1, end + 1 + head.size) });
});
socket.write(JSON.stringify({ preset, size: input.length, params }) + "\n");
socket.end(input);
});
}
// const { data } = await render(fs.readFileSync("quote.docx"), "convert");
// fs.writeFileSync("quote.pdf", data);The same call from Python
The protocol is the same, so Python needs only the standard library:
import json, os, socket
def render(data: bytes, preset: str, **params) -> bytes:
s = socket.socket(socket.AF_UNIX)
s.connect(os.environ["CANNER_RENDER_SOCKET"])
s.sendall(json.dumps({"preset": preset, "size": len(data), "params": params}).encode() + b"\n")
s.sendall(data)
f = s.makefile("rb")
head = json.loads(f.readline())
if not head["ok"]:
raise RuntimeError(f'{head["code"]}: {head["error"]}')
return f.read(head["size"])
# pdf = render(open("quote.docx", "rb").read(), "convert")Limits, and when to use something else
| Canner render service | |
|---|---|
convert preset | docx, xlsx, pptx, odt, ods, odp, rtf, doc, xls, ppt to PDF; no parameters; the type is read from the bytes |
| Other presets | pdf (self-contained HTML to PDF) and screenshot (HTML to PNG) |
| Per job | 50 MB in, 200 MB out, 2 minutes |
| Rate | One job at a time per project, 20 a minute |
| Job minutes | 300 a month, shared with media processing and OCR by your organization’s projects. The Media add-on adds 600 a month for $9 |
Try it
Upload a Word, Excel or PowerPoint file and get the PDF back. This box runs the real service described above, is limited to 5 files an hour per visitor, and keeps nothing you upload.
Build your own
The demo above is this endpoint plus a bot check and an hourly limit per visitor, kept in the project’s cache. It takes the file as the request body, scans it with CANNER_SCAN_SOCKET, sends it to CANNER_RENDER_SOCKET with the convert preset, and returns the PDF. The two socket functions are the docs examples, unchanged. Turn on Virus scan and Document rendering (PDF), then redeploy.
- Scan first. Office files can carry malware. Anything other than
stream: OKorFOUNDmeans the file was not scanned, and the code treats it as an error, not as clean. - Limit each visitor. A public endpoint like this one needs a per-visitor limit (by IP or by account) before it goes live, or anyone can spend your organization’s job minutes.
- Expect `busy`. The service runs one job at a time per project. The code answers
429so the client can retry; for steady volume, put uploads in a queue (background jobs). - Nothing on disk. The file stays in memory and goes straight back. If you keep the PDFs, Files storage scans what you upload to it.
// server.js: POST a DOCX, XLSX or PPTX as the request body, get the PDF back.
// Needs Document rendering (PDF) and Virus scan turned on in the Services tab.
import http from "node:http";
import net from "node:net";
const MAX = 50 * 1024 * 1024; // the render service takes up to 50 MB
// scan() is the Node.js example from /docs/services#scan
function scan(buffer) {
return new Promise((resolve, reject) => {
const socket = net.connect(process.env.CANNER_SCAN_SOCKET);
const out = [];
socket.on("data", (d) => out.push(d));
socket.on("error", reject);
socket.on("close", () => {
const verdict = Buffer.concat(out).toString().replace(/\0$/, "").trim();
if (verdict === "stream: OK") return resolve({ clean: true });
const found = verdict.match(/^stream: (.+) FOUND$/);
if (found) return resolve({ clean: false, signature: found[1] });
reject(new Error(verdict || "scan failed")); // not scanned: do not treat as clean
});
socket.write("zINSTREAM\0");
for (let i = 0; i < buffer.length; i += 65536) {
const part = buffer.subarray(i, i + 65536);
const size = Buffer.alloc(4);
size.writeUInt32BE(part.length);
socket.write(size);
socket.write(part);
}
socket.end(Buffer.alloc(4)); // a zero-length chunk ends the stream
});
}
// render() is the Node.js example from /docs/services#render
function render(input, preset, params = {}) {
return new Promise((resolve, reject) => {
const socket = net.connect(process.env.CANNER_RENDER_SOCKET);
const chunks = [];
socket.on("data", (d) => chunks.push(d));
socket.on("error", reject);
socket.on("close", () => {
const reply = Buffer.concat(chunks);
const end = reply.indexOf(10); // the header line ends at the first newline
if (end < 0) return reject(new Error("no reply"));
const head = JSON.parse(reply.subarray(0, end).toString());
if (!head.ok) return reject(new Error(`${head.code}: ${head.error}`));
resolve({ ...head, data: reply.subarray(end + 1, end + 1 + head.size) });
});
socket.write(JSON.stringify({ preset, size: input.length, params }) + "\n");
socket.end(input);
});
}
function readBody(req) {
return new Promise((resolve, reject) => {
const chunks = [];
let size = 0;
req.on("data", (d) => {
size += d.length;
if (size <= MAX) chunks.push(d);
});
req.on("end", () => (size > MAX ? reject(new Error("too_large: 50 MB at most")) : resolve(Buffer.concat(chunks))));
req.on("error", reject);
});
}
http.createServer(async (req, res) => {
if (req.method !== "POST" || req.url !== "/convert") return res.writeHead(404).end();
// A public endpoint needs a per-visitor limit here, such as a few files an hour per IP.
try {
const file = await readBody(req);
const verdict = await scan(file);
if (!verdict.clean) return res.writeHead(422).end(`Rejected: ${verdict.signature}`);
const { data } = await render(file, "convert");
res.writeHead(200, { "content-type": "application/pdf" });
res.end(data); // nothing is written to disk
} catch (err) {
const code = err.message.split(":")[0];
const status = { too_large: 413, unsupported_input: 415, busy: 429, rate: 429 }[code] ?? 500;
res.writeHead(status).end(err.message);
}
}).listen(process.env.PORT || 3000);
// curl --data-binary @quote.docx -o quote.pdf https://your-app.example/convertQuestions
How do I convert DOCX to PDF in Node.js?
Install LibreOffice on the server and call it, directly with execFile or through the libreoffice-convert package: soffice --headless --convert-to pdf --outdir out file.docx. Pure-JS libraries such as mammoth convert the structure to HTML but not Word’s page layout.
How do I convert DOCX to PDF with LibreOffice on Linux?
apt-get install libreoffice-writer-nogui, then soffice --headless --convert-to pdf --outdir out file.docx. Add -env:UserInstallation=file:///tmp/some-dir so each conversion has its own profile, and install the fonts your documents use.
Why does soffice exit without writing a PDF?
Most often another conversion is using the same profile directory. Give each conversion its own with -env:UserInstallation. Also check that the home directory is writable and that the input isn’t damaged.
Why does my PDF look different from Word?
Usually fonts. The server substitutes fonts it doesn’t have, which changes line breaks and page count. Install metric-compatible fonts such as Carlito (Calibri) and Liberation (Arial, Times New Roman, Courier New), or the licensed originals.
How much memory does LibreOffice need on Lambda?
The @shelf/aws-lambda-libreoffice README recommends at least 3008 MB of memory and at least 45 seconds of timeout, from a container image.
Related
- GuideHTML to PDF in Node.js: Puppeteer in production
- GuideRedis “connect ECONNREFUSED 127.0.0.1:6379” in production
- Guidespawn ffmpeg ENOENT and “Cannot find ffmpeg”
- GuideScan uploaded files for viruses with ClamAV
- RubyRuby on Rails hosting in Canada
- PythonDjango hosting in Canada
Office files to PDF, in Canada, with no LibreOffice in your image.
Document rendering comes with Live: create an account, move your project to Live, turn the service on and redeploy. Files are converted on the same servers as your app and nothing is kept.