Fix codestyling according to flake8 rules

This commit is contained in:
Edwin Smulders 2020-04-16 22:51:59 +02:00
parent 45a46eb924
commit 9175f0cbd6
26 changed files with 371 additions and 318 deletions

View File

@ -12,18 +12,15 @@
# All configuration values have a default; values that are commented out # All configuration values have a default; values that are commented out
# serve to show the default. # serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory, # 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 # 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. # 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 ------------------------------------------------ # -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here. # 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 # Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
@ -39,7 +36,7 @@ templates_path = ['_templates']
source_suffix = '.rst' source_suffix = '.rst'
# The encoding of source files. # The encoding of source files.
#source_encoding = 'utf-8-sig' # source_encoding = 'utf-8-sig'
# The master toctree document. # The master toctree document.
master_doc = 'index' master_doc = 'index'
@ -59,13 +56,13 @@ release = '0.9.x'
# The language for content autogenerated by Sphinx. Refer to documentation # The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages. # for a list of supported languages.
#language = None # language = None
# There are two options for replacing |today|: either, you set today to some # There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used: # non-false value, then it is used:
#today = '' # today = ''
# Else, today_fmt is used as the format for a strftime call. # 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 # List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files. # 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 # The reST default role (used for this markup: `text`) to use for all
# documents. # documents.
#default_role = None # default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text. # 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 # If true, the current module name will be prepended to all description
# unit titles (such as .. function::). # unit titles (such as .. function::).
#add_module_names = True # add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the # If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default. # output. They are ignored by default.
#show_authors = False # show_authors = False
# The name of the Pygments (syntax highlighting) style to use. # The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx' pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting. # 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. # If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False # keep_warnings = False
# -- Options for HTML output ---------------------------------------------- # -- 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 # 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 # further. For a list of options available for each theme, see the
# documentation. # documentation.
#html_theme_options = {} # html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory. # 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 # The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation". # "<project> v<release> documentation".
#html_title = None # html_title = None
# A shorter title for the navigation bar. Default is the same as html_title. # 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 # The name of an image file (relative to this directory) to place at the top
# of the sidebar. # 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 # 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 # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large. # pixels large.
#html_favicon = None # html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here, # 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, # 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 # Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied # .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation. # 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, # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format. # 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 # If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities. # typographically correct entities.
#html_use_smartypants = True # html_use_smartypants = True
# Custom sidebar templates, maps document names to template names. # 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 # Additional templates that should be rendered to pages, maps page names to
# template names. # template names.
#html_additional_pages = {} # html_additional_pages = {}
# If false, no module index is generated. # If false, no module index is generated.
#html_domain_indices = True # html_domain_indices = True
# If false, no index is generated. # 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. # 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. # 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. # 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. # 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 # If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the # contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served. # 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"). # 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. # Output file base name for HTML help builder.
htmlhelp_basename = 'python-docx-templatedoc' htmlhelp_basename = 'python-docx-templatedoc'
@ -184,14 +181,12 @@ htmlhelp_basename = 'python-docx-templatedoc'
# -- Options for LaTeX output --------------------------------------------- # -- Options for LaTeX output ---------------------------------------------
latex_elements = { latex_elements = {
# The paper size ('letterpaper' or 'a4paper'). # The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper', # 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
# The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt',
#'pointsize': '10pt', # Additional stuff for the LaTeX preamble.
# 'preamble': '',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
} }
# Grouping the document tree into LaTeX files. List of tuples # 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 name of an image file (relative to this directory) to place at the top of
# the title page. # the title page.
#latex_logo = None # latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts, # For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters. # not chapters.
#latex_use_parts = False # latex_use_parts = False
# If true, show page references after internal links. # If true, show page references after internal links.
#latex_show_pagerefs = False # latex_show_pagerefs = False
# If true, show URL addresses after external links. # 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. # Documents to append as an appendix to all manuals.
#latex_appendices = [] # latex_appendices = []
# If false, no module index is generated. # If false, no module index is generated.
#latex_domain_indices = True # latex_domain_indices = True
# -- Options for manual page output --------------------------------------- # -- Options for manual page output ---------------------------------------
@ -233,7 +228,7 @@ man_pages = [
] ]
# If true, show URL addresses after external links. # If true, show URL addresses after external links.
#man_show_urls = False # man_show_urls = False
# -- Options for Texinfo output ------------------------------------------- # -- Options for Texinfo output -------------------------------------------
@ -248,13 +243,13 @@ texinfo_documents = [
] ]
# Documents to append as an appendix to all manuals. # Documents to append as an appendix to all manuals.
#texinfo_appendices = [] # texinfo_appendices = []
# If false, no module index is generated. # If false, no module index is generated.
#texinfo_domain_indices = True # texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'. # 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. # If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False # texinfo_no_detailmenu = False

View File

