docform 0.21.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
docform/__init__.py ADDED
@@ -0,0 +1,17 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Docform: fill document templates with data.
4
+
5
+ Based on python-docx-template by Eric Lapouyade.
6
+ """
7
+
8
+ __version__ = "0.21.0"
9
+
10
+ # flake8: noqa
11
+ from .docx import InlineImage, Listing, RichText, R, RichTextParagraph, RP
12
+ from .docx import DocxTemplate, Template
13
+
14
+ try:
15
+ from .docx import Subdoc
16
+ except ImportError:
17
+ pass
docform/__main__.py ADDED
@@ -0,0 +1,176 @@
1
+ import argparse
2
+ import json
3
+ import os
4
+ import sys
5
+
6
+ from .docx.template import DocxTemplate, TemplateError
7
+
8
+ TEMPLATE_ARG = "template_path"
9
+ JSON_ARG = "json_path"
10
+ OUTPUT_ARG = "output_filename"
11
+ OVERWRITE_ARG = "overwrite"
12
+ QUIET_ARG = "quiet"
13
+
14
+
15
+ def make_arg_parser():
16
+ parser = argparse.ArgumentParser(
17
+ usage="python -m docform [-h] [-o] [-q] {} {} {}".format(
18
+ TEMPLATE_ARG, JSON_ARG, OUTPUT_ARG
19
+ ),
20
+ description="Make docx file from existing template docx and json data.",
21
+ )
22
+ parser.add_argument(
23
+ TEMPLATE_ARG, type=str, help="The path to the template docx file."
24
+ )
25
+ parser.add_argument(
26
+ JSON_ARG, type=str, help="The path to the json file with the data."
27
+ )
28
+ parser.add_argument(
29
+ OUTPUT_ARG, type=str, help="The filename to save the generated docx."
30
+ )
31
+ parser.add_argument(
32
+ "-" + OVERWRITE_ARG[0],
33
+ "--" + OVERWRITE_ARG,
34
+ action="store_true",
35
+ help="If output file already exists, overwrites without asking for confirmation",
36
+ )
37
+ parser.add_argument(
38
+ "-" + QUIET_ARG[0],
39
+ "--" + QUIET_ARG,
40
+ action="store_true",
41
+ help="Do not display unnecessary messages",
42
+ )
43
+ return parser
44
+
45
+
46
+ def get_args(parser):
47
+ try:
48
+ parsed_args = vars(parser.parse_args())
49
+ return parsed_args
50
+ # Argument errors raise a SystemExit with code 2. Normal usage of the
51
+ # --help or -h flag raises a SystemExit with code 0.
52
+ except SystemExit as e:
53
+ if e.code == 0:
54
+ raise SystemExit
55
+ else:
56
+ raise RuntimeError(
57
+ "Correct usage is:\n{parser.usage}".format(parser=parser)
58
+ )
59
+
60
+
61
+ def is_argument_valid(arg_name, arg_value, overwrite):
62
+ # Basic checks for the arguments
63
+ if arg_name == TEMPLATE_ARG:
64
+ return os.path.isfile(arg_value) and arg_value.endswith(".docx")
65
+ elif arg_name == JSON_ARG:
66
+ return os.path.isfile(arg_value) and arg_value.endswith(".json")
67
+ elif arg_name == OUTPUT_ARG:
68
+ return arg_value.endswith(".docx") and check_exists_ask_overwrite(
69
+ arg_value, overwrite
70
+ )
71
+ elif arg_name in [OVERWRITE_ARG, QUIET_ARG]:
72
+ return arg_value in [True, False]
73
+
74
+
75
+ def check_exists_ask_overwrite(arg_value, overwrite):
76
+ # If output file does not exist or command was run with overwrite option,
77
+ # returns True, else asks for overwrite confirmation. If overwrite is
78
+ # confirmed returns True, else raises OSError.
79
+ if os.path.exists(arg_value) and not overwrite:
80
+ try:
81
+ msg = (
82
+ "File %s already exists, would you like to overwrite the existing file? "
83
+ "(y/n)" % arg_value
84
+ )
85
+ if input(msg).lower() == "y":
86
+ return True
87
+ else:
88
+ raise OSError
89
+ except OSError:
90
+ raise RuntimeError(
91
+ "File %s already exists, please choose a different name." % arg_value
92
+ )
93
+ else:
94
+ return True
95
+
96
+
97
+ def validate_all_args(parsed_args):
98
+ overwrite = parsed_args[OVERWRITE_ARG]
99
+ # Raises AssertionError if any of the arguments is not validated
100
+ try:
101
+ for arg_name, arg_value in parsed_args.items():
102
+ if not is_argument_valid(arg_name, arg_value, overwrite):
103
+ raise AssertionError
104
+ except AssertionError:
105
+ raise RuntimeError(
106
+ 'The specified {arg_name} "{arg_value}" is not valid.'.format(
107
+ arg_name=arg_name, arg_value=arg_value
108
+ )
109
+ )
110
+
111
+
112
+ def get_json_data(json_path):
113
+ with open(json_path) as file:
114
+ try:
115
+ json_data = json.load(file)
116
+ return json_data
117
+ except json.JSONDecodeError as e:
118
+ print(
119
+ "There was an error on line {e.lineno}, column {e.colno} while trying "
120
+ "to parse file {json_path}".format(e=e, json_path=json_path)
121
+ )
122
+ raise RuntimeError("Failed to get json data.")
123
+
124
+
125
+ def make_docxtemplate(template_path):
126
+ try:
127
+ return DocxTemplate(template_path)
128
+ except TemplateError:
129
+ raise RuntimeError("Could not create docx template.")
130
+
131
+
132
+ def render_docx(doc, json_data):
133
+ try:
134
+ doc.render(json_data)
135
+ return doc
136
+ except TemplateError:
137
+ raise RuntimeError("An error ocurred while trying to render the docx")
138
+
139
+
140
+ def save_file(doc, parsed_args):
141
+ try:
142
+ output_path = parsed_args[OUTPUT_ARG]
143
+ doc.save(output_path)
144
+ if not parsed_args[QUIET_ARG]:
145
+ print(
146
+ "Document successfully generated and saved at {output_path}".format(
147
+ output_path=output_path
148
+ )
149
+ )
150
+ except OSError as e:
151
+ print("{e.strerror}. Could not save file {e.filename}.".format(e=e))
152
+ raise RuntimeError("Failed to save file.")
153
+
154
+
155
+ def main():
156
+ parser = make_arg_parser()
157
+ # Everything is in a try-except block that catches a RuntimeError that is
158
+ # raised if any of the individual functions called cause an error
159
+ # themselves, terminating the main function.
160
+ parsed_args = get_args(parser)
161
+ try:
162
+ validate_all_args(parsed_args)
163
+ json_data = get_json_data(os.path.abspath(parsed_args[JSON_ARG]))
164
+ doc = make_docxtemplate(os.path.abspath(parsed_args[TEMPLATE_ARG]))
165
+ doc = render_docx(doc, json_data)
166
+ save_file(doc, parsed_args)
167
+ except RuntimeError as e:
168
+ print("Error: " + e.__str__(), file=sys.stderr)
169
+ sys.exit(1)
170
+ finally:
171
+ if not parsed_args[QUIET_ARG]:
172
+ print("Exiting program!")
173
+
174
+
175
+ if __name__ == "__main__":
176
+ main()
@@ -0,0 +1,15 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Word (.docx) templates."""
3
+
4
+ # flake8: noqa
5
+ from .inline_image import InlineImage
6
+ from .listing import Listing
7
+ from .richtext import RichText, R, RichTextParagraph, RP
8
+ from .template import DocxTemplate
9
+
10
+ Template = DocxTemplate
11
+
12
+ try:
13
+ from .subdoc import Subdoc
14
+ except ImportError:
15
+ pass
@@ -0,0 +1,102 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Created : 2021-07-30
4
+
5
+ @author: Eric Lapouyade
6
+ """
7
+ from docx.oxml import OxmlElement
8
+ from docx.oxml.ns import qn
9
+
10
+
11
+ class InlineImage(object):
12
+ """Class to generate an inline image
13
+
14
+ This is much faster than using Subdoc class.
15
+ """
16
+
17
+ tpl = None
18
+ image_descriptor = None
19
+ width = None
20
+ height = None
21
+ anchor = None
22
+ title = None
23
+ descr = None
24
+
25
+ def __init__(
26
+ self,
27
+ tpl,
28
+ image_descriptor,
29
+ width=None,
30
+ height=None,
31
+ anchor=None,
32
+ title=None,
33
+ descr=None,
34
+ ):
35
+ self.tpl, self.image_descriptor = tpl, image_descriptor
36
+ self.width, self.height = width, height
37
+ self.anchor = anchor
38
+ self.title = str(title) if title is not None else None
39
+ self.descr = str(descr) if descr is not None else None
40
+
41
+ def _add_hyperlink(self, run, url, part):
42
+ # Create a relationship for the hyperlink
43
+ r_id = part.relate_to(
44
+ url,
45
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",
46
+ is_external=True,
47
+ )
48
+
49
+ # Find the <wp:docPr> and <pic:cNvPr> element
50
+ docPr = run.xpath(".//wp:docPr")[0]
51
+ cNvPr = run.xpath(".//pic:cNvPr")[0]
52
+
53
+ # Create the <a:hlinkClick> element
54
+ hlinkClick1 = OxmlElement("a:hlinkClick")
55
+ hlinkClick1.set(qn("r:id"), r_id)
56
+ hlinkClick2 = OxmlElement("a:hlinkClick")
57
+ hlinkClick2.set(qn("r:id"), r_id)
58
+
59
+ # Insert the <a:hlinkClick> element right after the <wp:docPr> element
60
+ docPr.append(hlinkClick1)
61
+ cNvPr.append(hlinkClick2)
62
+
63
+ return run
64
+
65
+ def _set_doc_properties(self, run):
66
+ docPr = run.xpath(".//wp:docPr")[0]
67
+ cNvPr = run.xpath(".//pic:cNvPr")[0]
68
+
69
+ for elt in (docPr, cNvPr):
70
+ if self.title is not None:
71
+ elt.set("title", self.title)
72
+ if self.descr is not None:
73
+ elt.set("descr", self.descr)
74
+
75
+ def _insert_image(self):
76
+ pic = self.tpl.current_rendering_part.new_pic_inline(
77
+ self.image_descriptor,
78
+ self.width,
79
+ self.height,
80
+ )
81
+ if self.title is not None or self.descr is not None:
82
+ self._set_doc_properties(pic)
83
+ if self.anchor:
84
+ if pic.xpath(".//a:blip"):
85
+ pic = self._add_hyperlink(
86
+ pic, self.anchor, self.tpl.current_rendering_part
87
+ )
88
+ pic = pic.xml
89
+
90
+ return (
91
+ "</w:t></w:r><w:r><w:drawing>%s</w:drawing></w:r><w:r>"
92
+ '<w:t xml:space="preserve">' % pic
93
+ )
94
+
95
+ def __unicode__(self):
96
+ return self._insert_image()
97
+
98
+ def __str__(self):
99
+ return self._insert_image()
100
+
101
+ def __html__(self):
102
+ return self._insert_image()
@@ -0,0 +1,35 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Created : 2021-07-30
4
+
5
+ @author: Eric Lapouyade
6
+ """
7
+ try:
8
+ from html import escape
9
+ except ImportError:
10
+ # cgi.escape is deprecated in python 3.7
11
+ from cgi import escape
12
+
13
+
14
+ class Listing(object):
15
+ r"""class to manage \n and \a without to use RichText,
16
+ by this way you keep the current template styling
17
+
18
+ use {{ mylisting }} in your template and
19
+ context={ mylisting:Listing(the_listing_with_newlines) }
20
+ """
21
+
22
+ def __init__(self, text):
23
+ # If not a string : cast to string (ex: int, dict etc...)
24
+ if not isinstance(text, (str, bytes)):
25
+ text = str(text)
26
+ self.xml = escape(text)
27
+
28
+ def __unicode__(self):
29
+ return self.xml
30
+
31
+ def __str__(self):
32
+ return self.xml
33
+
34
+ def __html__(self):
35
+ return self.xml
@@ -0,0 +1,180 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Created : 2021-07-30
4
+
5
+ @author: Eric Lapouyade
6
+ """
7
+ try:
8
+ from html import escape
9
+ except ImportError:
10
+ # cgi.escape is deprecated in python 3.7
11
+ from cgi import escape
12
+
13
+
14
+ class RichText(object):
15
+ """class to generate Rich Text when using templates variables
16
+
17
+ This is much faster than using Subdoc class,
18
+ but this only for texts INSIDE an existing paragraph.
19
+ """
20
+
21
+ def __init__(self, text=None, **text_prop):
22
+ self.xml = ""
23
+ if text:
24
+ self.add(text, **text_prop)
25
+
26
+ def add(
27
+ self,
28
+ text,
29
+ style=None,
30
+ color=None,
31
+ highlight=None,
32
+ size=None,
33
+ subscript=None,
34
+ superscript=None,
35
+ bold=False,
36
+ italic=False,
37
+ underline=False,
38
+ strike=False,
39
+ font=None,
40
+ url_id=None,
41
+ rtl=False,
42
+ lang=None,
43
+ ):
44
+
45
+ # If a RichText is added
46
+ if isinstance(text, RichText):
47
+ self.xml += text.xml
48
+ return
49
+
50
+ # # If nothing to add : just return
51
+ # if text is None or text == "":
52
+ # return
53
+
54
+ # If not a string : cast to string (ex: int, dict etc...)
55
+ if not isinstance(text, (str, bytes)):
56
+ text = str(text)
57
+ if not isinstance(text, str):
58
+ text = text.decode("utf-8", errors="ignore")
59
+ text = escape(text)
60
+
61
+ prop = ""
62
+
63
+ if style:
64
+ prop += '<w:rStyle w:val="%s"/>' % style
65
+ if font:
66
+ regional_font = ""
67
+ if ":" in font:
68
+ region, font = font.split(":", 1)
69
+ regional_font = ' w:{region}="{font}"'.format(font=font, region=region)
70
+ prop += '<w:rFonts w:ascii="{font}" w:hAnsi="{font}" w:cs="{font}"{regional_font}/>'.format(
71
+ font=font, regional_font=regional_font
72
+ )
73
+ if color:
74
+ if color[0] == "#":
75
+ color = color[1:]
76
+ prop += '<w:color w:val="%s"/>' % color
77
+ if highlight:
78
+ if highlight[0] == "#":
79
+ highlight = highlight[1:]
80
+ prop += '<w:shd w:fill="%s"/>' % highlight
81
+ if size:
82
+ prop += '<w:sz w:val="%s"/>' % size
83
+ prop += '<w:szCs w:val="%s"/>' % size
84
+ if subscript:
85
+ prop += '<w:vertAlign w:val="subscript"/>'
86
+ if superscript:
87
+ prop += '<w:vertAlign w:val="superscript"/>'
88
+ if bold:
89
+ prop += "<w:b/>"
90
+ if rtl:
91
+ prop += "<w:bCs/>"
92
+ if italic:
93
+ prop += "<w:i/>"
94
+ if rtl:
95
+ prop += "<w:iCs/>"
96
+ if underline:
97
+ if underline not in [
98
+ "single",
99
+ "double",
100
+ "thick",
101
+ "dotted",
102
+ "dash",
103
+ "dotDash",
104
+ "dotDotDash",
105
+ "wave",
106
+ ]:
107
+ underline = "single"
108
+ prop += '<w:u w:val="%s"/>' % underline
109
+ if strike:
110
+ prop += "<w:strike/>"
111
+ if rtl:
112
+ prop += '<w:rtl w:val="true"/>'
113
+ if lang:
114
+ prop += '<w:lang w:val="%s"/>' % lang
115
+ xml = "<w:r>"
116
+ if prop:
117
+ xml += "<w:rPr>%s</w:rPr>" % prop
118
+ xml += '<w:t xml:space="preserve">%s</w:t></w:r>' % text
119
+ if url_id:
120
+ xml = '<w:hyperlink r:id="%s" w:tgtFrame="_blank">%s</w:hyperlink>' % (
121
+ url_id,
122
+ xml,
123
+ )
124
+ self.xml += xml
125
+
126
+ def __unicode__(self):
127
+ return self.xml
128
+
129
+ def __str__(self):
130
+ return self.xml
131
+
132
+ def __html__(self):
133
+ return self.xml
134
+
135
+
136
+ class RichTextParagraph(object):
137
+ """class to generate Rich Text Paragraphs when using templates variables
138
+
139
+ This is much faster than using Subdoc class,
140
+ but this only for texts OUTSIDE an existing paragraph.
141
+ """
142
+
143
+ def __init__(self, text=None, **text_prop):
144
+ self.xml = ""
145
+ if text:
146
+ self.add(text, **text_prop)
147
+
148
+ def add(
149
+ self,
150
+ text,
151
+ parastyle=None,
152
+ ):
153
+
154
+ # If a RichText is added
155
+ if not isinstance(text, RichText):
156
+ text = RichText(text)
157
+
158
+ prop = ""
159
+ if parastyle:
160
+ prop += '<w:pStyle w:val="%s"/>' % parastyle
161
+
162
+ xml = "<w:p>"
163
+ if prop:
164
+ xml += "<w:pPr>%s</w:pPr>" % prop
165
+ xml += text.xml
166
+ xml += "</w:p>"
167
+ self.xml += xml
168
+
169
+ def __unicode__(self):
170
+ return self.xml
171
+
172
+ def __str__(self):
173
+ return self.xml
174
+
175
+ def __html__(self):
176
+ return self.xml
177
+
178
+
179
+ R = RichText
180
+ RP = RichTextParagraph
docform/docx/subdoc.py ADDED
@@ -0,0 +1,103 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Created : 2021-07-30
4
+
5
+ @author: Eric Lapouyade
6
+ """
7
+
8
+ from docx import Document
9
+ from docx.oxml import CT_SectPr
10
+ from docx.opc.constants import RELATIONSHIP_TYPE as RT
11
+ from docxcompose.properties import CustomProperties
12
+ from docxcompose.utils import xpath
13
+ from docxcompose.composer import Composer
14
+ from docxcompose.utils import NS
15
+ from lxml import etree
16
+ import re
17
+
18
+
19
+ class SubdocComposer(Composer):
20
+ def attach_parts(self, doc, remove_property_fields=True):
21
+ """Attach docx parts instead of appending the whole document
22
+ thus subdoc insertion can be delegated to jinja2"""
23
+ self.reset_reference_mapping()
24
+
25
+ # Remove custom property fields but keep the values
26
+ if remove_property_fields:
27
+ cprops = CustomProperties(doc)
28
+ for name in cprops.keys():
29
+ cprops.dissolve_fields(name)
30
+
31
+ self._create_style_id_mapping(doc)
32
+
33
+ for element in doc.element.body:
34
+ if isinstance(element, CT_SectPr):
35
+ continue
36
+ self.add_referenced_parts(doc.part, self.doc.part, element)
37
+ self.add_styles(doc, element)
38
+ self.add_numberings(doc, element)
39
+ self.restart_first_numbering(doc, element)
40
+ self.add_images(doc, element)
41
+ self.add_diagrams(doc, element)
42
+ self.add_shapes(doc, element)
43
+ self.add_footnotes(doc, element)
44
+ self.remove_header_and_footer_references(doc, element)
45
+
46
+ self.add_styles_from_other_parts(doc)
47
+ self.renumber_bookmarks()
48
+ self.renumber_docpr_ids()
49
+ self.renumber_nvpicpr_ids()
50
+ self.fix_section_types(doc)
51
+
52
+ def add_diagrams(self, doc, element):
53
+ # While waiting docxcompose 1.3.3
54
+ dgm_rels = xpath(element, ".//dgm:relIds[@r:dm]")
55
+ for dgm_rel in dgm_rels:
56
+ for item, rt_type in (
57
+ ("dm", RT.DIAGRAM_DATA),
58
+ ("lo", RT.DIAGRAM_LAYOUT),
59
+ ("qs", RT.DIAGRAM_QUICK_STYLE),
60
+ ("cs", RT.DIAGRAM_COLORS),
61
+ ):
62
+ dm_rid = dgm_rel.get("{%s}%s" % (NS["r"], item))
63
+ dm_part = doc.part.rels[dm_rid].target_part
64
+ new_rid = self.doc.part.relate_to(dm_part, rt_type)
65
+ dgm_rel.set("{%s}%s" % (NS["r"], item), new_rid)
66
+
67
+
68
+ class Subdoc(object):
69
+ """Class for subdocument to insert into master document"""
70
+
71
+ def __init__(self, tpl, docpath=None):
72
+ self.tpl = tpl
73
+ self.docx = tpl.get_docx()
74
+ self.subdocx = Document(docpath)
75
+ if docpath:
76
+ compose = SubdocComposer(self.docx)
77
+ compose.attach_parts(self.subdocx)
78
+ else:
79
+ self.subdocx._part = self.docx._part
80
+
81
+ def __getattr__(self, name):
82
+ return getattr(self.subdocx, name)
83
+
84
+ def _get_xml(self):
85
+ if self.subdocx.element.body.sectPr is not None:
86
+ self.subdocx.element.body.remove(self.subdocx.element.body.sectPr)
87
+ xml = re.sub(
88
+ r"</?w:body[^>]*>",
89
+ "",
90
+ etree.tostring(
91
+ self.subdocx.element.body, encoding="unicode", pretty_print=False
92
+ ),
93
+ )
94
+ return xml
95
+
96
+ def __unicode__(self):
97
+ return self._get_xml()
98
+
99
+ def __str__(self):
100
+ return self._get_xml()
101
+
102
+ def __html__(self):
103
+ return self._get_xml()