Created
May 17, 2022 02:25
-
-
Save dalejfer/d2dd0c3cce042db512eabc69448ed146 to your computer and use it in GitHub Desktop.
Using COM interop with pywin32 to open files (and edit and save, save as...) with MS Word (and other office apps). Here we'll open a docx file and save it as pdf.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Using COM interop with pywin32 to open files (and edit and save, save as...) | |
with MS Word (and other office apps). Here we'll open a docx file and save | |
it as pdf. | |
You need to have office installed. | |
Source: http://timgolden.me.uk/python/win32_how_do_i/generate-a-static-com-proxy.html | |
static - dynamic proxy to office COM obj. | |
""" | |
import win32com.client | |
from pathlib import WindowsPath | |
wdFormatPDF = 17 | |
in_file = WindowsPath(r".\myfile.docx").resolve() | |
out_file = in_file.with_suffix(".pdf") | |
#print(out_file) | |
# opens the word application | |
word = win32com.client.gencache.EnsureDispatch ("Word.Application") | |
# we get the document object | |
doc = word.Documents.Open(str(in_file)) | |
# if you want to make the window visible | |
# word.Visible = True | |
# save as pdf | |
doc.SaveAs(str(out_file), FileFormat=wdFormatPDF) | |
doc.Close() | |
word.Quit() # will quit every open word application! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment