Join more Words documents in one PDF

Hello, this code is still working in 2024. I gave it a refresh as I needed it myself. I needed to join more word documents, docx, into one pdf for more convenience and I did it with the following code.

With this code I joined different docx (Word) files in one pdf

I did it because I wanted to join different docx in one file. I could’nt save the images in one docx file, but only text. So I decided to find a different solution. First I transformed the docx files in pdf (with the python code, obviously, not manually) and then I joined the pdf files in one file. So I made what I needed even if the result in not a docx files, but a pdf… So I cannot change the final output file (but I can always change the single docx files and then use again the code to Join them). I wish this code can be helpful for you as it has been for me.

You have to first install the comtypes library

pip install comtypes

import os
import glob
import comtypes.client
from PyPDF2 import PdfMerger


def docxs_to_pdf():
    """Converts all word files in pdfs and append them to pdfslist"""
    word = comtypes.client.CreateObject('Word.Application')
    pdfslist = PdfMerger()
    x = 0
    for f in glob.glob("*.docx"):
        input_file = os.path.abspath(f)
        output_file = os.path.abspath("demo" + str(x) + ".pdf")
        # loads each word document
        doc = word.Documents.Open(input_file)
        doc.SaveAs(output_file, FileFormat=16+1)
        doc.Close() # Closes the document, not the application
        pdfslist.append(open(output_file, 'rb'))
        x += 1
    word.Quit()
    return pdfslist

def joinpdf(pdfs):
    """Unite all pdfs"""
    with open("result.pdf", "wb") as result_pdf:
        pdfs.write(result_pdf)

def main():
    """docxs to pdfs: Open Word, create pdfs, close word, unite pdfs"""
    pdfs = docxs_to_pdf()
    joinpdf(pdfs)

main()

Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.