@ -11,7 +11,7 @@ __version__ = '0.9.0'
from lxml import etree from lxml import etree
from docx import Document 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 from docx.opc.part import XmlPart
import docx.oxml.ns import docx.oxml.ns
from docx.opc.constants import RELATIONSHIP_TYPE as REL_TYPE from docx.opc.constants import RELATIONSHIP_TYPE as REL_TYPE
@ -62,65 +62,66 @@ class DocxTemplate(object):
def get_xml(self): def get_xml(self):
return self.xml_to_string(self.docx._element.body) return self.xml_to_string(self.docx._element.body)
def write_xml(self,filename): def write_xml(self, filename):
with open(filename,'w') as fh: with open(filename, 'w') as fh:
fh.write(self.get_xml()) 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 # strip all xml tags inside {% %} and {{ }} that MS word can insert
# into xml source also unescape html entities # into xml source also unescape html entities
src_xml = re.sub(r'(?<={)(<[^>]*>)+(?=[\{%])|(?<=[%\}])(<[^>]*>)+(?=\})','', src_xml = re.sub(r'(?<={)(<[^>]*>)+(?=[\{%])|(?<=[%\}])(<[^>]*>)+(?=\})', '',
src_xml,flags=re.DOTALL) src_xml, flags=re.DOTALL)
def striptags(m): def striptags(m):
return re.sub('</w:t>.*?(<w:t>|<w:t [^>]*>)','', return re.sub('</w:t>.*?(<w:t>|<w:t [^>]*>)', '',
m.group(0),flags=re.DOTALL) m.group(0), flags=re.DOTALL)
src_xml = re.sub(r'{%(?:(?!%}).)*|{{(?:(?!}}).)*',striptags, src_xml = re.sub(r'{%(?:(?!%}).)*|{{(?:(?!}}).)*', striptags,
src_xml,flags=re.DOTALL) src_xml, flags=re.DOTALL)
# manage table cell colspan # manage table cell colspan
def colspan(m): def colspan(m):
cell_xml = m.group(1) + m.group(3) cell_xml = m.group(1) + m.group(3)
cell_xml = re.sub(r'<w:r[ >](?:(?!<w:r[ >]).)*<w:t></w:t>.*?</w:r>', cell_xml = re.sub(r'<w:r[ >](?:(?!<w:r[ >]).)*<w:t></w:t>.*?</w:r>',
'', cell_xml,flags=re.DOTALL) '', cell_xml, flags=re.DOTALL)
cell_xml = re.sub(r'<w:gridSpan[^/]*/>','', cell_xml, count=1) cell_xml = re.sub(r'<w:gridSpan[^/]*/>', '', cell_xml, count=1)
return re.sub(r'(<w:tcPr[^>]*>)',r'\1<w:gridSpan w:val="{{%s}}"/>' return re.sub(r'(<w:tcPr[^>]*>)', r'\1<w:gridSpan w:val="{{%s}}"/>'
% m.group(2), cell_xml ) % m.group(2), cell_xml)
src_xml = re.sub(r'(<w:tc[ >](?:(?!<w:tc[ >]).)*){%\s*colspan\s+([^%]*)\s*%}(.*?</w:tc>)', src_xml = re.sub(r'(<w:tc[ >](?:(?!<w:tc[ >]).)*){%\s*colspan\s+([^%]*)\s*%}(.*?</w:tc>)',
colspan,src_xml,flags=re.DOTALL) colspan, src_xml, flags=re.DOTALL)
# manage table cell background color # manage table cell background color
def cellbg(m): def cellbg(m):
cell_xml = m.group(1) + m.group(3) cell_xml = m.group(1) + m.group(3)
cell_xml = re.sub(r'<w:r[ >](?:(?!<w:r[ >]).)*<w:t></w:t>.*?</w:r>', cell_xml = re.sub(r'<w:r[ >](?:(?!<w:r[ >]).)*<w:t></w:t>.*?</w:r>',
'',cell_xml,flags=re.DOTALL) '', cell_xml, flags=re.DOTALL)
cell_xml = re.sub(r'<w:shd[^/]*/>','', cell_xml, count=1) cell_xml = re.sub(r'<w:shd[^/]*/>', '', cell_xml, count=1)
return re.sub(r'(<w:tcPr[^>]*>)', return re.sub(r'(<w:tcPr[^>]*>)',
r'\1<w:shd w:val="clear" w:color="auto" w:fill="{{%s}}"/>' r'\1<w:shd w:val="clear" w:color="auto" w:fill="{{%s}}"/>'
% m.group(2), cell_xml) % m.group(2), cell_xml)
src_xml = re.sub(r'(<w:tc[ >](?:(?!<w:tc[ >]).)*){%\s*cellbg\s+([^%]*)\s*%}(.*?</w:tc>)', src_xml = re.sub(r'(<w:tc[ >](?:(?!<w:tc[ >]).)*){%\s*cellbg\s+([^%]*)\s*%}(.*?</w:tc>)',
cellbg,src_xml,flags=re.DOTALL) cellbg, src_xml, flags=re.DOTALL)
# avoid {{r and {%r tags to strip MS xml tags too far # avoid {{r and {%r tags to strip MS xml tags too far
# ensure space preservation when splitting # ensure space preservation when splitting
src_xml = re.sub(r'<w:t>((?:(?!<w:t>).)*)({{r\s.*?}}|{%r\s.*?%})', src_xml = re.sub(r'<w:t>((?:(?!<w:t>).)*)({{r\s.*?}}|{%r\s.*?%})',
r'<w:t xml:space="preserve">\1\2', r'<w:t xml:space="preserve">\1\2',
src_xml,flags=re.DOTALL) src_xml, flags=re.DOTALL)
src_xml = re.sub(r'({{r\s.*?}}|{%r\s.*?%})', src_xml = re.sub(r'({{r\s.*?}}|{%r\s.*?%})',
r'</w:t></w:r><w:r><w:t xml:space="preserve">\1</w:t></w:r><w:r><w:t xml:space="preserve">', r'</w:t></w:r><w:r><w:t xml:space="preserve">\1</w:t></w:r><w:r><w:t xml:space="preserve">',
src_xml,flags=re.DOTALL) src_xml, flags=re.DOTALL)
# {%- will merge with previous paragraph text # {%- will merge with previous paragraph text
src_xml = re.sub(r'</w:t>(?:(?!</w:t>).)*?{%-','{%',src_xml,flags=re.DOTALL) src_xml = re.sub(r'</w:t>(?:(?!</w:t>).)*?{%-', '{%', src_xml, flags=re.DOTALL)
# -%} will merge with next paragraph text # -%} will merge with next paragraph text
src_xml = re.sub(r'-%}(?:(?!<w:t[ >]).)*?<w:t[^>]*?>','%}',src_xml,flags=re.DOTALL) src_xml = re.sub(r'-%}(?:(?!<w:t[ >]).)*?<w:t[^>]*?>', '%}', src_xml, flags=re.DOTALL)
for y in ['tr', 'tc', 'p', 'r']: for y in ['tr', 'tc', 'p', 'r']:
# replace into xml code the row/paragraph/run containing # replace into xml code the row/paragraph/run containing
# {%y xxx %} or {{y xxx}} template tag # {%y xxx %} or {{y xxx}} template tag
# by {% xxx %} or {{ xx }} without any surronding <w:y> tags : # by {% xxx %} or {{ xx }} without any surronding <w:y> tags :
# This is mandatory to have jinja2 generating correct xml code # This is mandatory to have jinja2 generating correct xml code
pat = r'<w:%(y)s[ >](?:(?!<w:%(y)s[ >]).)*({%%|{{)%(y)s ([^}%%]*(?:%%}|}})).*?</w:%(y)s>' % {'y':y} pat = r'<w:%(y)s[ >](?:(?!<w:%(y)s[ >]).)*({%%|{{)%(y)s ([^}%%]*(?:%%}|}})).*?</w:%(y)s>' % {'y': y}
src_xml = re.sub(pat, r'\1 \2',src_xml,flags=re.DOTALL) src_xml = re.sub(pat, r'\1 \2', src_xml, flags=re.DOTALL)
# add vMerge # add vMerge
# use {% vm %} to make this table cell and its copies be vertically merged within a {% for %} # 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) h_merge_tc, src_xml, flags=re.DOTALL)
def clean_tags(m): def clean_tags(m):
return ( m.group(0) return (m.group(0)
.replace(r"&#8216;","'") .replace(r"&#8216;", "'")
.replace('&lt;','<') .replace('&lt;', '<')
.replace('&gt;','>') .replace('&gt;', '>')
.replace(u'',u'"') .replace(u'', u'"')
.replace(u'',u'"') .replace(u'', u'"')
.replace(u"",u"'") .replace(u"", u"'")
.replace(u"",u"'") ) .replace(u"", u"'"))
src_xml = re.sub(r'(?<=\{[\{%])(.*?)(?=[\}%]})',clean_tags,src_xml) src_xml = re.sub(r'(?<=\{[\{%])(.*?)(?=[\}%]})', clean_tags, src_xml)
return 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'<w:p>', '\n<w:p>') src_xml = src_xml.replace(r'<w:p>', '\n<w:p>')
try: try:
if jinja_env: if jinja_env:
@ -223,14 +224,14 @@ class DocxTemplate(object):
src_xml.splitlines()[line_number:(line_number + 7)]) src_xml.splitlines()[line_number:(line_number + 7)])
raise exc raise exc
dst_xml = dst_xml.replace('\n<w:p>', '<w:p>') dst_xml = dst_xml.replace('\n<w:p>', '<w:p>')
dst_xml = ( dst_xml dst_xml = (dst_xml
.replace('{_{','{{') .replace('{_{', '{{')
.replace('}_}','}}') .replace('}_}', '}}')
.replace('{_%','{%') .replace('{_%', '{%')
.replace('%_}','%}') ) .replace('%_}', '%}'))
return dst_xml 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.get_xml()
xml = self.patch_xml(xml) xml = self.patch_xml(xml)
xml = self.render_xml(xml, context, jinja_env) xml = self.render_xml(xml, context, jinja_env)
@ -246,13 +247,13 @@ class DocxTemplate(object):
if (val.reltype == uri) and (val.target_part.blob): if (val.reltype == uri) and (val.target_part.blob):
yield relKey, self.xml_to_string(parse_xml(val.target_part.blob)) yield relKey, self.xml_to_string(parse_xml(val.target_part.blob))
def get_headers_footers_encoding(self,xml): def get_headers_footers_encoding(self, xml):
m = re.match(r'<\?xml[^\?]+\bencoding="([^"]+)"',xml,re.I) m = re.match(r'<\?xml[^\?]+\bencoding="([^"]+)"', xml, re.I)
if m: if m:
return m.group(1) return m.group(1)
return 'utf-8' 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): for relKey, xml in self.get_headers_footers_xml(uri):
encoding = self.get_headers_footers_encoding(xml) encoding = self.get_headers_footers_encoding(xml)
xml = self.patch_xml(xml) xml = self.patch_xml(xml)
@ -317,7 +318,7 @@ class DocxTemplate(object):
width = 0.0 width = 0.0
new_average = None new_average = None
for c in columns: 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')) width += float(c.get(ns+'w'))
# try to keep proportion of table # try to keep proportion of table
if width > 0: if width > 0:
@ -376,14 +377,13 @@ class DocxTemplate(object):
extra_space = removed_width / len(columns_left) extra_space = removed_width / len(columns_left)
extra_space = int(extra_space) extra_space = int(extra_space)
for c in columns_left: for c in columns_left:
c.set(ns+'w', str(int(float(c.get(ns+'w')) + extra_space))) c.set(ns+'w', str(int(float(c.get(ns+'w')) + extra_space)))
return tree return tree
def new_subdoc(self,docpath=None): def new_subdoc(self, docpath=None):
return Subdoc(self,docpath) return Subdoc(self, docpath)
@staticmethod @staticmethod
def get_file_crc(file_obj): def get_file_crc(file_obj):
@ -396,7 +396,7 @@ class DocxTemplate(object):
crc = (binascii.crc32(buf) & 0xFFFFFFFF) crc = (binascii.crc32(buf) & 0xFFFFFFFF)
return crc 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 """Replace one media by another one into a docx
This has been done mainly because it is not possible to add images in 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: with open(dst_file, 'rb') as fh:
self.crc_to_new_media[crc] = fh.read() 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. """Replace embedded picture with original-name given by embedded_file.
(give only the file basename, not the full path) (give only the file basename, not the full path)
The new picture is given by dst_file (either a filename or a file-like 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) for replace_embedded and replace_media)
""" """
if hasattr(dst_file,'read'): if hasattr(dst_file, 'read'):
# NOTE: file extension not checked # NOTE: file extension not checked
self.pic_to_replace[embedded_file]=dst_file.read() self.pic_to_replace[embedded_file] = dst_file.read()
else: else:
emp_path,emb_ext=os.path.splitext(embedded_file) emp_path, emb_ext = os.path.splitext(embedded_file)
dst_path,dst_ext=os.path.splitext(dst_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') raise ValueError('replace_pic: extensions must match')
with open(dst_file, 'rb') as fh: 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 """Replace one embdded object by another one into a docx
This has been done mainly because it is not possible to add images 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) crc = self.get_file_crc(src_file)
self.crc_to_new_embedded[crc] = fh.read() 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 """Replace one file in the docx file
First note that a MSWord .docx file is in fact a zip 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() self.zipname_to_replace[zipname] = fh.read()
def post_processing(self, docx_file): def post_processing(self, docx_file):
if ( self.crc_to_new_media or if (self.crc_to_new_media or
self.crc_to_new_embedded or self.crc_to_new_embedded or
self.zipname_to_replace ): self.zipname_to_replace):
if hasattr(docx_file, 'read'): if hasattr(docx_file, 'read'):
tmp_file = io.BytesIO() tmp_file = io.BytesIO()
@ -520,11 +520,11 @@ class DocxTemplate(object):
buf = zin.read(item.filename) buf = zin.read(item.filename)
if item.filename in self.zipname_to_replace: if item.filename in self.zipname_to_replace:
zout.writestr(item, self.zipname_to_replace[item.filename]) zout.writestr(item, self.zipname_to_replace[item.filename])
elif ( item.filename.startswith('word/media/') and elif (item.filename.startswith('word/media/') and
item.CRC in self.crc_to_new_media ): item.CRC in self.crc_to_new_media):
zout.writestr(item, self.crc_to_new_media[item.CRC]) zout.writestr(item, self.crc_to_new_media[item.CRC])
elif ( item.filename.startswith('word/embeddings/') and elif (item.filename.startswith('word/embeddings/') and
item.CRC in self.crc_to_new_embedded): item.CRC in self.crc_to_new_embedded):
zout.writestr(item, self.crc_to_new_embedded[item.CRC]) zout.writestr(item, self.crc_to_new_embedded[item.CRC])
else: else:
zout.writestr(item, buf) zout.writestr(item, buf)
@ -540,70 +540,70 @@ class DocxTemplate(object):
self.build_pic_map() self.build_pic_map()
# Do the actual replacement # 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: if embedded_file not in self.pic_map:
raise ValueError('Picture "%s" not found in the docx template' raise ValueError('Picture "%s" not found in the docx template'
% embedded_file) % embedded_file)
self.pic_map[embedded_file][1]._blob=stream self.pic_map[embedded_file][1]._blob = stream
def build_pic_map(self): def build_pic_map(self):
"""Searches in docx template all the xml pictures tag and store them """Searches in docx template all the xml pictures tag and store them
in pic_map dict""" in pic_map dict"""
if self.pic_to_replace: if self.pic_to_replace:
# Main document # Main document
part=self.docx.part part = self.docx.part
self.pic_map.update(self._img_filename_to_part(part)) self.pic_map.update(self._img_filename_to_part(part))
# Header/Footer # Header/Footer
for relid, rel in six.iteritems(self.docx.part.rels): 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)) self.pic_map.update(self._img_filename_to_part(rel.target_part))
def get_pic_map(self): def get_pic_map(self):
return self.pic_map 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: for gd in gds:
rel=None rel = None
# Either IMAGE, CHART, SMART_ART, ... # Either IMAGE, CHART, SMART_ART, ...
try: 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 # Either PICTURE or LINKED_PICTURE image
blip=gd.xpath('pic:pic/pic:blipFill/a:blip', blip = gd.xpath('pic:pic/pic:blipFill/a:blip',
namespaces=docx.oxml.ns.nsmap)[0] namespaces=docx.oxml.ns.nsmap)[0]
dest=blip.xpath('@r:embed',namespaces=docx.oxml.ns.nsmap) dest = blip.xpath('@r:embed', namespaces=docx.oxml.ns.nsmap)
if len(dest)>0: if len(dest) > 0:
rel=dest[0] rel = dest[0]
else: else:
continue continue
else: else:
continue continue
#title=inl.xpath('wp:docPr/@title',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', name = gd.xpath('pic:pic/pic:nvPicPr/pic:cNvPr/@name',
namespaces=docx.oxml.ns.nsmap)[0] namespaces=docx.oxml.ns.nsmap)[0]
part_map[name]=(doc_part.rels[rel].target_ref, part_map[name] = (doc_part.rels[rel].target_ref,
doc_part.rels[rel].target_part) doc_part.rels[rel].target_part)
# FIXME: figure out what exceptions are thrown here and catch more specific exceptions
except: except Exception:
continue continue
return part_map 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, return self.docx._part.relate_to(url, REL_TYPE.HYPERLINK,
is_external=True) is_external=True)
def save(self,filename,*args,**kwargs): def save(self, filename, *args, **kwargs):
self.pre_processing() self.pre_processing()
self.docx.save(filename,*args,**kwargs) self.docx.save(filename, *args, **kwargs)
self.post_processing(filename) self.post_processing(filename)
def get_undeclared_template_variables(self, jinja_env=None): def get_undeclared_template_variables(self, jinja_env=None):
@ -621,19 +621,19 @@ class DocxTemplate(object):
class Subdoc(object): class Subdoc(object):
""" Class for subdocument to insert into master document """ """ Class for subdocument to insert into master document """
def __init__(self, tpl,docpath=None): def __init__(self, tpl, docpath=None):
self.tpl = tpl self.tpl = tpl
self.docx = tpl.get_docx() self.docx = tpl.get_docx()
self.subdocx = Document(docpath) self.subdocx = Document(docpath)
self.subdocx._part = self.docx._part self.subdocx._part = self.docx._part
def __getattr__(self, name) : def __getattr__(self, name):
return getattr(self.subdocx, name) return getattr(self.subdocx, name)
def _get_xml(self): def _get_xml(self):
if self.subdocx._element.body.sectPr is not None: if self.subdocx._element.body.sectPr is not None:
self.subdocx._element.body.remove(self.subdocx._element.body.sectPr) self.subdocx._element.body.remove(self.subdocx._element.body.sectPr)
xml = re.sub(r'</?w:body[^>]*>','',etree.tostring( xml = re.sub(r'</?w:body[^>]*>', '', etree.tostring(
self.subdocx._element.body, encoding='unicode', pretty_print=False)) self.subdocx._element.body, encoding='unicode', pretty_print=False))
return xml return xml
@ -658,18 +658,19 @@ class RichText(object):
if text: if text:
self.add(text, **text_prop) self.add(text, **text_prop)
def add(self, text, style=None, def add(self, text,
color=None, style=None,
highlight=None, color=None,
size=None, highlight=None,
subscript=None, size=None,
superscript=None, subscript=None,
bold=False, superscript=None,
italic=False, bold=False,
underline=False, italic=False,
strike=False, underline=False,
font=None, strike=False,
url_id=None): font=None,
url_id=None):
# If a RichText is added # If a RichText is added
if isinstance(text, RichText): if isinstance(text, RichText):
@ -680,7 +681,7 @@ class RichText(object):
if not isinstance(text, (six.text_type, six.binary_type)): if not isinstance(text, (six.text_type, six.binary_type)):
text = six.text_type(text) text = six.text_type(text)
if not isinstance(text, six.text_type): if not isinstance(text, six.text_type):
text = text.decode('utf-8',errors='ignore') text = text.decode('utf-8', errors='ignore')
text = (escape(text) text = (escape(text)
.replace('\n', NEWLINE_XML) .replace('\n', NEWLINE_XML)
.replace('\a', NEWPARAGRAPH_XML) .replace('\a', NEWPARAGRAPH_XML)
@ -711,26 +712,24 @@ class RichText(object):
if italic: if italic:
prop += u'<w:i/>' prop += u'<w:i/>'
if underline: if underline:
if underline not in ['single','double']: if underline not in ['single', 'double']:
underline = 'single' underline = 'single'
prop += u'<w:u w:val="%s"/>' % underline prop += u'<w:u w:val="%s"/>' % underline
if strike: if strike:
prop += u'<w:strike/>' prop += u'<w:strike/>'
if font: if font:
prop += ( u'<w:rFonts w:ascii="{font}" w:hAnsi="{font}" w:cs="{font}"/>' prop += (u'<w:rFonts w:ascii="{font}" w:hAnsi="{font}" w:cs="{font}"/>'
.format(font=font) ) .format(font=font))
xml = u'<w:r>' xml = u'<w:r>'
if prop: if prop:
xml += u'<w:rPr>%s</w:rPr>' % prop xml += u'<w:rPr>%s</w:rPr>' % prop
xml += u'<w:t xml:space="preserve">%s</w:t></w:r>' % text xml += u'<w:t xml:space="preserve">%s</w:t></w:r>' % text
if url_id: if url_id:
xml = ( u'<w:hyperlink r:id="%s" w:tgtFrame="_blank">%s</w:hyperlink>' xml = (u'<w:hyperlink r:id="%s" w:tgtFrame="_blank">%s</w:hyperlink>'
% (url_id, xml) ) % (url_id, xml))
self.xml += xml self.xml += xml
def __unicode__(self): def __unicode__(self):
return self.xml return self.xml
@ -802,5 +801,3 @@ class InlineImage(object):
def __html__(self): def __html__(self):
return self._insert_image() return self._insert_image()

View File

@ -6,6 +6,7 @@ import sys
# To register onto Pypi : # To register onto Pypi :
# python setup.py sdist bdist_wheel upload # python setup.py sdist bdist_wheel upload
def read(*names): def read(*names):
values = dict() values = dict()
for name in names: for name in names:
@ -28,18 +29,20 @@ News
%(CHANGES)s %(CHANGES)s
""" % read('README', 'CHANGES') """ % read('README', 'CHANGES')
def get_version(pkg): 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): if sys.version_info >= (3, 0):
fh = open(path, encoding='utf-8') # required to read utf-8 file on windows fh = open(path, encoding='utf-8') # required to read utf-8 file on windows
else: 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: 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: if m:
return m.group(1) return m.group(1)
raise RuntimeError("Unable to find __version__ string in %s." % path) raise RuntimeError("Unable to find __version__ string in %s." % path)
setup(name='docxtpl', setup(name='docxtpl',
version=get_version('docxtpl'), version=get_version('docxtpl'),
description='Python docx template engine', description='Python docx template engine',

View File

@ -7,14 +7,34 @@ Created : 2015-03-12
from docxtpl import DocxTemplate, RichText from docxtpl import DocxTemplate, RichText
tpl=DocxTemplate('templates/cellbg_tpl.docx') tpl = DocxTemplate('templates/cellbg_tpl.docx')
context = { context = {
'alerts' : [ '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-10',
{'date' : '2015-03-12', 'desc' : RichText('Information'), 'type' : 'INFO', 'bg': '8888FF' }, 'desc': RichText('Very critical alert', color='FF0000', bold=True),
{'date' : '2015-03-13', 'desc' : RichText('Debug trace'), 'type' : 'DEBUG', 'bg': 'FF00FF' }, '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',
},
], ],
} }

View File

@ -10,6 +10,7 @@ import jinja2
jinja_env = jinja2.Environment() jinja_env = jinja2.Environment()
# to create new filters, first create functions that accept the value to filter # to create new filters, first create functions that accept the value to filter
# as first argument, and filter parameters as next arguments # as first argument, and filter parameters as next arguments
def my_filterA(value, my_string_arg): 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_value = value + my_float_arg
return return_value return return_value
# Then, declare them to jinja like this : # Then, declare them to jinja like this :
jinja_env.filters['my_filterA'] = my_filterA jinja_env.filters['my_filterA'] = my_filterA
jinja_env.filters['my_filterB'] = my_filterB 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.render(context, jinja_env)
tpl.save('output/custom_jinja_filters.docx') tpl.save('output/custom_jinja_filters.docx')

View File

@ -1,14 +1,14 @@
from docxtpl import DocxTemplate from docxtpl import DocxTemplate
tpl=DocxTemplate('templates/dynamic_table_tpl.docx') tpl = DocxTemplate('templates/dynamic_table_tpl.docx')
context = { context = {
'col_labels' : ['fruit', 'vegetable', 'stone', 'thing'], 'col_labels': ['fruit', 'vegetable', 'stone', 'thing'],
'tbl_contents': [ 'tbl_contents': [
{'label': 'yellow', 'cols': ['banana', 'capsicum', 'pyrite', 'taxi']}, {'label': 'yellow', 'cols': ['banana', 'capsicum', 'pyrite', 'taxi']},
{'label': 'red', 'cols': ['apple', 'tomato', 'cinnabar', 'doubledecker']}, {'label': 'red', 'cols': ['apple', 'tomato', 'cinnabar', 'doubledecker']},
{'label': 'green', 'cols': ['guava', 'cucumber', 'aventurine', 'card']}, {'label': 'green', 'cols': ['guava', 'cucumber', 'aventurine', 'card']},
] ],
} }
tpl.render(context) tpl.render(context)

View File

@ -8,29 +8,38 @@ Created : 2017-09-09
from docxtpl import DocxTemplate from docxtpl import DocxTemplate
# rendering the "dynamic embedded docx": # 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 = { context = {
'name' : 'John Doe', 'name': 'John Doe',
} }
embedded_docx_tpl.render(context) embedded_docx_tpl.render(context)
embedded_docx_tpl.save('output/embedded_embedded_docx.docx') embedded_docx_tpl.save('output/embedded_embedded_docx.docx')
# rendring the main document : # rendring the main document :
tpl=DocxTemplate('templates/embedded_main_tpl.docx') tpl = DocxTemplate('templates/embedded_main_tpl.docx')
context = { context = {
'name' : 'John Doe', 'name': 'John Doe',
} }
tpl.replace_embedded('templates/embedded_dummy.docx','templates/embedded_static_docx.docx') tpl.replace_embedded(
tpl.replace_embedded('templates/embedded_dummy2.docx','output/embedded_embedded_docx.docx') '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) # 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/". # 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... # 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(
tpl.replace_zipname('word/embeddings/Pr_sentation_Microsoft_Office_PowerPoint4.pptx','templates/real_PowerPoint.pptx') '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.render(context)
tpl.save('output/embedded.docx') tpl.save('output/embedded.docx')

View File

@ -1,13 +1,20 @@
from docxtpl import * from docxtpl import DocxTemplate, R, Listing
tpl = DocxTemplate('templates/escape_tpl.docx') tpl = DocxTemplate('templates/escape_tpl.docx')
context = {'myvar': R('"less than" must be escaped : <, this can be done with RichText() or R()'), context = {
'myescvar': 'It can be escaped with a "|e" jinja filter in the template too : < ', 'myvar': R(
'nlnp': R('Here is a multiple\nlines\nstring\aand some\aother\aparagraphs\aNOTE: the current character styling is removed'), '"less than" must be escaped : <, this can be done with RichText() or R()'
'mylisting': Listing('the listing\nwith\nsome\nlines\nand special chars : <>&\f ... and a page break'), ),
'page_break': R('\f'), '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.render(context)
tpl.save('output/escape.docx') tpl.save('output/escape.docx')

View File

@ -14,11 +14,12 @@ XML_RESERVED = """<"&'>"""
tpl = DocxTemplate('templates/escape_tpl_auto.docx') tpl = DocxTemplate('templates/escape_tpl_auto.docx')
context = {'nested_dict': {name(text_type(c)): c for c in XML_RESERVED}, context = {
'autoescape': 'Escaped "str & ing"!', 'nested_dict': {name(text_type(c)): c for c in XML_RESERVED},
'autoescape_unicode': u'This is an escaped <unicode> example \u4f60 & \u6211', 'autoescape': 'Escaped "str & ing"!',
'iteritems': iteritems, 'autoescape_unicode': u'This is an escaped <unicode> example \u4f60 & \u6211',
} 'iteritems': iteritems,
}
tpl.render(context, autoescape=True) tpl.render(context, autoescape=True)

View File

@ -7,17 +7,19 @@ Created : 2015-03-12
from docxtpl import DocxTemplate from docxtpl import DocxTemplate
tpl=DocxTemplate('templates/header_footer_tpl.docx') tpl = DocxTemplate('templates/header_footer_tpl.docx')
sd = tpl.new_subdoc() 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 = { context = {
'title' : 'Header and footer test', 'title': 'Header and footer test',
'company_name' : 'The World Wide company', 'company_name': 'The World Wide company',
'date' : '2016-03-17', 'date': '2016-03-17',
'mysubdoc' : sd, 'mysubdoc': sd,
} }
tpl.render(context) tpl.render(context)
tpl.save('output/header_footer.docx') tpl.save('output/header_footer.docx')

View File

@ -7,10 +7,10 @@ Created : 2015-03-12
from docxtpl import DocxTemplate from docxtpl import DocxTemplate
tpl=DocxTemplate('templates/header_footer_entities_tpl.docx') tpl = DocxTemplate('templates/header_footer_entities_tpl.docx')
context = { context = {
'title' : 'Header and footer test', 'title': 'Header and footer test',
} }
tpl.render(context) tpl.render(context)

View File

@ -9,11 +9,11 @@ from docxtpl import DocxTemplate
DEST_FILE = 'output/header_footer_image.docx' DEST_FILE = 'output/header_footer_image.docx'
tpl=DocxTemplate('templates/header_footer_image_tpl.docx') tpl = DocxTemplate('templates/header_footer_image_tpl.docx')
context = { 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.render(context)
tpl.save(DEST_FILE) tpl.save(DEST_FILE)

View File

@ -11,10 +11,10 @@ import io
DEST_FILE = 'output/header_footer_image_file_obj.docx' DEST_FILE = 'output/header_footer_image_file_obj.docx'
DEST_FILE2 = 'output/header_footer_image_file_obj2.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 = { context = {
'mycompany' : 'The World Wide company', 'mycompany': 'The World Wide company',
} }
dummy_pic = io.BytesIO(open('templates/dummy_pic_for_header.png', 'rb').read()) 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) file_obj.seek(0)
with open(DEST_FILE2, 'wb') as f: with open(DEST_FILE2, 'wb') as f:
f.write(file_obj.read()) f.write(file_obj.read())

View File

@ -9,16 +9,18 @@ Edited : 2016-07-19 by Eric Lapouyade
from docxtpl import DocxTemplate from docxtpl import DocxTemplate
tpl=DocxTemplate('templates/header_footer_tpl_utf8.docx') tpl = DocxTemplate('templates/header_footer_tpl_utf8.docx')
sd = tpl.new_subdoc() 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 = { context = {
'title' : u'헤더와 푸터', 'title': u'헤더와 푸터',
'company_name' : u'세계적 회사', 'company_name': u'세계적 회사',
'date' : u'2016-03-17', 'date': u'2016-03-17',
'mysubdoc' : sd, 'mysubdoc': sd,
} }
tpl.render(context) tpl.render(context)

View File

@ -6,32 +6,40 @@ Created : 2017-01-14
''' '''
from docxtpl import DocxTemplate, InlineImage 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 = { context = {
'myimage' : InlineImage(tpl,'templates/python_logo.png',width=Mm(20)), 'myimage': InlineImage(tpl, 'templates/python_logo.png', width=Mm(20)),
'myimageratio': InlineImage(tpl, 'templates/python_jpeg.jpg', width=Mm(30), height=Mm(60)), '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'}, 'frameworks': [
{
{'image' : InlineImage(tpl,'templates/zope.png',height=Mm(10)), 'image': InlineImage(tpl, 'templates/django.png', height=Mm(10)),
'desc' : 'Zope is a leading Open Source Application Server and Content Management Framework'}, 'desc': 'The web framework for perfectionists with deadlines',
},
{'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/zope.png', height=Mm(10)),
'desc': 'Zope is a leading Open Source Application Server and Content Management Framework',
{'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/pyramid.png', height=Mm(10)),
{'image': InlineImage(tpl, 'templates/tornado.png', height=Mm(10)), 'desc': 'Pyramid is a lightweight Python web framework aimed at taking small web apps into big web apps.',
'desc': 'Tornado is a Python web framework and asynchronous networking library.'}, },
] {
'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 # testing that it works also when autoescape has been forced to True
jinja_env = jinja2.Environment(autoescape=True) jinja_env = jinja2.Environment(autoescape=True)

View File

@ -7,10 +7,10 @@ Created : 2015-03-12
from docxtpl import DocxTemplate from docxtpl import DocxTemplate
tpl=DocxTemplate('templates/merge_paragraph_tpl.docx') tpl = DocxTemplate('templates/merge_paragraph_tpl.docx')
context = { context = {
'living_in_town' : True, 'living_in_town': True,
} }
tpl.render(context) tpl.render(context)

View File

@ -7,26 +7,38 @@ Created : 2016-03-26
from docxtpl import DocxTemplate from docxtpl import DocxTemplate
tpl=DocxTemplate('templates/nested_for_tpl.docx') tpl = DocxTemplate('templates/nested_for_tpl.docx')
context = { context = {
'dishes' : [ 'dishes': [
{'name' : 'Pizza', 'ingredients' : ['bread','tomato', 'ham', 'cheese']}, {'name': 'Pizza', 'ingredients': ['bread', 'tomato', 'ham', 'cheese']},
{'name' : 'Hamburger', 'ingredients' : ['bread','chopped steak', 'cheese', 'sauce']}, {
{'name' : 'Apple pie', 'ingredients' : ['flour','apples', 'suggar', 'quince jelly']}, '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) tpl.render(context)

View File

@ -7,19 +7,19 @@ Created : 2015-03-12
from docxtpl import DocxTemplate from docxtpl import DocxTemplate
tpl=DocxTemplate('templates/order_tpl.docx') tpl = DocxTemplate('templates/order_tpl.docx')
context = { context = {
'customer_name' : 'Eric', 'customer_name': 'Eric',
'items' : [ 'items': [
{'desc' : 'Python interpreters', 'qty' : 2, 'price' : 'FREE' }, {'desc': 'Python interpreters', 'qty': 2, 'price': 'FREE'},
{'desc' : 'Django projects', 'qty' : 5403, 'price' : 'FREE' }, {'desc': 'Django projects', 'qty': 5403, 'price': 'FREE'},
{'desc' : 'Guido', 'qty' : 1, 'price' : '100,000,000.00' }, {'desc': 'Guido', 'qty': 1, 'price': '100,000,000.00'},
], ],
'in_europe' : True, 'in_europe': True,
'is_paid': False, 'is_paid': False,
'company_name' : 'The World Wide company', 'company_name': 'The World Wide company',
'total_price' : '100,000,000.00' 'total_price': '100,000,000.00',
} }
tpl.render(context) tpl.render(context)

View File

@ -9,10 +9,10 @@ from docxtpl import DocxTemplate
DEST_FILE = 'output/replace_picture.docx' DEST_FILE = 'output/replace_picture.docx'
tpl=DocxTemplate('templates/replace_picture_tpl.docx') tpl = DocxTemplate('templates/replace_picture_tpl.docx')
context = {} context = {}
tpl.replace_pic('python_logo.png','templates/python.png') tpl.replace_pic('python_logo.png', 'templates/python.png')
tpl.render(context) tpl.render(context)
tpl.save(DEST_FILE) tpl.save(DEST_FILE)

View File

@ -7,7 +7,7 @@ Created : 2015-03-26
from docxtpl import DocxTemplate, RichText from docxtpl import DocxTemplate, RichText
tpl=DocxTemplate('templates/richtext_tpl.docx') tpl = DocxTemplate('templates/richtext_tpl.docx')
rt = RichText() rt = RichText()
rt.add('a rich text', style='myrichtextstyle') rt.add('a rich text', style='myrichtextstyle')
@ -23,16 +23,16 @@ rt.add(' or ')
rt.add('big', size=60) rt.add('big', size=60)
rt.add(' text.') rt.add(' text.')
rt.add('\nYou can add an hyperlink, here to ') 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('\nEt voilà ! ')
rt.add('\n1st line') rt.add('\n1st line')
rt.add('\n2nd line') rt.add('\n2nd line')
rt.add('\n3rd line') rt.add('\n3rd line')
rt.add('\n\n<cool>') rt.add('\n\n<cool>')
rt.add('\nFonts :\n',underline=True) rt.add('\nFonts :\n', underline=True)
rt.add('Arial\n',font='Arial') rt.add('Arial\n', font='Arial')
rt.add('Courier New\n',font='Courier New') rt.add('Courier New\n', font='Courier New')
rt.add('Times New Roman\n',font='Times New Roman') rt.add('Times New Roman\n', font='Times New Roman')
rt.add('\n\nHere some') rt.add('\n\nHere some')
rt.add('superscript', superscript=True) rt.add('superscript', superscript=True)
rt.add(' and some') rt.add(' and some')
@ -42,7 +42,7 @@ rt_embedded = RichText('an example of ')
rt_embedded.add(rt) rt_embedded.add(rt)
context = { context = {
'example' : rt_embedded, 'example': rt_embedded,
} }
tpl.render(context) tpl.render(context)

View File

@ -7,12 +7,10 @@ Created : 2015-03-26
from docxtpl import DocxTemplate, RichText from docxtpl import DocxTemplate, RichText
tpl=DocxTemplate('templates/richtext_and_if_tpl.docx') tpl = DocxTemplate('templates/richtext_and_if_tpl.docx')
context = { context = {'foobar': RichText('Foobar!', color='ff0000')}
'foobar': RichText('Foobar!', color='ff0000')
}
tpl.render(context) tpl.render(context)
tpl.save('output/richtext_and_if.docx') tpl.save('output/richtext_and_if.docx')

View File

@ -6,13 +6,13 @@ import os
tests = sorted(glob.glob('[A-Za-z]*.py')) tests = sorted(glob.glob('[A-Za-z]*.py'))
excludes = ['runtests.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): if not os.path.exists(output_dir):
os.mkdir(output_dir) os.mkdir(output_dir)
for test in tests: for test in tests:
if test not in excludes: if test not in excludes:
six.print_('%s ...' % test) six.print_('%s ...' % test)
subprocess.call(['python','./%s' % test]) subprocess.call(['python', './%s' % test])
six.print_('Done.') six.print_('Done.')

View File

@ -8,7 +8,7 @@ Created : 2015-03-12
from docxtpl import DocxTemplate from docxtpl import DocxTemplate
from docx.shared import Inches from docx.shared import Inches
tpl=DocxTemplate('templates/subdoc_tpl.docx') tpl = DocxTemplate('templates/subdoc_tpl.docx')
sd = tpl.new_subdoc() sd = tpl.new_subdoc()
p = sd.add_paragraph('This is a sub-document inserted into a bigger one') 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[0].text = 'Qty'
hdr_cells[1].text = 'Id' hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc' hdr_cells[2].text = 'Desc'
recordset=( (1,101,'Spam'), recordset = ((1, 101, 'Spam'), (2, 42, 'Eggs'), (3, 631, 'Spam,spam, eggs, and ham'))
(2,42,'Eggs'),
(3,631,'Spam,spam, eggs, and ham') )
for item in recordset: for item in recordset:
row_cells = table.add_row().cells row_cells = table.add_row().cells
row_cells[0].text = str(item[0]) row_cells[0].text = str(item[0])
@ -40,7 +38,7 @@ for item in recordset:
row_cells[2].text = item[2] row_cells[2].text = item[2]
context = { context = {
'mysubdoc' : sd, 'mysubdoc': sd,
} }
tpl.render(context) tpl.render(context)

View File

@ -1,4 +1,4 @@
from docxtpl import DocxTemplate, RichText from docxtpl import DocxTemplate
from jinja2.exceptions import TemplateError from jinja2.exceptions import TemplateError
import six import six
@ -7,9 +7,7 @@ six.print_("Generating template error for testing (so it is safe to ignore) :")
six.print_('.' * 80) six.print_('.' * 80)
try: try:
tpl = DocxTemplate('templates/template_error_tpl.docx') tpl = DocxTemplate('templates/template_error_tpl.docx')
tpl.render({ tpl.render({'test_variable': 'test variable value'})
'test_variable' : 'test variable value'
})
except TemplateError as the_error: except TemplateError as the_error:
six.print_(six.text_type(the_error)) six.print_(six.text_type(the_error))
if hasattr(the_error, 'docx_context'): if hasattr(the_error, 'docx_context'):

View File

@ -7,16 +7,16 @@ Created : 2017-10-15
from docxtpl import DocxTemplate from docxtpl import DocxTemplate
tpl=DocxTemplate('templates/vertical_merge_tpl.docx') tpl = DocxTemplate('templates/vertical_merge_tpl.docx')
context = { context = {
'items' : [ 'items': [
{'desc' : 'Python interpreters', 'qty' : 2, 'price' : 'FREE' }, {'desc': 'Python interpreters', 'qty': 2, 'price': 'FREE'},
{'desc' : 'Django projects', 'qty' : 5403, 'price' : 'FREE' }, {'desc': 'Django projects', 'qty': 5403, 'price': 'FREE'},
{'desc' : 'Guido', 'qty' : 1, 'price' : '100,000,000.00' }, {'desc': 'Guido', 'qty': 1, 'price': '100,000,000.00'},
], ],
'total_price' : '100,000,000.00', 'total_price': '100,000,000.00',
'category' : 'Book' 'category': 'Book',
} }
tpl.render(context) tpl.render(context)

View File

@ -1,10 +1,12 @@
from docxtpl import DocxTemplate, RichText from docxtpl import DocxTemplate, RichText
tpl = DocxTemplate('templates/word2016_tpl.docx') tpl = DocxTemplate('templates/word2016_tpl.docx')
tpl.render({ tpl.render(
'test_space' : ' ', {
'test_tabs': 5*'\t', 'test_space': ' ',
'test_space_r' : RichText(' '), 'test_tabs': 5 * '\t',
'test_tabs_r': RichText(5*'\t'), 'test_space_r': RichText(' '),
}) 'test_tabs_r': RichText(5 * '\t'),
}
)
tpl.save('output/word2016.docx') tpl.save('output/word2016.docx')