WORD2PDF = 17
word = win32com.client.Dispatch("Word.Application")
word.Visible = False
word.DisplayAlerts = 0
converted_files = []
file_paths = [
p.resolve()
for p in map(Path, file_paths)
if not p.name.startswith("~") and p.suffix.lower() in (".doc", ".docx")
]
if output_path:
output_path = Path(output_path).resolve()
else:
output_path = file_paths[0].parent
output_path.mkdir(parents=True, exist_ok=True)
for doc_filepath in tqdm(sorted(file_paths), "Converting Word to PDF"):
pdf_filepath = output_path / (doc_filepath.stem + ".pdf")
try:
doc = word.Documents.Open(str(doc_filepath), ReadOnly=1)
doc.SaveAs(str(pdf_filepath), FileFormat=WORD2PDF)
converted_files.append(str(pdf_filepath))
except Exception as e:
raise ValueError(f"Failed to convert {doc_filepath}: {e}")
finally:
doc.Close(False)
except Exception as e:
raise ValueError(f"Failed to convert {doc_filepath}: {e}")
finally:
word.Quit()
pythoncom.CoUninitialize()
return converted_files
Assistant
Short answer
Yes – if Word was already running when your script starts, your current code will attach to that instance and word.Quit() will close every Word window the user has open.
Why it happens win32com.client.Dispatch("Word.Application") looks for an existing instance of Word first.
• If it finds one → it returns a handle to that process.
• If it does not → it launches a new Word process.
So, when you later call word.Quit(), you terminate whichever instance you attached to—possibly the one the user was working in.
How to avoid killing the user’s Word session
Create a brand-new instance instead of attaching to the first one you find.
Use DispatchEx, which always spawns a new instance:
python
word = win32com.client.DispatchEx("Word.Application") # <-- new instance
Alternatively, detect whether Word was running before you started; only quit the
instance if you created it:
python
import win32com.client, pythoncom, psutil
def _is_word_running():
return any(p.name().lower() == "winword.exe" for p in psutil.process_iter())
was_running_at_start = _is_word_running()
word = win32com.client.Dispatch("Word.Application") # may attach or create
...
finally:
if not was_running_at_start: # we created it ⇒ safe to quit
word.Quit()
Or, simply never call Quit() at all; instead just doc.Close(False) for every
document you open. Word will stay alive (and released) after your script ends,
but that is usually harmless.
from pathlib import Path
from tqdm import tqdm
import pythoncom, win32com.client
PDF_FORMAT = 17 # Word constant
def convert_doc2pdf(files, out_dir=None):
pythoncom.CoInitialize()
word = None
converted = []
try:
# ALWAYS start a brand-new Word instance so we can kill it safely
word = win32com.client.DispatchEx("Word.Application")
word.Visible = False
word.DisplayAlerts = 0
paths = [p for p in map(Path, files)
if p.suffix.lower() in (".doc", ".docx") and not p.name.startswith("~")]
# Resolve output directory
out_dir = Path(out_dir).resolve() if out_dir else paths[0].parent
out_dir.mkdir(parents=True, exist_ok=True)
for doc_path in tqdm(paths, desc="Converting Word → PDF"):
pdf_path = out_dir / (doc_path.stem + ".pdf")
doc = None
try:
doc = word.Documents.Open(str(doc_path), ReadOnly=1)
doc.SaveAs(str(pdf_path), FileFormat=PDF_FORMAT)
converted.append(str(pdf_path))
finally:
if doc:
doc.Close(False)
finally:
if word: # only affects *this* instance
word.Quit()
pythoncom.CoUninitialize()
return converted
Key take-aways
• Dispatch may hijack the user’s Word session; DispatchEx gives you your own.
• If you must use Dispatch, track whether Word was running beforehand and only quit when you’re sure you created that instance.