Created
June 3, 2017 14:26
-
-
Save rgherta/cf8c0feb0d9c6ec6cabce14c99609bdd to your computer and use it in GitHub Desktop.
Python function for replacing values in a word template and save 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
#FUNCTION DEFINITION | |
def saveInvoice(templateName, saveWithName, valuesDictionary): | |
word = win32.gencache.EnsureDispatch('Word.Application') | |
word.Visible = False | |
myTemplate = word.Documents.Open(templateName) | |
for key in valuesDictionary: | |
find = word.Selection.Find | |
find.Text = key | |
find.Replacement.Text = valuesDictionary[key] | |
find.Execute(Replace=2,Forward=True) | |
myTemplate.SaveAs(invoiceName, FileFormat=17) | |
myTemplate.Close(False) | |
word.Quit() | |
#MAIN PROGRAM | |
import win32com.client as win32 | |
templateName = 'C:\\Users\\Grossman\\workspace\\Invoicetemplate\\invoiceTemplate.docx' | |
saveWithName= 'C:\\Users\\Grossman\\workspace\\Invoicetemplate\\Modified1.pdf' | |
valuesDictionary = {'{PlaceHolder1}' : 'value1', '{PlaceHolder2}' : 'value2', '{PlaceHolder3}' : 'value3'} | |
saveInvoice(templateName, saveWithName, valuesDictionary) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment