Convert word files to pdfs and then merge pdfs

Viewed 32

I'm trying to convert some words to pdfs and then merge the pdfs. I'm having trouble with the merging part where I get an empty pdf file. Because I'm doing the merging at the directory that has the word files I use path.endwith(".pdf") to merge only the pdf files. The code is as below:

import os
import win32com.client
import re
from PyPDF2 import PdfMerger

path = (r'C:\Mytest\trials')
word_file_names = []
word = win32com.client.Dispatch('Word.Application')
for dirpath, dirnames, filenames in os.walk(path):
    for f in filenames:  
        if f.lower().endswith(".docx") :
            new_name = f.replace(".docx", ".pdf")
            in_file =(dirpath + '/'+ f)
            new_file =(dirpath + '/' + new_name)
            doc = word.Documents.Open(in_file)
            doc.SaveAs(new_file, FileFormat = 17)
            doc.Close()
        if f.lower().endswith(".doc"):
            new_name = f.replace(".doc", ".pdf")
            in_file =(dirpath +'/' + f)
            new_file =(dirpath +'/' + new_name)
            doc = word.Documents.Open(in_file)
            doc.SaveAs(new_file, FileFormat = 17)
            doc.Close()
word.Quit()



merger = PdfMerger()
pdfs = os.scandir(r'C:\Mytest\trials')

for pdf in pdfs:
    if path.endswith(".pdf"):
        merger.append(pdf)

merger.write("merged.pdf")
merger.close()
1 Answers

I had found a way that worked. Sorry for not posting it sooner.

merger = PyPDF2.PdfFileMerger()

for file in os.listdir(os.curdir):
    if file.endswith(".pdf"):
        merger.append(file)
merger.write("merged.pdf")
merger.close()
Related