Skip to content

Instantly share code, notes, and snippets.

@rgherta
Created June 3, 2017 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rgherta/cf8c0feb0d9c6ec6cabce14c99609bdd to your computer and use it in GitHub Desktop.
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
#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