Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
python-docx can't parse some jpeg files correctly, so we use PIL
to format all jpeg files to workaround this issue when generate docx
file.
  • Loading branch information
Swind authored and Swind-Ou committed Sep 12, 2020
1 parent c46e177 commit 69c8fd1
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
14 changes: 13 additions & 1 deletion backend/api/admin/actions/export_docx.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@

from docxcompose.composer import Composer

import PIL
import time

LOGGER = logging.getLogger('django')

CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
Expand Down Expand Up @@ -332,7 +335,16 @@ def _attchments(self):
generator.new(
self.document, f"附件 {ConvertToLowerCaseNumbers(index)}", 12)
data = urlopen(image.image_path).read()
self.document.add_picture(BytesIO(data), width=Mm(150))

image_data = PIL.Image.open(BytesIO(data))
if image_data.format == "JPEG":
# Use PIL to save all jpeg files again to workaround python-docx bug
# https://github.com/python-openxml/python-docx/issues/187
tmp_image_data = BytesIO()
image_data.save(tmp_image_data, format="jpeg")
self.document.add_picture(tmp_image_data, width=Mm(150))
else:
self.document.add_picture(BytesIO(data), width=Mm(150))

def _page_break(self):
self.document.add_page_break()
Expand Down
22 changes: 22 additions & 0 deletions backend/api/admin/test/test_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,12 @@ def has_perm(self, perm):
"factory_type": "2-1",
"images": [
"https://i.imgur.com/3XPyVuF.png",
# python-docx can't parse this image correctly
# https://github.com/python-openxml/python-docx/issues/187
"https://i.imgur.com/Q3fplPG.jpg",
"https://i.imgur.com/eHQ8uWo.jpg",
"https://i.imgur.com/4AiXzf8.jpg",
"https://i.imgur.com/Jvh1OQm.jpg",
],
"lat": 23.123,
"lng": 120.2,
Expand Down Expand Up @@ -118,3 +123,20 @@ def test_export_doc_action(self):
assert response[
'Content-Type'
] == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'

def test_python_docx_workaround(self):
# python-docx can't parse some jpeg image correctly
# https://github.com/python-openxml/python-docx/issues/187
# So we use PIL to format the JPEG file to workaround this.
data = {
'action': 'export_as_docx',
'select_across': 0,
'index': 0,
'_selected_action': self.factories[1].id
}
response = self.client.post('/admin/api/factory/', data)

assert response.status_code == 200, f"status_code should be 200 but {response.status_code}"
assert response[
'Content-Type'
] == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'

0 comments on commit 69c8fd1

Please sign in to comment.