Created
September 1, 2020 23:46
-
-
Save elibroftw/5d048a6fededb730e3f2e95793212046 to your computer and use it in GitHub Desktop.
Word to PDF Generater
This file contains hidden or 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
import os | |
import pythoncom | |
import win32com | |
import win32com.client as client | |
from shutil import copyfile, rmtree | |
import threading | |
from contextlib import suppress | |
wdFormatPDF = 17 | |
with open('note_paths.txt') as f: | |
files = f.read().splitlines() | |
# or define files = [] manually | |
pythoncom.CoInitialize() | |
word = client.dynamic.Dispatch('Word.Application') | |
# debugging purposes | |
# word = client.DispatchEx('Word.Application') | |
# word = comtypes.client.CreateObject('Word.Application') | |
def convert_to_pdf(in_file, word_id): | |
pythoncom.CoInitialize() | |
word = client.dynamic.Dispatch(pythoncom.CoGetInterfaceAndReleaseStream(word_id, pythoncom.IID_IDispatch)) | |
word.Visible = False | |
in_file = os.path.abspath(in_file) | |
out_file = in_file.replace('.docx', '.pdf').replace('.doc', '.pdf') | |
with suppress(FileNotFoundError): os.remove(out_file) | |
doc = word.Documents.Open(in_file) | |
doc.SaveAs(out_file, FileFormat=wdFormatPDF) | |
doc.Close() | |
threads = [] | |
for file in files: | |
word_id = pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch, word) | |
t = threading.Thread(target=convert_to_pdf, args=(file, word_id)) | |
t.start() | |
threads.append(t) | |
print("Creating PDF's") | |
for t in threads: t.join() | |
word.Quit() | |
print("Created PDF's") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment