DEV Community

Allen Yang
Allen Yang

Posted on

Python Guide to Converting Word Documents and PDFs

Python Guide to Converting Word Documents and PDFs

Word and PDF are two of the most common document formats, but they serve different purposes. Word is designed for editing and layout, while PDF is meant for distribution and printing. In day-to-day work you often need to move between them — exporting a contract or report from Word to PDF to send to a client, or converting a received PDF back to Word for further editing. Doing this manually, file by file, is tedious, especially when you have dozens or hundreds of documents.

Python can handle such conversions in batch, processing an entire folder with a single script. Using Spire.Doc for Python and Spire.PDF for Python, this article walks through both directions — Word to PDF and PDF to Word — along with common conversion options.

Setting Up the Environment

Install the library that matches your needs. For Word-to-PDF conversion, install Spire.Doc:

pip install Spire.Doc
Enter fullscreen mode Exit fullscreen mode

For PDF-to-Word conversion, install Spire.PDF:

pip install Spire.PDF
Enter fullscreen mode Exit fullscreen mode

If you need both directions, install them together:

pip install Spire.Doc Spire.PDF
Enter fullscreen mode Exit fullscreen mode

Each library brings its own document object: Spire.Doc provides Document, and Spire.PDF provides PdfDocument.

Converting a Word Document to PDF

Word-to-PDF conversion is one of the most common tasks — for example, freezing an editable draft into a final, tamper-resistant version. With Spire.Doc, the process is straightforward: load the Word document, then save it in PDF format.

from spire.doc import *
from spire.doc.common import *

# Load a Word document
document = Document()
document.LoadFromFile("annual_report.docx")

# Save it as PDF
document.SaveToFile("annual_report.pdf", FileFormat.PDF)
document.Close()
Enter fullscreen mode Exit fullscreen mode

The first argument of SaveToFile() is the output path; the second specifies the output format. Passing FileFormat.PDF tells the library to perform the full Word-to-PDF conversion, preserving layout elements such as pagination, fonts, and images.

If the source is an older .doc file, it is safer to specify the format explicitly when loading:

document.LoadFromFile("legacy_document.doc", FileFormat.Doc)
Enter fullscreen mode Exit fullscreen mode

Controlling the Conversion with Parameters

Saving directly usually produces good results, but some scenarios require finer control over the output. This is where the ToPdfParameterList object comes in.

Keeping Bookmarks in the PDF

For long documents, you may want readers to jump between sections as easily as they use a table of contents. You can generate bookmarks from the document headings:

from spire.doc import *
from spire.doc.common import *

document = Document()
document.LoadFromFile("user_manual.docx")

# Create conversion parameters
params = ToPdfParameterList()
# Generate bookmarks from headings
params.CreateWordBookmarks = True
params.CreateWordBookmarksUsingHeadings = True

document.SaveToFile("user_manual.pdf", params)
document.Close()
Enter fullscreen mode Exit fullscreen mode

When CreateWordBookmarksUsingHeadings is True, bookmarks are generated from the document's heading styles; when set to False, only explicit Word bookmarks in the document are used.

Embedding Fonts for Consistent Rendering

If the machine that opens the converted PDF does not have the fonts used in the document, the text can be substituted and the layout may break. Embedding the fonts into the PDF avoids this:

document = Document()
document.LoadFromFile("flyer.docx")

params = ToPdfParameterList()
# Embed all fonts into the PDF
params.IsEmbeddedAllFonts = True

document.SaveToFile("flyer.pdf", params)
document.Close()
Enter fullscreen mode Exit fullscreen mode

The trade-off is a larger file size, which is usually acceptable for formal documents where layout consistency matters.

Protecting the PDF with a Password

If a PDF should only be viewable by specific people, you can encrypt it during conversion:

from spire.doc.common import *

document = Document()
document.LoadFromFile("business_plan.docx")

params = ToPdfParameterList()
params.PdfSecurity.Encrypt(
    "owner123",
    "user123",
    PdfPermissionsFlags.Default,
    PdfEncryptionKeySize.Key128Bit
)

document.SaveToFile("business_plan.pdf", params)
document.Close()
Enter fullscreen mode Exit fullscreen mode

The first two arguments of PdfSecurity.Encrypt() are the owner password and the user password. The owner password grants full control (including permission changes), while the user password is required to open the file.

Converting a PDF Document to Word

The reverse direction is equally common: when PDF content needs to be edited, quoted, or re-laid-out, converting it back to Word is the most convenient route. Using Spire.PDF's PdfDocument object, you load the PDF and save it as a Word file.

from spire.pdf import *
from spire.pdf.common import *

# Load a PDF document
pdf = PdfDocument()
pdf.LoadFromFile("requirements.pdf")

# Save as .docx
pdf.SaveToFile("requirements.docx", FileFormat.DOCX)
pdf.Close()
Enter fullscreen mode Exit fullscreen mode

FileFormat.DOCX targets the modern Word format. If the recipient uses an older Word version, you can switch to FileFormat.DOC to produce a .doc file:

pdf.SaveToFile("requirements.doc", FileFormat.DOC)
Enter fullscreen mode Exit fullscreen mode

A note on expectations: a PDF does not store semantic information such as paragraphs or tables, so the converted Word file is an editable text layout. Content that was an image in the PDF stays an image after conversion; it does not become editable text automatically. This type of conversion suits scenarios where you need to edit the text, not where you need to edit image content.

Setting Properties on the Converted Word Document

The output Word document inherits some basic properties, but you can also specify metadata such as title, author, and subject in advance through PdfToDocConverter:

from spire.pdf import *
from spire.pdf.common import *

# Create the converter and specify the input PDF
converter = PdfToDocConverter("research_report.pdf")
# Set properties for the output document
converter.DocxOptions.Title = "Research Report"
converter.DocxOptions.Authors = "Marketing Team"
converter.DocxOptions.Subject = "Q3 User Survey"

# Convert to .docx
converter.SaveToDocx("research_report.docx")
Enter fullscreen mode Exit fullscreen mode

DocxOptions supports several fields — title, author, subject, category, and more — which is useful for filling in consistent metadata when exporting documents in batch.

Practical Tips

  • For batch conversion, iterate over a directory with os.listdir(), calling LoadFromFile() and SaveToFile() in a loop to process an entire folder at once.
  • Font issues in Word-to-PDF conversion appear most often with CJK documents; prefer IsEmbeddedAllFonts or SetCustomFontsFolders() to point the converter at the needed fonts.
  • If the source PDF is a scan (pages that are entirely images), the converted Word file cannot be edited as text — OCR is required first.
  • Call Close() after conversion to release file handles and avoid locking files that later writes may need.

Conclusion

This article covered the complete flow of converting between Word and PDF with Python. Spire.Doc handles Word-to-PDF conversion through SaveToFile() with FileFormat.PDF, and ToPdfParameterList provides control over bookmarks, font embedding, and encryption. Spire.PDF handles the reverse direction via FileFormat.DOCX or PdfToDocConverter, including document properties. Both directions support batch processing, so you can leave tedious format conversions to a script.

Top comments (0)