Merge pull request #198 from edufresne/master

Issue #197 - Add support for file-like objects for replace_media
This commit is contained in:
Eric Lapouyade 2019-05-23 08:25:00 +02:00 committed by GitHub
commit e956892d61
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 42 additions and 8 deletions

View File

@ -370,9 +370,13 @@ class DocxTemplate(object):
return Subdoc(self,docpath)
@staticmethod
def get_file_crc(filename):
with open(filename, 'rb') as fh:
def get_file_crc(file_obj):
if hasattr(file_obj, 'read'):
buf = file_obj.read()
else:
with open(file_obj, 'rb') as fh:
buf = fh.read()
crc = (binascii.crc32(buf) & 0xFFFFFFFF)
return crc
@ -382,16 +386,23 @@ class DocxTemplate(object):
This has been done mainly because it is not possible to add images in
docx header/footer.
With this function, put a dummy picture in your header/footer,
then specify it with its replacement in this function
then specify it with its replacement in this function using the file path
or file-like objects.
Syntax: tpl.replace_media('dummy_media_to_replace.png','media_to_paste.jpg')
-- or --
tpl.replace_media(io.BytesIO(image_stream), io.BytesIO(new_image_stream))
Note: for images, the aspect ratio will be the same as the replaced image
Note2 : it is important to have the source media file as it is required
to calculate its CRC to find them in the docx
"""
with open(dst_file, 'rb') as fh:
crc = self.get_file_crc(src_file)
if hasattr(dst_file, 'read'):
self.crc_to_new_media[crc] = dst_file.read()
else:
with open(dst_file, 'rb') as fh:
self.crc_to_new_media[crc] = fh.read()
def replace_pic(self,embedded_file,dst_file):

View File

@ -0,0 +1,23 @@
# -*- coding: utf-8 -*-
'''
Created : 2019-05-22
@author: Eric Dufresne
'''
from docxtpl import DocxTemplate
import io
DEST_FILE = 'output/header_footer_image_file_obj.docx'
tpl=DocxTemplate('templates/header_footer_image_tpl.docx')
context = {
'mycompany' : 'The World Wide company',
}
dummy_pic = io.BytesIO(open('templates/dummy_pic_for_header.png', 'rb').read())
new_image = io.BytesIO(open('templates/python.png', 'rb').read())
tpl.replace_media(dummy_pic, new_image)
tpl.render(context)
tpl.save(DEST_FILE)