Problem when trying to convert .docx files to .pdf

1.3k Views Asked by At

I'm trying to create a simple docx to pdf converter and it throws me this problem:

Exception has occurred: com_error (-2147352567, 'Exception occurred.', (0, 'Microsoft Word', 'Sorry, we couldn’t find your file. Is it possible it was moved, renamed or deleted?\r (C:\Windows\system32\document1.docx)', 'wdmain11.chm', 24654, -2146823114), None)

import os
filesToConvertPath = os.getcwd() + r'\docxFiles'
folderWithPdfFIles = os.getcwd() + r'\pdfFiles'
for i in range(len(os.listdir(filesToConvertPath))):
    convert(os.listdir(filesToConvertPath)[i], folderWithPdfFIles)

.py file is in the main folder, with 2 subfolders, docxFiles and pdfFiles

1

There are 1 best solutions below

0
henrylin03 On

Recommend:

  1. Replacing os.getcwd() to ensure you get the folder of your .py and not of Python:
import os
from pathlib import Path
from docx2pdf import convert

current_folder = Path(__file__).parent.resolve()

filesToConvertPath = os.path.join(current_folder, "docxFiles")
folderWithPdfFIles = os.path.join(current_folder, "pdfFiles")  
  1. (Optional) Replacing looping over Word docs to providing input and output folder. docx2pdf allows batch converting and outputting using folders (as well as single files) (documentation).

Replace:

for i in range(len(os.listdir(filesToConvertPath))):
    convert(os.listdir(filesToConvertPath)[i], folderWithPdfFIles)

With:

convert(filesToConvertPath, folderWithPdfFIles)