convert docx to pdf in python
three ways to turn a word document into a pdf from python: call an http api, run libreoffice headless, or drive microsoft word with docx2pdf. each works; they differ in what you have to install and run.
which option fits
| option | needs | runs on linux servers | typical time per document | cost |
|---|---|---|---|---|
| files.miami api | requests and an api key | yes | 0.15 s | $0.005 per conversion |
| libreoffice headless | libreoffice installed (several hundred mb) | yes | seconds; starts libreoffice each call | free; your servers |
| docx2pdf | microsoft word installed | no (windows and macos only) | seconds; drives word | free; needs a word licence |
1. with an http api
send the file as multipart form data and write the response to disk. nothing to install besides requests; it accepts .docx, .doc, .odt and .rtf.
in our benchmark of 100 docx files, files.miami returned a typical pdf in 0.15 s, against 1.2 s for convertapi and 3.6 s for cloudconvert: 16× faster on average.
import os, requests
with open("document.docx", "rb") as file:
response = requests.post("https://api.files.miami/v1",
headers={"Authorization": f"Bearer {os.environ['FILES_MIAMI_API_KEY']}"},
files={"file": file})
response.raise_for_status()
with open("document.pdf", "wb") as output:
output.write(response.content)to convert a folder, send requests in parallel. the api has no concurrency limit, so the thread count is up to you.
import os, pathlib, requests
from concurrent.futures import ThreadPoolExecutor
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['FILES_MIAMI_API_KEY']}"
def convert(path):
with open(path, "rb") as file:
response = session.post("https://api.files.miami/v1", files={"file": file})
response.raise_for_status()
path.with_suffix(".pdf").write_bytes(response.content)
with ThreadPoolExecutor(max_workers=16) as pool:
list(pool.map(convert, pathlib.Path("documents").glob("*.docx")))2. with libreoffice headless
if libreoffice is installed, its soffice command converts without opening a window:
import subprocess
subprocess.run(["soffice", "--headless", "--convert-to", "pdf",
"--outdir", "out", "document.docx"], check=True)each call starts libreoffice, which takes a few seconds. calls that share a user profile can’t run at the same time, so for parallel work give each worker its own profile with -env:UserInstallation=file:///tmp/lo-profile-<n>. in containers you’ll also need the fonts your documents use, or the layout will change.
3. with docx2pdf
the docx2pdf package asks an installed copy of microsoft word to do the conversion, so the output matches word exactly. it only works on windows and macos with word installed, which rules it out for most servers.
from docx2pdf import convert
convert("document.docx", "document.pdf")