def verify_template_docx(template_path): if not os.path.isfile(template_path): raise FileNotFoundError("File {} not found".format(template_path)) counter = 0 test_string = "a" print("Verifying template...") doc = DocxTemplate(template_path) doc.render({}) no_params = doc.get_xml() # check if each of the fields in csv file exist in template # print("Checking fields in csv") for field in fieldnames: doc = DocxTemplate(template_path) # print("\tChecking '"+field + "'...") doc.render({field: test_string}) if doc.get_xml() == no_params: print("\t'{}' not defined in the template".format(field)) counter += 1 # else: # print("\t\tOK") # check if any field(s) used in the template is not defined in the csv # print("Checking variables in template") doc = DocxTemplate(template_path) for variable in doc.get_undeclared_template_variables(): # print("\tChecking '"+variable + "'...") if variable not in fieldnames: print("\t'{}' not defined in the csv".format(variable)) counter += 1 # else: # print("\t\tOK") return counter
def main(): args = parser.parse_args() file_path = os.path.abspath(args.file) assert os.path.exists(os.path.abspath(file_path)), "file doesn't exist" tpl = DocxTemplate(file_path) ast = jinja_env.parse(tpl.patch_xml(tpl.get_xml())) variables = meta.find_undeclared_variables(ast) print("Variables: ", variables) context = {} for variable in variables: print("Enter value of variable {}({})".format( variable, variable.replace('_', ''))) line = input("> ") lines = [] while line != 'end': lines.append(line) line = input("> ") line = '\n'.join(lines) context[variable] = Listing(line) print("context: ", context) tpl.render(context) tpl.save("generated.docx")
def is_template(documento): doc = DocxTemplate(MEDIA_ROOT + documento) xml = doc.get_xml() xml = doc.patch_xml(xml) # patch xml for jinja2schema variables = jinja2schema.infer(xml) list_xml = list(variables.keys()) # create a nice list return list_xml
def verify_template_docx(self, template): # messages = [] result = {'in_template': [], 'in_csv': []} test_string = "a" doc = DocxTemplate(template) doc.render({}) no_params = doc.get_xml() # check if each of the fields in csv file exist in template for field in self.fieldnames: doc = DocxTemplate(template) doc.render({field: test_string}) if doc.get_xml() == no_params: # messages.append("'{}' not defined in the template".format(field)) result['in_template'].append(field) # check if any field(s) used in the template is not defined in the csv doc = DocxTemplate(template) for variable in doc.get_undeclared_template_variables(): if variable not in self.fieldnames: # messages.append("'{}' not defined in the csv".format(variable)) result['in_csv'].append(variable) # return messages return result
def html_to_docx(html_text, doc_tpl): #конвертирование html кода в docx file_object = NamedTemporaryFile(suffix='.docx') # create temp file pypandoc.convert(html_text, 'docx', format='html', outputfile=file_object.name) # generate it using pandoc subdocx = DocxTemplate(file_object.name) #open docx file subdocx._part = doc_tpl.docx._part if subdocx._element.body.sectPr is not None: subdocx._element.body.remove(subdocx._element.body.sectPr) xml = re.sub( r'</?w:body[^>]*>', '', subdocx.get_xml() ) #etree.tostring(subdocx._element.body,encoding='unicode', pretty_print=False)) return xml
def validate_template_syntax(self, available_placeholders=None, sample_data=None): try: doc = DocxTemplate(self.template) root = _MagicPlaceholder() env = get_jinja_env() ph = { name: root[name] for name in doc.get_undeclared_template_variables(env) } xml = doc.get_xml() xml = doc.patch_xml(xml) image_match = re.match(r".*{{\s?(\S*)\s?\|\s?image\(.*", xml) images = image_match.groups() if image_match else [] for image in images: cleaned_image = image.strip('"').strip("'") ph[root[cleaned_image]] = django_file("black.png").file ph["_tpl"] = doc doc.render(ph, env) if sample_data: sample_data["_tpl"] = doc doc.render(sample_data, env) self.validate_available_placeholders( used_placeholders=root.reports, available_placeholders=available_placeholders, ) except TemplateSyntaxError as exc: arg_str = ";".join(exc.args) raise exceptions.ValidationError( f"Syntax error in template: {arg_str}") finally: self.template.seek(0)
def add_sub_docx(sub_docx): document = DocxTemplate(sub_docx) xml = re.sub(r'</?w:body[^>]*>', '', document.get_xml()) return xml