Wednesday, October 2, 2013

Convert Microsoft Word files to PDF with DOCXtoPDF

By Vasudev Ram


Building upon my recent post, here:

Extract text from Word .docx files with python-docx,

I came up with the idea of combining that DOCX text extraction functionality of python-docx with my xtopdf toolkit, to create a program that can convert the text in Microsoft Word DOCX files to PDF format.

[ Note: The conversion has some limitations. E.g. fonts, tables, etc. from the input are not preserved in the output. ]

Here is the program, called It will become a part of my xtopdf toolkit.


# Author: Vasudev Ram -
# Copyright 2012 Vasudev Ram,

# This is open source code, released under the New BSD License -
# see .

import sys
import os
import os.path
import string
from textwrap import TextWrapper
from docx import opendocx, getdocumenttext
from PDFWriter import PDFWriter

def docx_to_pdf(infilename, outfilename):

    # Extract the text from the DOCX file object infile and write it to 
    # a PDF file.

        infil = opendocx(infilename)
    except Exception, e:
        print "Error opening infilename"
        print "Exception: " + repr(e) + "\n"

    paragraphs = getdocumenttext(infil)

    pw = PDFWriter(outfilename)
    pw.setFont("Courier", 12)
    pw.setHeader("DOCXtoPDF - convert text in DOCX file to PDF")
    pw.setFooter("Generated by xtopdf and python-docx")
    wrapper = TextWrapper(width=70, drop_whitespace=False)

    # For Unicode handling.
    new_paragraphs = []
    for paragraph in paragraphs:

    for paragraph in new_paragraphs:
        lines = wrapper.wrap(paragraph)
        for line in lines:

def usage():

    return "Usage: python infile.docx outfile.txt\n"

def main():

        # Check for correct number of command-line arguments.
        if len(sys.argv) != 3:
            print "Wrong number of arguments"
            print usage()
        infilename = sys.argv[1]
        outfilename = sys.argv[2]

        # Check for right infilename extension.
        infile_ext = os.path.splitext(infilename)[1]
        if infile_ext.upper() != ".DOCX":
            print "Input filename extension should be .DOCX"
            print usage()

        # Check for right outfilename extension.
        outfile_ext = os.path.splitext(outfilename)[1]
        if outfile_ext.upper() != ".PDF":
            print "Output filename extension should be .PDF"
            print usage()

        docx_to_pdf(infilename, outfilename)

    except Exception, e:
        sys.stderr.write("Error: " + repr(e) + "\n")

if __name__ == '__main__':


To run DOCXtoPDF, give a command of the form:

python infilename.docx outfilename.pdf

After this, the text content of the DOCX file will be in the PDF file.

- Enjoy.

Read other posts about xtopdf on this blog.
Read other posts about Python on this blog.

- Vasudev Ram - Dancing Bison Enterprises

Training or consulting inquiry

O'Reilly 50% Ebook Deal of the Day


Anonymous said...


Thanks for this post! I think you have a typo in usage: you should change outfile.txt to outfile.pdf

Vasudev Ram said...


>Thanks for this post!

You're welcome.

>I think you have a typo in usage: you should change outfile.txt to outfile.pdf

You're right, the message in the usage() function should say outfile.pdf. Thanks. I won't change it in the post, though, since it is minor, and to do so would mean the post would go to the feeds again. Will just leave the comment here. Developers would spot the typo anyway.