# Convert PDF to Word in Python

Convert PDF files to editable Word documents (DOCX) from a Python script with the switchfile SDK. Scanned PDFs work too.

This guide turns a PDF into an editable Word file (`.docx`) from a Python script. The conversion runs on our server through the [PDF to Word API](https://switchfile.io/pdf-to-word-api), so you install no converter, and scanned PDFs work the same way as digital ones. Text comes back as paragraphs you can edit, and tables become Word tables.

## 1. Install the SDK and set the key

The SDK needs Python 3.10 or later.

```bash
pip install switchfile-sdk
export SWITCHFILE_API_KEY="sf_live_..."
```

Create the key in the dashboard under [API keys](https://switchfile.io/dashboard/keys). A script can also [get a key without a browser](https://switchfile.io/docs/authentication#get-an-api-key-without-a-browser). A free account converts 20 files and 20 minutes of conversion time a day, whichever runs out first, each PDF with up to 50 pages.

## 2. Convert one PDF

pdf_to_word.py:

```python
import os

import switchfile

switchfile.configure(api_key=os.environ["SWITCHFILE_API_KEY"])
conversion = switchfile.convert("report.pdf", "docx")
result = conversion["result"]
if result["incomplete"]:
    print("Not saved, the result is incomplete:", *result.get("notes", []), sep="\n")
else:
    switchfile.download(conversion, "report.docx")
    print(f"report.docx is ready, {conversion['credits']} credits")
```

`convert` sends the PDF, waits until the Word file is ready and returns the [conversion](https://switchfile.io/docs/simple-api#the-conversion-object). `download` saves the result, but only after the script has checked that no page is missing, see [Check the result](https://switchfile.io/docs/pdf-to-word-python#result). Large files go through an [upload](https://switchfile.io/docs/uploads) on their own, so the same call works for a PDF of any size up to the [limits](https://switchfile.io/docs/limits#sizes).

## 3. Set options

Options go in a dict as the third argument:

```python
conversion = switchfile.convert("scan.pdf", "docx", {"pages": "1-10", "ocr_language": "deu"})
```

| Option | What it does |
| --- | --- |
| `pages` | The pages to convert, for example `1-3` or `1,3,5` |
| `ocr_language` | The language of scanned pages, for example `deu` for German. Without it, the language is detected on its own |
| `prioritize_visual_appearance` | `True` places all text where it sits on the page, with graphics as a background. Use it when the Word file has to look like the PDF |
| `password` | The password of a protected PDF |

Every option of the target format is listed under [Formats and options](https://switchfile.io/docs/formats/docx).

## 4. Convert a folder of PDFs

folder_to_word.py:

```python
import os
from pathlib import Path

import switchfile

switchfile.configure(api_key=os.environ["SWITCHFILE_API_KEY"])
for pdf in sorted(Path("pdfs").glob("*.pdf")):
    target = pdf.with_suffix(".docx")
    if target.exists():
        continue
    try:
        conversion = switchfile.convert(pdf, "docx")
    except switchfile.SwitchfileError as e:
        print(f"{pdf.name}: {e.code} {e.message}")
        continue
    result = conversion["result"]
    if result["incomplete"]:
        print(f"{pdf.name}: incomplete, not saved", *result.get("notes", []), sep="\n  ")
        continue
    switchfile.download(conversion, target)
    print(f"{pdf.name} -> {target.name}")
```

Files that already have a Word file are skipped, so you can run the script again after an error. An incomplete result is not saved, so the next run converts that PDF again. Each call waits for its result. To send many files at once, put up to 50 of them into a [batch](https://switchfile.io/docs/simple-api#batches).

## 5. Check the result

`conversion["result"]["incomplete"]` is `True` when pages are missing from the Word file or were added as images without text. `conversion["result"]["notes"]` then names the pages. The examples above do not save such a file. To keep it anyway, save it under a name that marks it:

```python
result = conversion["result"]
if result["incomplete"]:
    print("\n".join(result.get("notes", [])))
    switchfile.download(conversion, "report.incomplete.docx")
```

The first 5 incomplete results of a day are free, see [Errors](https://switchfile.io/docs/errors#incomplete).

## Errors

A failed request or conversion raises `switchfile.SwitchfileError`, with a stable code in `e.code`:

| `e.code` | Meaning | What to do |
| --- | --- | --- |
| `PASSWORD_PROTECTED` | The PDF needs a password | Pass it in the `password` option |
| `INPUT_TOO_LARGE` | The PDF has more pages than allowed: 50 without credits, 300 with credits | Convert it in parts with `pages`, or add credits |
| `CREDITS_EXCEEDED` | HTTP 402: the free daily quota is used up (20 files or 20 minutes of conversion time, whichever runs out first) and there are not enough credits | Wait until midnight UTC, or add credits |
| `INVALID_INPUT` | The file could not be read | Check that it is a PDF and not damaged |

All codes are on the page [Errors](https://switchfile.io/docs/errors).

## Without storage

`convert_without_storage` sends the PDF and gets the Word file back in the same response. Neither file is written to our file storage or database. This works for files up to 50 MB.

```python
from pathlib import Path

result = switchfile.convert_without_storage("contract.pdf", "docx")
if result.incomplete:
    print("Not saved, the result is incomplete:", *result.notes, sep="\n")
else:
    Path("contract.docx").write_bytes(result.data)
```

More in [Converting without storage](https://switchfile.io/docs/no-store).

## What it costs

PDF to Word uses 1 credit per started minute of conversion time, at least 2 per file. The free daily quota comes first. `switchfile.estimate("report.pdf", "docx")` returns the credits and the price of a file before you convert it. Prices are on the [pricing page](https://switchfile.io/pricing).

## The same in Node.js

pdf-to-word.mjs:

```js
// npm i switchfile
import Switchfile from "switchfile";

const switchfile = new Switchfile({ apiKey: process.env.SWITCHFILE_API_KEY });
const conversion = await switchfile.convert("report.pdf", "docx");
await switchfile.download(conversion, "report.docx");
```

Other languages and plain HTTP requests are on the [PDF to Word API](https://switchfile.io/pdf-to-word-api) page and in the [SDK overview](https://switchfile.io/docs/sdks).

## Next

- [Simple API](https://switchfile.io/docs/simple-api): Convert a file with one request to the switchfile simple API (v1). Synchronous and asynchronous requests, the conversion object, batches, ZIP files and cost estimates.
- [Errors](https://switchfile.io/docs/errors): Error formats of the simple API and of jobs and tasks, every error code with its HTTP status, and what to do about it.
