2

I want to add an image as background/watermark to a new word document using Python. I tried Python-docx but couldn't find anything useful

from docx import Document
from docx.shared import Inches

document = Document()

document.add_picture(r'D:\Python\Projects\raw_imgs\3b057d6199d95c4339ef532001cb20cd.jpg', width=Inches(6))
document.save('demo.docx')

The above code just inserts the image but I want to add it as the background image.

  • https://stackoverflow.com/questions/56074727/what-is-the-way-to-add-watermark-text-in-a-docx-file-using-python – Joe Apr 10 '20 at 11:28
  • https://github.com/python-openxml/python-docx/issues/407 – Joe Apr 10 '20 at 11:29
  • @Joe Thanks, but I have already looked into it, these don't help with background/watermark image – gunjit bedi Apr 10 '20 at 12:43
  • https://stackoverflow.com/questions/32932230/add-an-image-in-a-specific-position-in-the-document-docx-with-python – Joe Apr 10 '20 at 14:20

1 Answers1

0

Aspose.Words Cloud SDK for Python can insert an image as a background to the DOC/DOCX. Though it is paid product, its free trial allows 150 free API calls monthly.

# For complete examples and data files, please go to https://github.com/aspose-words-cloud/aspose-words-cloud-python
# Import module
import asposewordscloud
import asposewordscloud.models.requests
from shutil import copyfile

# Please get your Client ID and Secret from https://dashboard.aspose.cloud.
client_id='xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx'
client_secret='xxxxxxxxxxxxxxxxxxxxxxxxxxx'

words_api = asposewordscloud.WordsApi(client_id,client_secret)
words_api.api_client.configuration.host='https://api.aspose.cloud'

localFile = 'C:/Temp/Sections.docx'
imageFile= 'C:/Temp/Tulips.jpg'
outputFile= 'C:/Temp/Watermark.docx'

request = asposewordscloud.models.requests.InsertWatermarkImageOnlineRequest(document=open(localFile, 'rb'), image_file=open(imageFile, 'rb'))

result = words_api.insert_watermark_image_online(request)
copyfile(result.document, outputFile)

Tilal Ahmad
  • 940
  • 5
  • 9