Merge pull request #201 from edufresne/master

#200 - fix issue with reading and writing to file-like object using replace_media
This commit is contained in:
Eric Lapouyade 2019-06-03 16:02:26 +02:00 committed by GitHub
commit d3ddb59d1c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 7 deletions

View File

@ -5,6 +5,7 @@ Created : 2015-03-12
@author: Eric Lapouyade
'''
import functools
import io
__version__ = '0.5.20'
@ -450,13 +451,20 @@ class DocxTemplate(object):
crc = self.get_file_crc(src_file)
self.crc_to_new_embedded[crc] = fh.read()
def post_processing(self,docx_filename):
def post_processing(self, docx_file):
if self.crc_to_new_media or self.crc_to_new_embedded:
backup_filename = '%s_docxtpl_before_replace_medias' % docx_filename
os.rename(docx_filename,backup_filename)
with zipfile.ZipFile(backup_filename) as zin:
with zipfile.ZipFile(docx_filename, 'w') as zout:
if hasattr(docx_file, 'read'):
tmp_file = io.BytesIO()
Document(docx_file).save(tmp_file)
tmp_file.seek(0)
else:
tmp_file = '%s_docxtpl_before_replace_medias' % docx_file
os.rename(docx_file, tmp_file)
with zipfile.ZipFile(tmp_file) as zin:
with zipfile.ZipFile(docx_file, 'w') as zout:
for item in zin.infolist():
buf = zin.read(item.filename)
if ( item.filename.startswith('word/media/') and
@ -468,7 +476,10 @@ class DocxTemplate(object):
else:
zout.writestr(item, buf)
os.remove(backup_filename)
if not hasattr(tmp_file, 'read'):
os.remove(tmp_file)
if hasattr(docx_file, 'read'):
docx_file.seek(0)
def pre_processing(self):

View File

@ -9,6 +9,7 @@ from docxtpl import DocxTemplate
import io
DEST_FILE = 'output/header_footer_image_file_obj.docx'
DEST_FILE2 = 'output/header_footer_image_file_obj2.docx'
tpl=DocxTemplate('templates/header_footer_image_tpl.docx')
@ -21,3 +22,14 @@ new_image = io.BytesIO(open('templates/python.png', 'rb').read())
tpl.replace_media(dummy_pic, new_image)
tpl.render(context)
tpl.save(DEST_FILE)
tpl = DocxTemplate('templates/header_footer_image_tpl.docx')
dummy_pic.seek(0)
new_image.seek(0)
tpl.replace_media(dummy_pic, new_image)
tpl.render(context)
file_obj = io.BytesIO()
tpl.save(file_obj)
file_obj.seek(0)
DocxTemplate(file_obj).save(DEST_FILE2)