diff --git a/docs/conf.py b/docs/conf.py index e49608b..b97390f 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -12,18 +12,15 @@ # All configuration values have a default; values that are commented out # serve to show the default. -import sys -import os - # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. -#sys.path.insert(0, os.path.abspath('.')) +# sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. -#needs_sphinx = '1.0' +# needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom @@ -39,7 +36,7 @@ templates_path = ['_templates'] source_suffix = '.rst' # The encoding of source files. -#source_encoding = 'utf-8-sig' +# source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' @@ -59,13 +56,13 @@ release = '0.9.x' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. -#language = None +# language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: -#today = '' +# today = '' # Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' +# today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. @@ -73,27 +70,27 @@ exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. -#default_role = None +# default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True +# add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). -#add_module_names = True +# add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. -#show_authors = False +# show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] +# modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. -#keep_warnings = False +# keep_warnings = False # -- Options for HTML output ---------------------------------------------- @@ -105,26 +102,26 @@ html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. -#html_theme_options = {} +# html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. -#html_theme_path = [] +# html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". -#html_title = None +# html_title = None # A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None +# html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. -#html_logo = None +# html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. -#html_favicon = None +# html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, @@ -134,48 +131,48 @@ html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. -#html_extra_path = [] +# html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' +# html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. -#html_use_smartypants = True +# html_use_smartypants = True # Custom sidebar templates, maps document names to template names. -#html_sidebars = {} +# html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. -#html_additional_pages = {} +# html_additional_pages = {} # If false, no module index is generated. -#html_domain_indices = True +# html_domain_indices = True # If false, no index is generated. -#html_use_index = True +# html_use_index = True # If true, the index is split into individual pages for each letter. -#html_split_index = False +# html_split_index = False # If true, links to the reST sources are added to the pages. -#html_show_sourcelink = True +# html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -#html_show_sphinx = True +# html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -#html_show_copyright = True +# html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. -#html_use_opensearch = '' +# html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = None +# html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'python-docx-templatedoc' @@ -184,14 +181,12 @@ htmlhelp_basename = 'python-docx-templatedoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { -# The paper size ('letterpaper' or 'a4paper'). -#'papersize': 'letterpaper', - -# The font size ('10pt', '11pt' or '12pt'). -#'pointsize': '10pt', - -# Additional stuff for the LaTeX preamble. -#'preamble': '', + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples @@ -204,23 +199,23 @@ latex_documents = [ # The name of an image file (relative to this directory) to place at the top of # the title page. -#latex_logo = None +# latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. -#latex_use_parts = False +# latex_use_parts = False # If true, show page references after internal links. -#latex_show_pagerefs = False +# latex_show_pagerefs = False # If true, show URL addresses after external links. -#latex_show_urls = False +# latex_show_urls = False # Documents to append as an appendix to all manuals. -#latex_appendices = [] +# latex_appendices = [] # If false, no module index is generated. -#latex_domain_indices = True +# latex_domain_indices = True # -- Options for manual page output --------------------------------------- @@ -233,7 +228,7 @@ man_pages = [ ] # If true, show URL addresses after external links. -#man_show_urls = False +# man_show_urls = False # -- Options for Texinfo output ------------------------------------------- @@ -248,13 +243,13 @@ texinfo_documents = [ ] # Documents to append as an appendix to all manuals. -#texinfo_appendices = [] +# texinfo_appendices = [] # If false, no module index is generated. -#texinfo_domain_indices = True +# texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. -#texinfo_show_urls = 'footnote' +# texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. -#texinfo_no_detailmenu = False +# texinfo_no_detailmenu = False diff --git a/docxtpl/__init__.py b/docxtpl/__init__.py index 211bd79..9a284b9 100644 --- a/docxtpl/__init__.py +++ b/docxtpl/__init__.py @@ -11,7 +11,7 @@ __version__ = '0.9.0' from lxml import etree from docx import Document -from docx.opc.oxml import serialize_part_xml, parse_xml +from docx.opc.oxml import parse_xml from docx.opc.part import XmlPart import docx.oxml.ns from docx.opc.constants import RELATIONSHIP_TYPE as REL_TYPE @@ -62,65 +62,66 @@ class DocxTemplate(object): def get_xml(self): return self.xml_to_string(self.docx._element.body) - def write_xml(self,filename): - with open(filename,'w') as fh: + def write_xml(self, filename): + with open(filename, 'w') as fh: fh.write(self.get_xml()) - def patch_xml(self,src_xml): + def patch_xml(self, src_xml): # strip all xml tags inside {% %} and {{ }} that MS word can insert # into xml source also unescape html entities - src_xml = re.sub(r'(?<={)(<[^>]*>)+(?=[\{%])|(?<=[%\}])(<[^>]*>)+(?=\})','', - src_xml,flags=re.DOTALL) + src_xml = re.sub(r'(?<={)(<[^>]*>)+(?=[\{%])|(?<=[%\}])(<[^>]*>)+(?=\})', '', + src_xml, flags=re.DOTALL) + def striptags(m): - return re.sub('.*?(|]*>)','', - m.group(0),flags=re.DOTALL) - src_xml = re.sub(r'{%(?:(?!%}).)*|{{(?:(?!}}).)*',striptags, - src_xml,flags=re.DOTALL) + return re.sub('.*?(|]*>)', '', + m.group(0), flags=re.DOTALL) + src_xml = re.sub(r'{%(?:(?!%}).)*|{{(?:(?!}}).)*', striptags, + src_xml, flags=re.DOTALL) # manage table cell colspan def colspan(m): cell_xml = m.group(1) + m.group(3) cell_xml = re.sub(r'](?:(?!]).)*.*?', - '', cell_xml,flags=re.DOTALL) - cell_xml = re.sub(r'','', cell_xml, count=1) - return re.sub(r'(]*>)',r'\1' - % m.group(2), cell_xml ) + '', cell_xml, flags=re.DOTALL) + cell_xml = re.sub(r'', '', cell_xml, count=1) + return re.sub(r'(]*>)', r'\1' + % m.group(2), cell_xml) src_xml = re.sub(r'(](?:(?!]).)*){%\s*colspan\s+([^%]*)\s*%}(.*?)', - colspan,src_xml,flags=re.DOTALL) + colspan, src_xml, flags=re.DOTALL) # manage table cell background color def cellbg(m): cell_xml = m.group(1) + m.group(3) cell_xml = re.sub(r'](?:(?!]).)*.*?', - '',cell_xml,flags=re.DOTALL) - cell_xml = re.sub(r'','', cell_xml, count=1) + '', cell_xml, flags=re.DOTALL) + cell_xml = re.sub(r'', '', cell_xml, count=1) return re.sub(r'(]*>)', r'\1' % m.group(2), cell_xml) src_xml = re.sub(r'(](?:(?!]).)*){%\s*cellbg\s+([^%]*)\s*%}(.*?)', - cellbg,src_xml,flags=re.DOTALL) + cellbg, src_xml, flags=re.DOTALL) # avoid {{r and {%r tags to strip MS xml tags too far # ensure space preservation when splitting src_xml = re.sub(r'((?:(?!).)*)({{r\s.*?}}|{%r\s.*?%})', r'\1\2', - src_xml,flags=re.DOTALL) + src_xml, flags=re.DOTALL) src_xml = re.sub(r'({{r\s.*?}}|{%r\s.*?%})', r'\1', - src_xml,flags=re.DOTALL) + src_xml, flags=re.DOTALL) # {%- will merge with previous paragraph text - src_xml = re.sub(r'(?:(?!).)*?{%-','{%',src_xml,flags=re.DOTALL) + src_xml = re.sub(r'(?:(?!).)*?{%-', '{%', src_xml, flags=re.DOTALL) # -%} will merge with next paragraph text - src_xml = re.sub(r'-%}(?:(?!]).)*?]*?>','%}',src_xml,flags=re.DOTALL) + src_xml = re.sub(r'-%}(?:(?!]).)*?]*?>', '%}', src_xml, flags=re.DOTALL) for y in ['tr', 'tc', 'p', 'r']: # replace into xml code the row/paragraph/run containing # {%y xxx %} or {{y xxx}} template tag # by {% xxx %} or {{ xx }} without any surronding tags : # This is mandatory to have jinja2 generating correct xml code - pat = r'](?:(?!]).)*({%%|{{)%(y)s ([^}%%]*(?:%%}|}})).*?' % {'y':y} - src_xml = re.sub(pat, r'\1 \2',src_xml,flags=re.DOTALL) + pat = r'](?:(?!]).)*({%%|{{)%(y)s ([^}%%]*(?:%%}|}})).*?' % {'y': y} + src_xml = re.sub(pat, r'\1 \2', src_xml, flags=re.DOTALL) # add vMerge # use {% vm %} to make this table cell and its copies be vertically merged within a {% for %} @@ -196,19 +197,19 @@ class DocxTemplate(object): h_merge_tc, src_xml, flags=re.DOTALL) def clean_tags(m): - return ( m.group(0) - .replace(r"‘","'") - .replace('<','<') - .replace('>','>') - .replace(u'“',u'"') - .replace(u'”',u'"') - .replace(u"‘",u"'") - .replace(u"’",u"'") ) - src_xml = re.sub(r'(?<=\{[\{%])(.*?)(?=[\}%]})',clean_tags,src_xml) + return (m.group(0) + .replace(r"‘", "'") + .replace('<', '<') + .replace('>', '>') + .replace(u'“', u'"') + .replace(u'”', u'"') + .replace(u"‘", u"'") + .replace(u"’", u"'")) + src_xml = re.sub(r'(?<=\{[\{%])(.*?)(?=[\}%]})', clean_tags, src_xml) return src_xml - def render_xml(self,src_xml,context,jinja_env=None): + def render_xml(self, src_xml, context, jinja_env=None): src_xml = src_xml.replace(r'', '\n') try: if jinja_env: @@ -223,14 +224,14 @@ class DocxTemplate(object): src_xml.splitlines()[line_number:(line_number + 7)]) raise exc dst_xml = dst_xml.replace('\n', '') - dst_xml = ( dst_xml - .replace('{_{','{{') - .replace('}_}','}}') - .replace('{_%','{%') - .replace('%_}','%}') ) + dst_xml = (dst_xml + .replace('{_{', '{{') + .replace('}_}', '}}') + .replace('{_%', '{%') + .replace('%_}', '%}')) return dst_xml - def build_xml(self,context,jinja_env=None): + def build_xml(self, context, jinja_env=None): xml = self.get_xml() xml = self.patch_xml(xml) xml = self.render_xml(xml, context, jinja_env) @@ -246,13 +247,13 @@ class DocxTemplate(object): if (val.reltype == uri) and (val.target_part.blob): yield relKey, self.xml_to_string(parse_xml(val.target_part.blob)) - def get_headers_footers_encoding(self,xml): - m = re.match(r'<\?xml[^\?]+\bencoding="([^"]+)"',xml,re.I) + def get_headers_footers_encoding(self, xml): + m = re.match(r'<\?xml[^\?]+\bencoding="([^"]+)"', xml, re.I) if m: return m.group(1) return 'utf-8' - def build_headers_footers_xml(self,context, uri,jinja_env=None): + def build_headers_footers_xml(self, context, uri, jinja_env=None): for relKey, xml in self.get_headers_footers_xml(uri): encoding = self.get_headers_footers_encoding(xml) xml = self.patch_xml(xml) @@ -317,7 +318,7 @@ class DocxTemplate(object): width = 0.0 new_average = None for c in columns: - if not c.get(ns+'w') == None: + if not c.get(ns+'w') is None: width += float(c.get(ns+'w')) # try to keep proportion of table if width > 0: @@ -376,14 +377,13 @@ class DocxTemplate(object): extra_space = removed_width / len(columns_left) extra_space = int(extra_space) - for c in columns_left: c.set(ns+'w', str(int(float(c.get(ns+'w')) + extra_space))) return tree - def new_subdoc(self,docpath=None): - return Subdoc(self,docpath) + def new_subdoc(self, docpath=None): + return Subdoc(self, docpath) @staticmethod def get_file_crc(file_obj): @@ -396,7 +396,7 @@ class DocxTemplate(object): crc = (binascii.crc32(buf) & 0xFFFFFFFF) return crc - def replace_media(self,src_file,dst_file): + def replace_media(self, src_file, dst_file): """Replace one media by another one into a docx This has been done mainly because it is not possible to add images in @@ -422,7 +422,7 @@ class DocxTemplate(object): with open(dst_file, 'rb') as fh: self.crc_to_new_media[crc] = fh.read() - def replace_pic(self,embedded_file,dst_file): + def replace_pic(self, embedded_file, dst_file): """Replace embedded picture with original-name given by embedded_file. (give only the file basename, not the full path) The new picture is given by dst_file (either a filename or a file-like @@ -437,20 +437,20 @@ class DocxTemplate(object): for replace_embedded and replace_media) """ - if hasattr(dst_file,'read'): + if hasattr(dst_file, 'read'): # NOTE: file extension not checked - self.pic_to_replace[embedded_file]=dst_file.read() + self.pic_to_replace[embedded_file] = dst_file.read() else: - emp_path,emb_ext=os.path.splitext(embedded_file) - dst_path,dst_ext=os.path.splitext(dst_file) + emp_path, emb_ext = os.path.splitext(embedded_file) + dst_path, dst_ext = os.path.splitext(dst_file) - if emb_ext!=dst_ext: + if emb_ext != dst_ext: raise ValueError('replace_pic: extensions must match') with open(dst_file, 'rb') as fh: - self.pic_to_replace[embedded_file]=fh.read() + self.pic_to_replace[embedded_file] = fh.read() - def replace_embedded(self,src_file,dst_file): + def replace_embedded(self, src_file, dst_file): """Replace one embdded object by another one into a docx This has been done mainly because it is not possible to add images @@ -467,7 +467,7 @@ class DocxTemplate(object): crc = self.get_file_crc(src_file) self.crc_to_new_embedded[crc] = fh.read() - def replace_zipname(self,zipname,dst_file): + def replace_zipname(self, zipname, dst_file): """Replace one file in the docx file First note that a MSWord .docx file is in fact a zip file. @@ -498,9 +498,9 @@ class DocxTemplate(object): self.zipname_to_replace[zipname] = fh.read() def post_processing(self, docx_file): - if ( self.crc_to_new_media or - self.crc_to_new_embedded or - self.zipname_to_replace ): + if (self.crc_to_new_media or + self.crc_to_new_embedded or + self.zipname_to_replace): if hasattr(docx_file, 'read'): tmp_file = io.BytesIO() @@ -520,11 +520,11 @@ class DocxTemplate(object): buf = zin.read(item.filename) if item.filename in self.zipname_to_replace: zout.writestr(item, self.zipname_to_replace[item.filename]) - elif ( item.filename.startswith('word/media/') and - item.CRC in self.crc_to_new_media ): + elif (item.filename.startswith('word/media/') and + item.CRC in self.crc_to_new_media): zout.writestr(item, self.crc_to_new_media[item.CRC]) - elif ( item.filename.startswith('word/embeddings/') and - item.CRC in self.crc_to_new_embedded): + elif (item.filename.startswith('word/embeddings/') and + item.CRC in self.crc_to_new_embedded): zout.writestr(item, self.crc_to_new_embedded[item.CRC]) else: zout.writestr(item, buf) @@ -540,70 +540,70 @@ class DocxTemplate(object): self.build_pic_map() # Do the actual replacement - for embedded_file,stream in six.iteritems(self.pic_to_replace): + for embedded_file, stream in six.iteritems(self.pic_to_replace): if embedded_file not in self.pic_map: raise ValueError('Picture "%s" not found in the docx template' % embedded_file) - self.pic_map[embedded_file][1]._blob=stream + self.pic_map[embedded_file][1]._blob = stream def build_pic_map(self): """Searches in docx template all the xml pictures tag and store them in pic_map dict""" if self.pic_to_replace: # Main document - part=self.docx.part + part = self.docx.part self.pic_map.update(self._img_filename_to_part(part)) # Header/Footer for relid, rel in six.iteritems(self.docx.part.rels): - if rel.reltype in (REL_TYPE.HEADER,REL_TYPE.FOOTER): + if rel.reltype in (REL_TYPE.HEADER, REL_TYPE.FOOTER): self.pic_map.update(self._img_filename_to_part(rel.target_part)) def get_pic_map(self): return self.pic_map - def _img_filename_to_part(self,doc_part): + def _img_filename_to_part(self, doc_part): - et=etree.fromstring(doc_part.blob) + et = etree.fromstring(doc_part.blob) - part_map={} + part_map = {} - gds=et.xpath('//a:graphic/a:graphicData',namespaces=docx.oxml.ns.nsmap) + gds = et.xpath('//a:graphic/a:graphicData', namespaces=docx.oxml.ns.nsmap) for gd in gds: - rel=None + rel = None # Either IMAGE, CHART, SMART_ART, ... try: - if gd.attrib['uri']==docx.oxml.ns.nsmap['pic']: + if gd.attrib['uri'] == docx.oxml.ns.nsmap['pic']: # Either PICTURE or LINKED_PICTURE image - blip=gd.xpath('pic:pic/pic:blipFill/a:blip', - namespaces=docx.oxml.ns.nsmap)[0] - dest=blip.xpath('@r:embed',namespaces=docx.oxml.ns.nsmap) - if len(dest)>0: - rel=dest[0] + blip = gd.xpath('pic:pic/pic:blipFill/a:blip', + namespaces=docx.oxml.ns.nsmap)[0] + dest = blip.xpath('@r:embed', namespaces=docx.oxml.ns.nsmap) + if len(dest) > 0: + rel = dest[0] else: continue else: continue - #title=inl.xpath('wp:docPr/@title',namespaces=docx.oxml.ns.nsmap)[0] - name=gd.xpath('pic:pic/pic:nvPicPr/pic:cNvPr/@name', - namespaces=docx.oxml.ns.nsmap)[0] + # title=inl.xpath('wp:docPr/@title',namespaces=docx.oxml.ns.nsmap)[0] + name = gd.xpath('pic:pic/pic:nvPicPr/pic:cNvPr/@name', + namespaces=docx.oxml.ns.nsmap)[0] - part_map[name]=(doc_part.rels[rel].target_ref, - doc_part.rels[rel].target_part) - - except: + part_map[name] = (doc_part.rels[rel].target_ref, + doc_part.rels[rel].target_part) + # FIXME: figure out what exceptions are thrown here and catch more specific exceptions + except Exception: continue return part_map - def build_url_id(self,url): + def build_url_id(self, url): return self.docx._part.relate_to(url, REL_TYPE.HYPERLINK, is_external=True) - def save(self,filename,*args,**kwargs): + def save(self, filename, *args, **kwargs): self.pre_processing() - self.docx.save(filename,*args,**kwargs) + self.docx.save(filename, *args, **kwargs) self.post_processing(filename) def get_undeclared_template_variables(self, jinja_env=None): @@ -621,19 +621,19 @@ class DocxTemplate(object): class Subdoc(object): """ Class for subdocument to insert into master document """ - def __init__(self, tpl,docpath=None): + def __init__(self, tpl, docpath=None): self.tpl = tpl self.docx = tpl.get_docx() self.subdocx = Document(docpath) self.subdocx._part = self.docx._part - def __getattr__(self, name) : + def __getattr__(self, name): return getattr(self.subdocx, name) def _get_xml(self): if self.subdocx._element.body.sectPr is not None: self.subdocx._element.body.remove(self.subdocx._element.body.sectPr) - xml = re.sub(r']*>','',etree.tostring( + xml = re.sub(r']*>', '', etree.tostring( self.subdocx._element.body, encoding='unicode', pretty_print=False)) return xml @@ -658,18 +658,19 @@ class RichText(object): if text: self.add(text, **text_prop) - def add(self, text, style=None, - color=None, - highlight=None, - size=None, - subscript=None, - superscript=None, - bold=False, - italic=False, - underline=False, - strike=False, - font=None, - url_id=None): + def add(self, text, + style=None, + color=None, + highlight=None, + size=None, + subscript=None, + superscript=None, + bold=False, + italic=False, + underline=False, + strike=False, + font=None, + url_id=None): # If a RichText is added if isinstance(text, RichText): @@ -680,7 +681,7 @@ class RichText(object): if not isinstance(text, (six.text_type, six.binary_type)): text = six.text_type(text) if not isinstance(text, six.text_type): - text = text.decode('utf-8',errors='ignore') + text = text.decode('utf-8', errors='ignore') text = (escape(text) .replace('\n', NEWLINE_XML) .replace('\a', NEWPARAGRAPH_XML) @@ -711,26 +712,24 @@ class RichText(object): if italic: prop += u'' if underline: - if underline not in ['single','double']: + if underline not in ['single', 'double']: underline = 'single' prop += u'' % underline if strike: prop += u'' if font: - prop += ( u'' - .format(font=font) ) - + prop += (u'' + .format(font=font)) xml = u'' if prop: xml += u'%s' % prop xml += u'%s' % text if url_id: - xml = ( u'%s' - % (url_id, xml) ) + xml = (u'%s' + % (url_id, xml)) self.xml += xml - def __unicode__(self): return self.xml @@ -802,5 +801,3 @@ class InlineImage(object): def __html__(self): return self._insert_image() - - diff --git a/setup.py b/setup.py index 42a559e..aa75ee6 100644 --- a/setup.py +++ b/setup.py @@ -6,6 +6,7 @@ import sys # To register onto Pypi : # python setup.py sdist bdist_wheel upload + def read(*names): values = dict() for name in names: @@ -28,18 +29,20 @@ News %(CHANGES)s """ % read('README', 'CHANGES') + def get_version(pkg): - path = os.path.join(os.path.dirname(__file__),pkg,'__init__.py') + path = os.path.join(os.path.dirname(__file__), pkg, '__init__.py') if sys.version_info >= (3, 0): fh = open(path, encoding='utf-8') # required to read utf-8 file on windows else: - fh = open(path) # encoding parameter does not exist in python 2 + fh = open(path) # encoding parameter does not exist in python 2 with fh: - m = re.search(r'^__version__\s*=\s*[\'"]([^\'"]+)[\'"]',fh.read(),re.M) + m = re.search(r'^__version__\s*=\s*[\'"]([^\'"]+)[\'"]', fh.read(), re.M) if m: return m.group(1) raise RuntimeError("Unable to find __version__ string in %s." % path) + setup(name='docxtpl', version=get_version('docxtpl'), description='Python docx template engine', diff --git a/tests/cellbg.py b/tests/cellbg.py index b6b19bd..79938fb 100644 --- a/tests/cellbg.py +++ b/tests/cellbg.py @@ -7,14 +7,34 @@ Created : 2015-03-12 from docxtpl import DocxTemplate, RichText -tpl=DocxTemplate('templates/cellbg_tpl.docx') +tpl = DocxTemplate('templates/cellbg_tpl.docx') context = { - 'alerts' : [ - {'date' : '2015-03-10', 'desc' : RichText('Very critical alert',color='FF0000', bold=True), 'type' : 'CRITICAL', 'bg': 'FF0000' }, - {'date' : '2015-03-11', 'desc' : RichText('Just a warning'), 'type' : 'WARNING', 'bg': 'FFDD00' }, - {'date' : '2015-03-12', 'desc' : RichText('Information'), 'type' : 'INFO', 'bg': '8888FF' }, - {'date' : '2015-03-13', 'desc' : RichText('Debug trace'), 'type' : 'DEBUG', 'bg': 'FF00FF' }, + 'alerts': [ + { + 'date': '2015-03-10', + 'desc': RichText('Very critical alert', color='FF0000', bold=True), + 'type': 'CRITICAL', + 'bg': 'FF0000', + }, + { + 'date': '2015-03-11', + 'desc': RichText('Just a warning'), + 'type': 'WARNING', + 'bg': 'FFDD00', + }, + { + 'date': '2015-03-12', + 'desc': RichText('Information'), + 'type': 'INFO', + 'bg': '8888FF', + }, + { + 'date': '2015-03-13', + 'desc': RichText('Debug trace'), + 'type': 'DEBUG', + 'bg': 'FF00FF', + }, ], } diff --git a/tests/custom_jinja_filters.py b/tests/custom_jinja_filters.py index 74db42c..580986b 100644 --- a/tests/custom_jinja_filters.py +++ b/tests/custom_jinja_filters.py @@ -10,6 +10,7 @@ import jinja2 jinja_env = jinja2.Environment() + # to create new filters, first create functions that accept the value to filter # as first argument, and filter parameters as next arguments def my_filterA(value, my_string_arg): @@ -21,13 +22,14 @@ def my_filterB(value, my_float_arg): return_value = value + my_float_arg return return_value + # Then, declare them to jinja like this : jinja_env.filters['my_filterA'] = my_filterA jinja_env.filters['my_filterB'] = my_filterB -context = {'base_value_string' : ' Hello', 'base_value_float' : 1.5 } +context = {'base_value_string': ' Hello', 'base_value_float': 1.5} -tpl=DocxTemplate('templates/custom_jinja_filters_tpl.docx') +tpl = DocxTemplate('templates/custom_jinja_filters_tpl.docx') tpl.render(context, jinja_env) -tpl.save('output/custom_jinja_filters.docx') \ No newline at end of file +tpl.save('output/custom_jinja_filters.docx') diff --git a/tests/dynamic_table.py b/tests/dynamic_table.py index bce8a6b..f4446d3 100644 --- a/tests/dynamic_table.py +++ b/tests/dynamic_table.py @@ -1,14 +1,14 @@ from docxtpl import DocxTemplate -tpl=DocxTemplate('templates/dynamic_table_tpl.docx') +tpl = DocxTemplate('templates/dynamic_table_tpl.docx') context = { - 'col_labels' : ['fruit', 'vegetable', 'stone', 'thing'], + 'col_labels': ['fruit', 'vegetable', 'stone', 'thing'], 'tbl_contents': [ {'label': 'yellow', 'cols': ['banana', 'capsicum', 'pyrite', 'taxi']}, {'label': 'red', 'cols': ['apple', 'tomato', 'cinnabar', 'doubledecker']}, {'label': 'green', 'cols': ['guava', 'cucumber', 'aventurine', 'card']}, - ] + ], } tpl.render(context) diff --git a/tests/embedded.py b/tests/embedded.py index bb6c74a..c2b776b 100644 --- a/tests/embedded.py +++ b/tests/embedded.py @@ -8,29 +8,38 @@ Created : 2017-09-09 from docxtpl import DocxTemplate # rendering the "dynamic embedded docx": -embedded_docx_tpl=DocxTemplate('templates/embedded_embedded_docx_tpl.docx') +embedded_docx_tpl = DocxTemplate('templates/embedded_embedded_docx_tpl.docx') context = { - 'name' : 'John Doe', + 'name': 'John Doe', } embedded_docx_tpl.render(context) embedded_docx_tpl.save('output/embedded_embedded_docx.docx') # rendring the main document : -tpl=DocxTemplate('templates/embedded_main_tpl.docx') +tpl = DocxTemplate('templates/embedded_main_tpl.docx') context = { - 'name' : 'John Doe', + 'name': 'John Doe', } -tpl.replace_embedded('templates/embedded_dummy.docx','templates/embedded_static_docx.docx') -tpl.replace_embedded('templates/embedded_dummy2.docx','output/embedded_embedded_docx.docx') +tpl.replace_embedded( + 'templates/embedded_dummy.docx', 'templates/embedded_static_docx.docx' +) +tpl.replace_embedded( + 'templates/embedded_dummy2.docx', 'output/embedded_embedded_docx.docx' +) # The zipname is the one you can find when you open docx with WinZip, 7zip (Windows) # or unzip -l (Linux). The zipname starts with "word/embeddings/". # Note that the file is renamed by MSWord, so you have to guess a little bit... -tpl.replace_zipname('word/embeddings/Feuille_Microsoft_Office_Excel3.xlsx','templates/real_Excel.xlsx') -tpl.replace_zipname('word/embeddings/Pr_sentation_Microsoft_Office_PowerPoint4.pptx','templates/real_PowerPoint.pptx') +tpl.replace_zipname( + 'word/embeddings/Feuille_Microsoft_Office_Excel3.xlsx', 'templates/real_Excel.xlsx' +) +tpl.replace_zipname( + 'word/embeddings/Pr_sentation_Microsoft_Office_PowerPoint4.pptx', + 'templates/real_PowerPoint.pptx', +) tpl.render(context) -tpl.save('output/embedded.docx') \ No newline at end of file +tpl.save('output/embedded.docx') diff --git a/tests/escape.py b/tests/escape.py index 79aa07c..a18b926 100644 --- a/tests/escape.py +++ b/tests/escape.py @@ -1,13 +1,20 @@ -from docxtpl import * +from docxtpl import DocxTemplate, R, Listing tpl = DocxTemplate('templates/escape_tpl.docx') -context = {'myvar': R('"less than" must be escaped : <, this can be done with RichText() or R()'), - 'myescvar': 'It can be escaped with a "|e" jinja filter in the template too : < ', - 'nlnp': R('Here is a multiple\nlines\nstring\aand some\aother\aparagraphs\aNOTE: the current character styling is removed'), - 'mylisting': Listing('the listing\nwith\nsome\nlines\nand special chars : <>&\f ... and a page break'), - 'page_break': R('\f'), - } +context = { + 'myvar': R( + '"less than" must be escaped : <, this can be done with RichText() or R()' + ), + 'myescvar': 'It can be escaped with a "|e" jinja filter in the template too : < ', + 'nlnp': R( + 'Here is a multiple\nlines\nstring\aand some\aother\aparagraphs\aNOTE: the current character styling is removed' + ), + 'mylisting': Listing( + 'the listing\nwith\nsome\nlines\nand special chars : <>&\f ... and a page break' + ), + 'page_break': R('\f'), +} tpl.render(context) tpl.save('output/escape.docx') diff --git a/tests/escape_auto.py b/tests/escape_auto.py index bafbfc2..e0def1d 100644 --- a/tests/escape_auto.py +++ b/tests/escape_auto.py @@ -14,11 +14,12 @@ XML_RESERVED = """<"&'>""" tpl = DocxTemplate('templates/escape_tpl_auto.docx') -context = {'nested_dict': {name(text_type(c)): c for c in XML_RESERVED}, - 'autoescape': 'Escaped "str & ing"!', - 'autoescape_unicode': u'This is an escaped example \u4f60 & \u6211', - 'iteritems': iteritems, - } +context = { + 'nested_dict': {name(text_type(c)): c for c in XML_RESERVED}, + 'autoescape': 'Escaped "str & ing"!', + 'autoescape_unicode': u'This is an escaped example \u4f60 & \u6211', + 'iteritems': iteritems, +} tpl.render(context, autoescape=True) diff --git a/tests/header_footer.py b/tests/header_footer.py index c3d1b6d..d60cc74 100644 --- a/tests/header_footer.py +++ b/tests/header_footer.py @@ -7,17 +7,19 @@ Created : 2015-03-12 from docxtpl import DocxTemplate -tpl=DocxTemplate('templates/header_footer_tpl.docx') +tpl = DocxTemplate('templates/header_footer_tpl.docx') sd = tpl.new_subdoc() -p = sd.add_paragraph('This is a sub-document to check it does not break header and footer') +p = sd.add_paragraph( + 'This is a sub-document to check it does not break header and footer' +) context = { - 'title' : 'Header and footer test', - 'company_name' : 'The World Wide company', - 'date' : '2016-03-17', - 'mysubdoc' : sd, + 'title': 'Header and footer test', + 'company_name': 'The World Wide company', + 'date': '2016-03-17', + 'mysubdoc': sd, } tpl.render(context) -tpl.save('output/header_footer.docx') \ No newline at end of file +tpl.save('output/header_footer.docx') diff --git a/tests/header_footer_entities.py b/tests/header_footer_entities.py index 8327936..320b5ef 100644 --- a/tests/header_footer_entities.py +++ b/tests/header_footer_entities.py @@ -7,10 +7,10 @@ Created : 2015-03-12 from docxtpl import DocxTemplate -tpl=DocxTemplate('templates/header_footer_entities_tpl.docx') +tpl = DocxTemplate('templates/header_footer_entities_tpl.docx') context = { - 'title' : 'Header and footer test', + 'title': 'Header and footer test', } tpl.render(context) diff --git a/tests/header_footer_image.py b/tests/header_footer_image.py index 2b95066..6ccaf55 100644 --- a/tests/header_footer_image.py +++ b/tests/header_footer_image.py @@ -9,11 +9,11 @@ from docxtpl import DocxTemplate DEST_FILE = 'output/header_footer_image.docx' -tpl=DocxTemplate('templates/header_footer_image_tpl.docx') +tpl = DocxTemplate('templates/header_footer_image_tpl.docx') context = { - 'mycompany' : 'The World Wide company', + 'mycompany': 'The World Wide company', } -tpl.replace_media('templates/dummy_pic_for_header.png','templates/python.png') +tpl.replace_media('templates/dummy_pic_for_header.png', 'templates/python.png') tpl.render(context) -tpl.save(DEST_FILE) \ No newline at end of file +tpl.save(DEST_FILE) diff --git a/tests/header_footer_image_file_obj.py b/tests/header_footer_image_file_obj.py index 4337640..a1bfcc9 100644 --- a/tests/header_footer_image_file_obj.py +++ b/tests/header_footer_image_file_obj.py @@ -11,10 +11,10 @@ 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') +tpl = DocxTemplate('templates/header_footer_image_tpl.docx') context = { - 'mycompany' : 'The World Wide company', + 'mycompany': 'The World Wide company', } dummy_pic = io.BytesIO(open('templates/dummy_pic_for_header.png', 'rb').read()) @@ -34,4 +34,3 @@ tpl.save(file_obj) file_obj.seek(0) with open(DEST_FILE2, 'wb') as f: f.write(file_obj.read()) - diff --git a/tests/header_footer_utf8.py b/tests/header_footer_utf8.py index 87df28f..7e337e9 100644 --- a/tests/header_footer_utf8.py +++ b/tests/header_footer_utf8.py @@ -9,16 +9,18 @@ Edited : 2016-07-19 by Eric Lapouyade from docxtpl import DocxTemplate -tpl=DocxTemplate('templates/header_footer_tpl_utf8.docx') +tpl = DocxTemplate('templates/header_footer_tpl_utf8.docx') sd = tpl.new_subdoc() -p = sd.add_paragraph(u'This is a sub-document to check it does not break header and footer with utf-8 characters inside the template .docx') +p = sd.add_paragraph( + u'This is a sub-document to check it does not break header and footer with utf-8 characters inside the template .docx' +) context = { - 'title' : u'헤더와 푸터', - 'company_name' : u'세계적 회사', - 'date' : u'2016-03-17', - 'mysubdoc' : sd, + 'title': u'헤더와 푸터', + 'company_name': u'세계적 회사', + 'date': u'2016-03-17', + 'mysubdoc': sd, } tpl.render(context) diff --git a/tests/inline_image.py b/tests/inline_image.py index f426463..5134d64 100644 --- a/tests/inline_image.py +++ b/tests/inline_image.py @@ -6,32 +6,40 @@ Created : 2017-01-14 ''' from docxtpl import DocxTemplate, InlineImage -# for height and width you have to use millimeters (Mm), inches or points(Pt) class : -from docx.shared import Mm, Inches, Pt -import jinja2 -from jinja2.utils import Markup -tpl=DocxTemplate('templates/inline_image_tpl.docx') +# for height and width you have to use millimeters (Mm), inches or points(Pt) class : +from docx.shared import Mm +import jinja2 + +tpl = DocxTemplate('templates/inline_image_tpl.docx') context = { - 'myimage' : InlineImage(tpl,'templates/python_logo.png',width=Mm(20)), - 'myimageratio': InlineImage(tpl, 'templates/python_jpeg.jpg', width=Mm(30), height=Mm(60)), - - 'frameworks' : [{'image' : InlineImage(tpl,'templates/django.png',height=Mm(10)), - 'desc' : 'The web framework for perfectionists with deadlines'}, - - {'image' : InlineImage(tpl,'templates/zope.png',height=Mm(10)), - 'desc' : 'Zope is a leading Open Source Application Server and Content Management Framework'}, - - {'image': InlineImage(tpl, 'templates/pyramid.png', height=Mm(10)), - 'desc': 'Pyramid is a lightweight Python web framework aimed at taking small web apps into big web apps.'}, - - {'image' : InlineImage(tpl,'templates/bottle.png',height=Mm(10)), - 'desc' : 'Bottle is a fast, simple and lightweight WSGI micro web-framework for Python'}, - - {'image': InlineImage(tpl, 'templates/tornado.png', height=Mm(10)), - 'desc': 'Tornado is a Python web framework and asynchronous networking library.'}, - ] + 'myimage': InlineImage(tpl, 'templates/python_logo.png', width=Mm(20)), + 'myimageratio': InlineImage( + tpl, 'templates/python_jpeg.jpg', width=Mm(30), height=Mm(60) + ), + 'frameworks': [ + { + 'image': InlineImage(tpl, 'templates/django.png', height=Mm(10)), + 'desc': 'The web framework for perfectionists with deadlines', + }, + { + 'image': InlineImage(tpl, 'templates/zope.png', height=Mm(10)), + 'desc': 'Zope is a leading Open Source Application Server and Content Management Framework', + }, + { + 'image': InlineImage(tpl, 'templates/pyramid.png', height=Mm(10)), + 'desc': 'Pyramid is a lightweight Python web framework aimed at taking small web apps into big web apps.', + }, + { + 'image': InlineImage(tpl, 'templates/bottle.png', height=Mm(10)), + 'desc': 'Bottle is a fast, simple and lightweight WSGI micro web-framework for Python', + }, + { + 'image': InlineImage(tpl, 'templates/tornado.png', height=Mm(10)), + 'desc': 'Tornado is a Python web framework and asynchronous networking library.', + }, + ], } # testing that it works also when autoescape has been forced to True jinja_env = jinja2.Environment(autoescape=True) diff --git a/tests/merge_paragraph.py b/tests/merge_paragraph.py index 90e84e3..6ff5cf0 100644 --- a/tests/merge_paragraph.py +++ b/tests/merge_paragraph.py @@ -7,10 +7,10 @@ Created : 2015-03-12 from docxtpl import DocxTemplate -tpl=DocxTemplate('templates/merge_paragraph_tpl.docx') +tpl = DocxTemplate('templates/merge_paragraph_tpl.docx') context = { - 'living_in_town' : True, + 'living_in_town': True, } tpl.render(context) diff --git a/tests/nested_for.py b/tests/nested_for.py index ded0033..839becc 100644 --- a/tests/nested_for.py +++ b/tests/nested_for.py @@ -7,26 +7,38 @@ Created : 2016-03-26 from docxtpl import DocxTemplate -tpl=DocxTemplate('templates/nested_for_tpl.docx') +tpl = DocxTemplate('templates/nested_for_tpl.docx') context = { - 'dishes' : [ - {'name' : 'Pizza', 'ingredients' : ['bread','tomato', 'ham', 'cheese']}, - {'name' : 'Hamburger', 'ingredients' : ['bread','chopped steak', 'cheese', 'sauce']}, - {'name' : 'Apple pie', 'ingredients' : ['flour','apples', 'suggar', 'quince jelly']}, + 'dishes': [ + {'name': 'Pizza', 'ingredients': ['bread', 'tomato', 'ham', 'cheese']}, + { + 'name': 'Hamburger', + 'ingredients': ['bread', 'chopped steak', 'cheese', 'sauce'], + }, + { + 'name': 'Apple pie', + 'ingredients': ['flour', 'apples', 'suggar', 'quince jelly'], + }, + ], + 'authors': [ + { + 'name': 'Saint-Exupery', + 'books': [ + {'title': 'Le petit prince'}, + {'title': "L'aviateur"}, + {'title': 'Vol de nuit'}, + ], + }, + { + 'name': 'Barjavel', + 'books': [ + {'title': 'Ravage'}, + {'title': "La nuit des temps"}, + {'title': 'Le grand secret'}, + ], + }, ], - 'authors' : [ - {'name' : 'Saint-Exupery', 'books' : [ - {'title' : 'Le petit prince'}, - {'title' : "L'aviateur"}, - {'title' : 'Vol de nuit'}, - ]}, - {'name' : 'Barjavel', 'books' : [ - {'title' : 'Ravage'}, - {'title' : "La nuit des temps"}, - {'title' : 'Le grand secret'}, - ]}, - ] } tpl.render(context) diff --git a/tests/order.py b/tests/order.py index 67ab9b4..a4f1f57 100644 --- a/tests/order.py +++ b/tests/order.py @@ -7,19 +7,19 @@ Created : 2015-03-12 from docxtpl import DocxTemplate -tpl=DocxTemplate('templates/order_tpl.docx') +tpl = DocxTemplate('templates/order_tpl.docx') -context = { - 'customer_name' : 'Eric', - 'items' : [ - {'desc' : 'Python interpreters', 'qty' : 2, 'price' : 'FREE' }, - {'desc' : 'Django projects', 'qty' : 5403, 'price' : 'FREE' }, - {'desc' : 'Guido', 'qty' : 1, 'price' : '100,000,000.00' }, - ], - 'in_europe' : True, +context = { + 'customer_name': 'Eric', + 'items': [ + {'desc': 'Python interpreters', 'qty': 2, 'price': 'FREE'}, + {'desc': 'Django projects', 'qty': 5403, 'price': 'FREE'}, + {'desc': 'Guido', 'qty': 1, 'price': '100,000,000.00'}, + ], + 'in_europe': True, 'is_paid': False, - 'company_name' : 'The World Wide company', - 'total_price' : '100,000,000.00' + 'company_name': 'The World Wide company', + 'total_price': '100,000,000.00', } tpl.render(context) diff --git a/tests/replace_picture.py b/tests/replace_picture.py index 6358ef4..45ccd7d 100644 --- a/tests/replace_picture.py +++ b/tests/replace_picture.py @@ -9,10 +9,10 @@ from docxtpl import DocxTemplate DEST_FILE = 'output/replace_picture.docx' -tpl=DocxTemplate('templates/replace_picture_tpl.docx') +tpl = DocxTemplate('templates/replace_picture_tpl.docx') context = {} -tpl.replace_pic('python_logo.png','templates/python.png') +tpl.replace_pic('python_logo.png', 'templates/python.png') tpl.render(context) -tpl.save(DEST_FILE) \ No newline at end of file +tpl.save(DEST_FILE) diff --git a/tests/richtext.py b/tests/richtext.py index 49132f6..81f7c0f 100644 --- a/tests/richtext.py +++ b/tests/richtext.py @@ -7,7 +7,7 @@ Created : 2015-03-26 from docxtpl import DocxTemplate, RichText -tpl=DocxTemplate('templates/richtext_tpl.docx') +tpl = DocxTemplate('templates/richtext_tpl.docx') rt = RichText() rt.add('a rich text', style='myrichtextstyle') @@ -23,16 +23,16 @@ rt.add(' or ') rt.add('big', size=60) rt.add(' text.') rt.add('\nYou can add an hyperlink, here to ') -rt.add('google',url_id=tpl.build_url_id('http://google.com')) +rt.add('google', url_id=tpl.build_url_id('http://google.com')) rt.add('\nEt voilà ! ') rt.add('\n1st line') rt.add('\n2nd line') rt.add('\n3rd line') rt.add('\n\n') -rt.add('\nFonts :\n',underline=True) -rt.add('Arial\n',font='Arial') -rt.add('Courier New\n',font='Courier New') -rt.add('Times New Roman\n',font='Times New Roman') +rt.add('\nFonts :\n', underline=True) +rt.add('Arial\n', font='Arial') +rt.add('Courier New\n', font='Courier New') +rt.add('Times New Roman\n', font='Times New Roman') rt.add('\n\nHere some') rt.add('superscript', superscript=True) rt.add(' and some') @@ -42,7 +42,7 @@ rt_embedded = RichText('an example of ') rt_embedded.add(rt) context = { - 'example' : rt_embedded, + 'example': rt_embedded, } tpl.render(context) diff --git a/tests/richtext_and_if.py b/tests/richtext_and_if.py index 170f60c..34ed64d 100644 --- a/tests/richtext_and_if.py +++ b/tests/richtext_and_if.py @@ -7,12 +7,10 @@ Created : 2015-03-26 from docxtpl import DocxTemplate, RichText -tpl=DocxTemplate('templates/richtext_and_if_tpl.docx') +tpl = DocxTemplate('templates/richtext_and_if_tpl.docx') -context = { - 'foobar': RichText('Foobar!', color='ff0000') -} +context = {'foobar': RichText('Foobar!', color='ff0000')} tpl.render(context) tpl.save('output/richtext_and_if.docx') diff --git a/tests/runtests.py b/tests/runtests.py index d2ebc2f..c956864 100644 --- a/tests/runtests.py +++ b/tests/runtests.py @@ -6,13 +6,13 @@ import os tests = sorted(glob.glob('[A-Za-z]*.py')) excludes = ['runtests.py'] -output_dir = os.path.join(os.path.dirname(__file__),'output') +output_dir = os.path.join(os.path.dirname(__file__), 'output') if not os.path.exists(output_dir): os.mkdir(output_dir) for test in tests: if test not in excludes: six.print_('%s ...' % test) - subprocess.call(['python','./%s' % test]) + subprocess.call(['python', './%s' % test]) six.print_('Done.') diff --git a/tests/subdoc.py b/tests/subdoc.py index afc5764..b118e4b 100644 --- a/tests/subdoc.py +++ b/tests/subdoc.py @@ -8,7 +8,7 @@ Created : 2015-03-12 from docxtpl import DocxTemplate from docx.shared import Inches -tpl=DocxTemplate('templates/subdoc_tpl.docx') +tpl = DocxTemplate('templates/subdoc_tpl.docx') sd = tpl.new_subdoc() p = sd.add_paragraph('This is a sub-document inserted into a bigger one') @@ -30,9 +30,7 @@ hdr_cells = table.rows[0].cells hdr_cells[0].text = 'Qty' hdr_cells[1].text = 'Id' hdr_cells[2].text = 'Desc' -recordset=( (1,101,'Spam'), - (2,42,'Eggs'), - (3,631,'Spam,spam, eggs, and ham') ) +recordset = ((1, 101, 'Spam'), (2, 42, 'Eggs'), (3, 631, 'Spam,spam, eggs, and ham')) for item in recordset: row_cells = table.add_row().cells row_cells[0].text = str(item[0]) @@ -40,7 +38,7 @@ for item in recordset: row_cells[2].text = item[2] context = { - 'mysubdoc' : sd, + 'mysubdoc': sd, } tpl.render(context) diff --git a/tests/template_error.py b/tests/template_error.py index 33d5c8e..2938fdc 100644 --- a/tests/template_error.py +++ b/tests/template_error.py @@ -1,4 +1,4 @@ -from docxtpl import DocxTemplate, RichText +from docxtpl import DocxTemplate from jinja2.exceptions import TemplateError import six @@ -7,9 +7,7 @@ six.print_("Generating template error for testing (so it is safe to ignore) :") six.print_('.' * 80) try: tpl = DocxTemplate('templates/template_error_tpl.docx') - tpl.render({ - 'test_variable' : 'test variable value' - }) + tpl.render({'test_variable': 'test variable value'}) except TemplateError as the_error: six.print_(six.text_type(the_error)) if hasattr(the_error, 'docx_context'): diff --git a/tests/vertical_merge.py b/tests/vertical_merge.py index be52531..60b6288 100644 --- a/tests/vertical_merge.py +++ b/tests/vertical_merge.py @@ -7,16 +7,16 @@ Created : 2017-10-15 from docxtpl import DocxTemplate -tpl=DocxTemplate('templates/vertical_merge_tpl.docx') +tpl = DocxTemplate('templates/vertical_merge_tpl.docx') -context = { - 'items' : [ - {'desc' : 'Python interpreters', 'qty' : 2, 'price' : 'FREE' }, - {'desc' : 'Django projects', 'qty' : 5403, 'price' : 'FREE' }, - {'desc' : 'Guido', 'qty' : 1, 'price' : '100,000,000.00' }, - ], - 'total_price' : '100,000,000.00', - 'category' : 'Book' +context = { + 'items': [ + {'desc': 'Python interpreters', 'qty': 2, 'price': 'FREE'}, + {'desc': 'Django projects', 'qty': 5403, 'price': 'FREE'}, + {'desc': 'Guido', 'qty': 1, 'price': '100,000,000.00'}, + ], + 'total_price': '100,000,000.00', + 'category': 'Book', } tpl.render(context) diff --git a/tests/word2016.py b/tests/word2016.py index 1729dc9..eb2f77d 100644 --- a/tests/word2016.py +++ b/tests/word2016.py @@ -1,10 +1,12 @@ from docxtpl import DocxTemplate, RichText tpl = DocxTemplate('templates/word2016_tpl.docx') -tpl.render({ - 'test_space' : ' ', - 'test_tabs': 5*'\t', - 'test_space_r' : RichText(' '), - 'test_tabs_r': RichText(5*'\t'), -}) +tpl.render( + { + 'test_space': ' ', + 'test_tabs': 5 * '\t', + 'test_space_r': RichText(' '), + 'test_tabs_r': RichText(5 * '\t'), + } +) tpl.save('output/word2016.docx')