Reputation: 21
I'm working on a python script which analyses excel file and based on than filling in docx files with multiple variables using mailmerge library. For string values all is working fine but I have a problems with inserting image into a file. As I have to choose from 7 images for now as a workaround I just created 7 templates and I'm choosing the correct template based on some conditions but in the near future I will have more combination of images inside docx file and then creating like 50 templates is not a good option.
On google i found out that images can be inserted into docx file with below structure:
{ INCLUDEPICTURE "{ MERGEFIELD 1.png * MERGEFORMAT }" * MERGEFORMAT }
but I cannot make it work for me. Is it possible to insert path of a image into it and then Word would use it to insert an image? something like that:
{ INCLUDEPICTURE "{ path_to_image * MERGEFORMAT }" * MERGEFORMAT }
from mailmerge import MailMerge
document = MailMerge(template.docx)
document.merge(path_to_image="C:\\image.png")
document.write(document_name)
Thanks!
Upvotes: 2
Views: 5288
Reputation: 11
For anyone reading this, I don't think it's possible to have the mailmerge fully update without any human interaction. Python can correctly input the absolute filepath (assuming format is correct as in usario1223's comment above) but the user must still go into Word and press F9 to 'update' mergefields.
This was a huge headache for me but I believe it is impossible. There is a reason that this is listed as a 'wishlist' item in the library's docs.
Upvotes: 1
Reputation: 610
1. No PNG files: You cannot insert .png files. You can only insert .jpg files.
2. Use Absolute filepaths: Ensure you are using an absolute filepath with double slashes, e.g: C:\\temp\\sample.jpg
3. Inserting the code into MS Word: The code that you insert into Word, must be inserted in a particular way:
i. In your MS Word template, press: ALT + F9
ii. Hold CTRL while pressing F9
iii. Enter:
{ INCLUDEPICTURE "{INSERT MERGE FIELD HERE}" \*MERGEFORMAT\d }
Highlight all the {INSERT MERGE FIELD HERE} characters, then select your merge field name from the top toolbar. Once selected the field name will be inserted inside curly brackets. Do not simply copy and paste the merge file from another section. You must create them all individually.
iv. Press: ALT + F9 to return to normal edit mode.
v. Complete your mailmerge for individual documents
vi. If your images don't show up, select all (CTRL + A) and press F9 to refresh. There may be some delay while the Word file is updating. If an image still won't show, click on it specifically and press F9. If the image still won't show, you have a problem in step 1 or 2.
Upvotes: 4