import os
import re
import pkg_resources
import docx
from docx import Document
from docx.shared import Inches
from docx.enum.style import WD_STYLE_TYPE
import egaia_root
import egaia_make
from egaia_config import getConfig
from utils import re_uuid
[docs]def add_hyperlink(paragraph, url, text):
"""Place a hyperlink within a paragraph object. This code is from
python-docx."""
# This gets access to the document.xml.rels file and gets a new relation id value
part = paragraph.part
r_id = part.relate_to(url, docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK,
is_external=True)
# Create the w:hyperlink tag and add needed values
hyperlink = docx.oxml.shared.OxmlElement('w:hyperlink')
hyperlink.set(docx.oxml.shared.qn('r:id'), r_id, )
# Create a w:r element
new_run = docx.oxml.shared.OxmlElement('w:r')
# Create a new w:rPr element
rPr = docx.oxml.shared.OxmlElement('w:rPr')
# Join all the xml elements together; add required text to the w:r element
new_run.append(rPr)
new_run.text = text
hyperlink.append(new_run)
paragraph._p.append(hyperlink)
return hyperlink
[docs]def writeDocx(uuids):
"""Append figures corresponding to a list of uuids to a template document.
"""
pub = os.path.expanduser(getConfig('archive', 'pub_path'))
template = pkg_resources.resource_filename('egaia', 'static/figures-reference.docx')
document = Document(template)
document._body.clear_content()
for item in uuids:
m = re.search(re_uuid, item)
if not m:
continue
uuid = m.group(0)
print "Adding image for %s..." % uuid
img = egaia_make.getThumb(uuid, size='med')
if not img:
print "Could not find image for %s" % uuid
continue
img_fn = os.path.join(pub, 'item', uuid, img)
# Add image with "Figure" style
p = document.add_paragraph(style='Figure')
r = p.add_run()
r.add_picture(img_fn, width=Inches(6))
meta_str = egaia_make.loadJson(uuid, 'item')
title = meta_str.get(egaia_make.fields_rev['DCTERMS.title'])
caption = meta_str.get(egaia_make.fields_rev['DCTERMS.description'])
# Add paragraphs with "Caption" style
if title:
p = document.add_paragraph(style='Caption')
p.add_run(title).bold = True
if caption:
document.add_paragraph(caption[0], style='Caption')
p = document.add_paragraph(style='Caption')
link = getConfig('archive', 'archive_url') + u'item/' + uuid + u'/'
add_hyperlink(p, link, link)
document.save(os.path.join('data', 'figures.docx'))
def _cli(args):
"""egaia figs
Given a list of UUIDs, append figures for referenced archive items to a
template document.
Usage:
egaia figs --help
egaia figs UUID...
"""
writeDocx(args['UUID'])