def make_report(self): print('Building report...') doc = docxtpl.DocxTemplate(density_report_template) styles = doc.styles date_now = datetime.today().strftime('%c') basic_info_table = self.make_table_doco( self.information_table.round(3), 'Summary') histo_inline = docxtpl.InlineImage(doc, self.histo_out) density_im_inline = docxtpl.InlineImage(doc, self.image_path, height=Mm(180)) context = { 'br_code': self.br_code, 'area_name': self.area_name, 'date_gen': date_now, 'cov_w_aoi': density_im_inline, 'histo': histo_inline, 'dens_table': basic_info_table, 'user': self.user, 'method': self.method, 'cell_count': self.compliant_cells, 'cell_sq': self.cell_size * self.cell_size } doc.render(context) doc.save(self.report_path) print('Wrote %s...' % os.path.basename(self.report_path))
def build_doc(self, table_pd, template): doc = docxtpl.DocxTemplate(template) table_pd = table_pd.round(3) styles = doc.styles doco = doc.new_subdoc() doco_out = None pd.set_option('display.precision', 2) try: doco.add_paragraph("") tin = doco.add_table(table_pd.shape[0] + 1, table_pd.shape[1]) tin.allow_autofit = True for j in range(table_pd.shape[-1]): tin.cell(0, j).text = str(table_pd.columns[j]) for i in range(table_pd.shape[0]): for j in range(table_pd.shape[-1]): tin.cell(i + 1, j).text = str(table_pd.values[i, j]) for row in tin.rows: for cell in row.cells: paragraphs = cell.paragraphs for paragraph in paragraphs: for run in paragraph.runs: font = run.font font.size = Pt(9) doco_out = doco except KeyError: print('Could not gen table') return doco_out
def process(self): now = datetime.datetime.now() year = '{:02d}'.format(now.year) index = self.ui.combo_box_subjects.currentIndex() data = { "department_name": self.settings["department_name"][self.settings["teacher_name"][ self.ui.combo_box_subjects.itemText(index)]], "number": str(self.ui.spin_box.value()), "subjects": self.ui.combo_box_subjects.itemText(index), "work_theme": self.ui.line_edit_work_theme.text().upper(), "name": self.ui.line_edit_name.text(), "teacher_name": self.settings["teacher_name"][self.ui.combo_box_subjects.itemText( index)], "year": str(year), "work_purpose": self.ui.text_edit_work_purpose.toPlainText(), "conclusion": self.ui.text_edit_conclusion.toPlainText(), "end": self.get_gender(self.settings["teacher_name"][ self.ui.combo_box_subjects.itemText(index)]) } doc = docxtpl.DocxTemplate(os.path.dirname(__file__) + "/lab.docx") doc.render(data) doc.save("{} - lab {}.docx".format( self.settings["short"][self.ui.combo_box_subjects.itemText(index)], str(self.ui.spin_box.value())))
def make_table_doco(self, table_pd, title): doc = docxtpl.DocxTemplate(density_report_template) styles = doc.styles doco = doc.new_subdoc() doco_out = None try: doco.add_paragraph("") doco.add_heading(title, level=2) tin = doco.add_table(table_pd.shape[0] + 1, table_pd.shape[1]) tin.allow_autofit = True for j in range(1, table_pd.shape[-1], 1): tin.cell(0, j).text = str(table_pd.columns[j]) for i in range(table_pd.shape[0]): for j in range(table_pd.shape[-1]): tin.cell(i + 1, j).text = str(table_pd.values[i, j]) for row in tin.rows: for cell in row.cells: paragraphs = cell.paragraphs for paragraph in paragraphs: for run in paragraph.runs: font = run.font font.size = Pt(9) doco_out = doco except KeyError: print('Could not gen table', title) return doco_out
def printf(self): pass # проверка валидности и распечатка try: if self.check_first(): doc = docxtpl.DocxTemplate("шаблон1.docx") context = { "Имя": self.lineEdit_name.text(), "Фамилия": self.lineEdit_surname.text(), "Отчество": self.lineEdit_secondname.text(), "Серия": self.lineEdit_series.text(), "Номер": self.lineEdit_pass_number.text(), "Дата": self.lineEdit_given_date.text(), } doc.render(context) doc.save('СОГЛАСИЕ НА ОБРАБОТКУ ПЕРСОНАЛЬНЫХ ДАННЫХ.docx') os.startfile('СОГЛАСИЕ НА ОБРАБОТКУ ПЕРСОНАЛЬНЫХ ДАННЫХ.docx') else: QMessageBox.critical(self, "Ошибка", "Проверьте правильность введённых данных", QMessageBox.Ok) except Exception as error: print(error)
def printf_2(self): try: if self.check_second(): try: doc = docxtpl.DocxTemplate("шаблон.docx") context = { "Имя": self.lineEdit_name.text(), "Фамилия": self.lineEdit_surname.text(), "Отчество": self.lineEdit_secondname.text(), "Серия": self.lineEdit_series.text(), "Номер": self.lineEdit_pass_number.text(), "Дата": self.lineEdit_given_date.text(), "Выданкем": self.lineEdit_given_by.text(), "Специальность": self.comboBox_educ_way.currentText(), "Формаобуч": self.comboBox_form_of_edu.currentText(), } doc.render(context) doc.save('Заявление о зачислении.docx') os.startfile('Заявление о зачислении.docx') except Exception as error: print(error) else: QMessageBox.critical(self, "Ошибка", "Проверьте правильность введённых данных", QMessageBox.Ok) except Exception as error: print(error)
def dynamic_table_tst(): tpl = docxtpl.DocxTemplate('dynamic_table_tpl.docx') context = { 'col_labels': ['Фрукт', 'vegetable', 'stone', 'thing'], 'tbl_contents': [ { 'label': 'Желтый', 'cols': [ 'Бананssssssssssssssssssssssssssssss', 'capsicum', 'pyrite', 'taxi' ] }, { 'label': 'red', 'cols': ['apple', 'tomato', 'cinnabar', 'doubledecker'] }, { 'label': 'green', 'cols': ['guava', 'cucumber', 'aventurine', 'card'] }, ], } tpl.render(context) tpl.save('dynamic_table.docx')
def print(self): try: doc = docxtpl.DocxTemplate("Формат личного дела.docx") context = { "Факультет": self.lineEdit_direction_2.text(), "Специальность": self.lineEdit_direction.text(), "Группа": self.comboBox.currentText(), "Основа": self.lineEdit_teach_form.text(), "Номердела": self.lineEdit_number_of_doc_frame_3.text(), "Ф": self.lineEdit_surname_2.text(), "И": self.lineEdit_name_2.text(), "О": self.lineEdit_secondname_2.text(), "Рождение": self.lineEdit_birht_date_2.text(), "Место": self.lineEdit_place_birth_2.text(), "Серия": self.lineEdit_series_2.text(), "Номер": self.lineEdit_pass_number_2.text(), "когдавыдан": self.lineEdit_given_date_2.text(), "выданкем": self.lineEdit_given_by_2.text(), "Телефон": self.lineEdit_phone_2.text(), "mail": self.lineEdit_email_2.text(), "адрес": self.lineEdit_adress_2.text(), } doc.render(context) doc.save('Личное дело.docx') os.startfile(os.getcwd() + '/Личное дело.docx') except Exception as err: print(err)
def print3(self): try: print(self.dekan) doc = docxtpl.DocxTemplate("Формат студенческого билета.docx") context = { "Факультет": self.lineEdit_direction_2.text(), "Группа": self.comboBox.currentText(), "Ф": self.lineEdit_surname_2.text(), "И": self.lineEdit_name_2.text(), "О": self.lineEdit_secondname_2.text(), "Номербилета": self.lineEdit_num_book.text(), "year1": "2021", "year2": "2022", "year3": "2023", "year4": "2024", "year5": "2025", "year6": "2026", "level1": "1", "level2": "2", "level3": "3", "level4": "4", "level5": "5", "level6": "6", "Проректор": "", "Декан": self.dekan[4], } doc.render(context) doc.save('Студенческий билет.docx') os.startfile(os.getcwd() + '/Студенческий билет.docx') except Exception as err: print(err)
def updateStatus(request, uuidStr): if not request.user.is_authenticated: return JsonResponse({"error": "Login required."}, status=401) if request.method == "PATCH": document = Document.objects.get(uuid=uuidStr) if request.user == document.creator or request.user in document.administrators.all( ): data = json.loads(request.body) document.active = data["active"] document.save() return JsonResponse({ "updated": document.updatedTime.strftime("%I:%M %p, %d/%m/%y"), "data": document.data, "activeStatus": document.active, "docVariables": sorted(docxtpl.DocxTemplate( document.templateFile.path).undeclared_template_variables, key=str.casefold), }) else: return JsonResponse( {"error": "You are not authorised to update this document"}, status=403)
def updateData(request, uuidStr): if not request.user.is_authenticated: return JsonResponse({"error": "Login required."}, status=401) if request.method == "PUT": document = Document.objects.get(uuid=uuidStr) if request.user == document.creator or request.user in document.administrators.all( ): data = json.loads(request.body) for queryItem in data: #add UUIDs to each queryItem and responseOption if "uuid" not in queryItem or queryItem["uuid"] == "": queryItem["uuid"] = str(uuid4()) if queryItem["type"] == "Selection": for responseOption in queryItem.get("responseOptions", []): if "uuid" not in responseOption or responseOption[ "uuid"] == "": responseOption["uuid"] = str(uuid4()) document.data = data document.save() return JsonResponse({ "updated": document.updatedTime.strftime("%I:%M %p, %d/%m/%y"), "data": document.data, "activeStatus": document.active, "docVariables": sorted(docxtpl.DocxTemplate( document.templateFile.path).undeclared_template_variables, key=str.casefold), }) else: return JsonResponse( {"error": "You are not authorised to update this document"}, status=403)
def create_slip(context): name = path / f"Order_{context['order_number']}.pdf" temp = path / 'temp.docx' doc = docxtpl.DocxTemplate(path / 'packing_slip.docx') doc.render(context) doc.save(temp) pdf = convertapi.convert('pdf', {'File': temp}, from_format='docx') pdf.save_files(name) return name
def form(request, uuidStr): try: document = Document.objects.get(uuid=uuidStr) docData = document.data except: raise Http404("Document does not exist") if not document.active: raise Http404("Document does not exist") if request.method == "POST": formData = request.POST docTemplate = docxtpl.DocxTemplate(document.templateFile.path) docVariables = sorted(docTemplate.undeclared_template_variables, key=str.casefold) docContext = {} for variable in docVariables: if variable.startswith("show_"): docContext[variable] = False elif variable.startswith("insert_"): docContext[variable] = "" for index, queryItem in enumerate(docData): if queryItem["type"] == "Selection": responseOptions = queryItem.get('responseOptions', []) selectedOptions = formData.getlist(f'item{index}_Selection', []) for selectedOption in selectedOptions: selectedResponseOptions = list( filter( lambda responseOption: responseOption.get('option') == selectedOption, responseOptions) ) #should only be one unless form creator set two options with identical names for selectedResponseOption in selectedResponseOptions: #no need but in case he set two options with identical names and different selections for linkedVariable in selectedResponseOption.get( 'linkedVariables', []): docContext[linkedVariable] = True elif queryItem["type"] == "FreeText": textToInsert = formData.get(f'item{index}_FreeText', "") for linkedVariable in queryItem.get("linkedVariables", []): docContext[linkedVariable] = textToInsert request.session[f'{uuidStr}_context'] = docContext return HttpResponseRedirect( reverse("app:thankYou", kwargs={"uuidStr": document.uuid})) questionIndex = 0 for queryItem in docData: if queryItem['type'] != 'Header': questionIndex += 1 queryItem['questionIndex'] = questionIndex return render( request, "app/form.html", { "name": document.name, "docData": docData, "uuid": document.uuid, "isLive": True, })
def endYN(dict): if 'q7' in dict: # execute code to generate a new document after the 7th question pathfrom = app.root_path + '/static/files/demo.docx' pathto = app.root_path + '/static/files/demoX.docx' templateDocument = docxtpl.DocxTemplate(pathfrom) templateDocument.render(dict) templateDocument.save(pathto) return "NO"
def export(self): ctx = {"tcp": self.nmap_results.hosts , "udp": []} try : docxtpl = sys.modules["docxtpl"] docx = docxtpl.DocxTemplate(self.template) docx.render(ctx) self.docx.save(self.filename) except Exception as e: self.logger.error("export failed : %s" % e)
def make_cover_page(self): doc = docxtpl.DocxTemplate(front_page) date_now = datetime.today().strftime('%c') new_plot_name_x = os.path.join(self.analysis_folder, 'Displacement_AFTER_X.png') old_plot_name_x = os.path.join(self.analysis_folder, 'Displacement_BEFORE_X.png') new_plot_name_y = os.path.join(self.analysis_folder, 'Displacement_AFTER_Y.png') old_plot_name_y = os.path.join(self.analysis_folder, 'Displacement_BEFORE_Y.png') cover_path = os.path.join( self.reprots_folder, '%s_%s_Front_Page.docx' % (self.br, self.area_name)) building_1_inline = docxtpl.InlineImage(doc, self.image_list[0], width=Mm(70)) old_x_inline = docxtpl.InlineImage(doc, old_plot_name_x, width=Mm(70)) old_y_inline = docxtpl.InlineImage(doc, old_plot_name_y, width=Mm(70)) new_y_inline = docxtpl.InlineImage(doc, new_plot_name_y, width=Mm(70)) new_x_inline = docxtpl.InlineImage(doc, new_plot_name_x, width=Mm(70)) self.about_area_pd.infer_objects().style.set_precision(2) self.adj_summary_pd.infer_objects().style.set_precision(2) self.about_area_pd.columns = ['Variable', 'Value'] ov_table = self.build_doc(self.about_area_pd, front_page) of_table = self.build_doc(self.adj_summary_pd, front_page) assessment = self.determine_assessment() context = { 'BR': self.br, 'area_name': self.area_name, 'building_1': building_1_inline, 'overview_table': ov_table, 'offset_table': of_table, 'x_before': old_x_inline, 'y_before': old_y_inline, 'x_after': new_x_inline, 'y_after': new_y_inline, 'RMSE_X_before': self.initial_x_rmse, 'RMSE_X_after': self.new_x_rmse, 'RMSE_Y_before': self.initial_y_rmse, 'RMSE_Y_after': self.new_y_rmse, 'CI95_X_before': self.initial_x_ci95, 'CI95_X_after': self.new_x_ci95, 'CI95_Y_before': self.initial_y_ci95, 'CI95_Y_after': self.new_y_ci95, 'assessment': assessment, 'gen': date_now } doc.render(context) doc.save(cover_path)
def fp_to_docx(fp_object, template, out_folder, doc_name): from docx.shared import Mm, Inches from os.path import join doc_template = docxtpl.DocxTemplate(template) in_vars = doc_template.get_undeclared_template_variables() dict_vars = {} for var in in_vars: try: if fp_object.fm_main[var]['domain_trans']: try: dict_vars[var] = fp_object.fm_main[var]['domain_trans'][ fp_object.attributes[var]] except KeyError: dict_vars[var] = fp_object.attributes[var] else: dict_vars[var] = fp_object.attributes[var] except KeyError: if 'att' in var: print('\tattachment {}'.format(var)) if 'att20_' in var: att_url = find_attachment(fp_object.att_res, var.replace('att20_', '')) if att_url == None: pass else: dict_vars[var] = docxtpl.InlineImage( doc_template, set_up_docx_inline(att_url), height=Mm(20)) else: att_url = find_attachment(fp_object.att_res, var.replace('att_', '')) if att_url == None: pass else: dict_vars[var] = docxtpl.InlineImage( doc_template, set_up_docx_inline(att_url), width=Inches(6)) elif 'rel_' in var: related_set = find_related_table(fp_object, var.replace('rel_', '')) if len(related_set.features) > 0: dict_vars[var] = related_set.return_sdf().to_dict( 'records') else: print('\tnon-attribute: {}'.format(var)) doc_template.render(dict_vars) if '.docx' not in doc_name: doc_name = doc_name + '.docx' print('\tsaving...') return doc_template.save(join(out_folder, doc_name))
def generate_index_files(cleandata): generate_index_templates(cleandata) for x in cleandata: event = x[1] summary = x[4] archive = x[3] date = x[0] date.split("/") month = date[1] year = date[0] dateindex = x[5] eventindex = x[6] filename = index+x[7] doc = docxtpl.DocxTemplate(filename) linkrt = docxtpl.RichText() linkrt.add(event, url_id = doc.build_url_id(summary), color="#0000FF") datert = docxtpl.RichText() datert.add(date, color='#FFFFFF') context[dateindex] = datert context[eventindex] = linkrt doc.save(filename) time.sleep(.25) for x in os.listdir(index): doc = docxtpl.DocxTemplate(index+x) doc.render(context) doc.save(index+x)
def endYN(dict): if 'q13' in dict: listYNQ = ["q3", "q4", "q5", "q6", "q7", "q9", "q10", "q11", "q12"] for key, v in dict.items(): for i in range(len(listYNQ)): if key == listYNQ[i] and int(v[4]) == 0: dict[key] = 'Yes' if key == listYNQ[i] and int(v[4]) == 1: dict[key] = 'No' pathfrom = app.root_path + '/static/files/demo.docx' pathto = app.root_path + '/static/files/demoX.docx' templateDocument = docxtpl.DocxTemplate(pathfrom) templateDocument.render(dict) templateDocument.save(pathto)
def print2(self): try: doc = docxtpl.DocxTemplate("Формат зачетной книжки.docx") context = { "Факультет": self.lineEdit_direction_2.text(), "Специальность": self.lineEdit_direction.text(), "Проректор": "", "Декан": self.dekan[4], "Ф": self.lineEdit_surname_2.text(), "И": self.lineEdit_name_2.text(), "О": self.lineEdit_secondname_2.text(), "Номеркнижки": self.lineEdit_num_book.text(), } doc.render(context) doc.save('Зачётная книжка.docx') os.startfile(os.getcwd() + '/Зачётная книжка.docx') except Exception as err: print(err)
def generate_summary_files(cleandata): os.chdir(filesystem) for x in cleandata: doc = docxtpl.DocxTemplate(r"C:\Users\tyler\Desktop\Workspace\TTT Admin Suite\Template.docx") filename = str(x[2])+".docx" link = docxtpl.RichText() link.add("Filesystem", url_id=doc.build_url_id(x[3]), color='#0000FF') context = {'DATE' : x[0]} context["FILESYSTEM"] = link context["EVENT"] = x[1] doc.render(context) doc.save(filename) link = upload_file(filesystem + filename, x[2]) x.append(link) return cleandata
def gen_kp_s(request, pk): doc = docxtpl.DocxTemplate( r"C:\Users\mrnik\Downloads\StudWork\StudWork\StudWorkApp\kp.docx") work = Work.objects.filter(id_work=pk) student = Student.objects.get(id_stud=work.values('id_stud')[0]['id_stud']) director = Director.objects.get(id_dir=work.values('id_dir')[0]['id_dir']) try: topic = Topic.objects.get(id_work=work.values('id_work')[0]['id_work']) except: topic = "Тема не указана" context = { 'subject': work.values()[0]['subject'], 'fio_s': student, 'topic': topic, 'director': director, } doc.render(context) doc.save(r"C:\Users\mrnik\Downloads\StudWork\KP_" + str(student) + str(work.values()[0]['subject']) + str(topic) + ".docx") return HttpResponseRedirect('../../../../student/' + str(pk))
def getDocument(request, uuidStr): try: document = Document.objects.get(uuid=uuidStr) except: raise Http404("Document does not exist") docContext = request.session.get(f'{uuidStr}_context') if docContext is not None: docTemplate = docxtpl.DocxTemplate(document.templateFile.path) docTemplate.render(docContext) doc_io = io.BytesIO() # create a file-like object docTemplate.save(doc_io) # save data to file-like object doc_io.seek(0) # go to the beginning of the file-like object response = HttpResponse(doc_io.read()) # Content-Disposition header makes a file downloadable response[ "Content-Disposition"] = f"attachment; filename={document.name}_generated.docx" # Set the appropriate Content-Type for docx file response[ "Content-Type"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document" return response else: return JsonResponse({"error": "Data not found"}, status=404)
def main(argv): args = __getopt() if not os.path.exists(args.DOCX): print(args.DOCX, ': file not found.\n', file=sys.stderr) sys.exit(1) if not os.path.exists(args.YAML): print(args.YAML, ': file not found.\n', file=sys.stderr) sys.exit(1) with io.open(args.YAML, 'r') as stream: try: context = yaml.load(stream) if type(context) is not dict: print('Error: YAML loaded data are not a dictionary.') sys.exit(1) doc = docxtpl.DocxTemplate(args.DOCX) doc.render(context) doc.save(args.OUTPUT) except yaml.YAMLError as exc: print('Error: YAML loaded data are not a dictionary.') print(exc)
"function": "Big Man", "adres": "On the Block", "tel": "0223 ja toch", "mail": "*****@*****.**", "tekst": tekst, "row_contents": [{ "description": "a b c", "value": "ja", "bool": True }, { "description": "a b c", "value": "nee", "bool": True }, { "description": "a b c", "value": "prrt", "bool": True }] } print(os.getcwd()) doc = docxtpl.DocxTemplate("test_template_2.docx") doc.render(data_package) doc.save("test_render.docx")
def get(self, request, *args, **kwargs): #t0 = time() data = self.kwargs['slug'] docx = self.kwargs['docx'] tfsid = [int(x) for x in self.request.GET.getlist('tfids') ] # tf id's from url get whish user check from jt tf checkbox if data != None: jt = Jobtitles.objects.filter(slug=data) ps = Psinfo.objects.filter(id=jt[0].ps_id) educationalreqs = Educationalreqs.objects.filter( gtf_id=jt[0].gtf_id) reqworkexperiences = Reqworkexperiences.objects.filter( gtf_id=jt[0].gtf_id) specialconditions = Specialconditions.objects.filter( gtf_id=jt[0].gtf_id) othercharacts = Othercharacts.objects.filter(gtf_id=jt[0].gtf_id) gtfs = Jobtitles.objects.filter(jobtitle=jt[0].jobtitle).filter( ps_id=jt[0].ps_id).exclude(nameotf=jt[0].nameotf) try: okz = Okz.objects.filter(gtf_id=jt[0].gtf_id).distinct() codeokz = okz[0].codeok nameokz = okz[0].nameokz except: okz = "Не указан" codeokz = "Не указан" nameokz = "Не указан" # if user go to url without parameters if not tfsid: tfs = Tfinfo.objects.filter(gtf_id=jt[0].gtf_id) tfsid = [x.id for x in tfs] otrasl = ps[0].otraslid generaldatas = [] oi_app = OIApp() ##### nowdate in roditelny padezh(need for docx generation)## rod_nowdate = oi_app.nowdate_rod() generaldatas = { 'slug': data, 'jobtitleid': jt[0].id, 'jobtitle': jt[0].jobtitle, 'jobtitlerod': jt[0].jobtitle_rod, 'nameotf': jt[0].nameotf, 'gtfs': gtfs, 'pspurposekind': ps[0].pspurposekind, 'nameps': ps[0].nameps, 'psregnum': ps[0].psregnum, 'ps_id': ps[0].id, 'psordernum': ps[0].psordernum, 'psdateappr': ps[0].psdateappr, 'otraslname': otrasl.name, 'otraslicon': otrasl.icon, 'educationalreqs': educationalreqs, 'reqworkexperiences': reqworkexperiences, 'specialconditions': specialconditions, 'othercharacts': othercharacts, 'today': rod_nowdate['today'], 'month': rod_nowdate['rod_month'], 'year': rod_nowdate['year'], 'codeokz': codeokz, 'nameokz': nameokz, } laresult = [] nkresult = [] rsresult = [] ocresult = [] tfresult = [] for tfid in tfsid: # select TF only for selected jobtitle tf = Tfinfo.objects.get(id=tfid) la_get_raw = Tf_la.objects.filter(tf_id=tfid).distinct() nk_get_raw = Tf_rs.objects.filter(tf_id=tfid).distinct() rs_get_raw = Tf_nk.objects.filter(tf_id=tfid).distinct() oc_get_raw = Tf_oc.objects.filter(tf_id=tfid).distinct() tfresult.append({ 'id': tf.id, 'codetf': tf.codetf, 'nametf': tf.nametf }) for la in la_get_raw: laresult.append({ 'id': la.id, 'laboraction': la.laboraction }) for nk in nk_get_raw: nkresult.append({ 'id': nk.id, 'necessaryknowledge': nk.requiredskill }) # !!!Swap with RS becouse rosmintrud edition!!! for rs in rs_get_raw: rsresult.append({ 'id': rs.id, 'requiredskill': rs.necessaryknowledge }) # # !!!Swap with NK becouse rosmintrud edition!!! for oc in oc_get_raw: ocresult.append({ 'id': oc.id, 'othercharacteristic': oc.othercharacteristic }) ocresultnew = set(x['othercharacteristic'] for x in ocresult) # get company data cmpd = oi_app.fake_cmpd(ps, okz, laresult, nkresult, rsresult, ocresult, tfresult) ########################## requirements = { 'tf': tfresult, 'laboractions': laresult, 'necessaryknowledges': nkresult, 'requiredskills': rsresult, 'othercharacteristics': ocresultnew, } ### Doc download part ### if docx == 'msword-document-download': context = { 'generaldatas': generaldatas, 'requirements': requirements, 'cmpd': cmpd } media_root = settings.MEDIA_ROOT doc = docxtpl.DocxTemplate(media_root + '/doctemplates/oitemplate.docx') doc.render(context) response = HttpResponse( content_type= 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ) response[ 'Content-Disposition'] = 'attachment; filename=%s.docx' % re.sub( r'-\d+$', '', generaldatas['slug']) doc.save(response) return response #return redirect(reverse_lazy("org-official-instructions", id=(companyid), pk=(departid), slug=(data) )) else: return render( request, self.template_name, { 'generaldatas': generaldatas, 'requirements': requirements, 'cmpd': cmpd })
def write_data(dic_list): for data in dic_list: doc = docxtpl.DocxTemplate("word_test.docx") doc.render(data) doc.save("./export/{}.docx".format(data['placeholder_1']))
def replacedocx(save_path, docxname, new_json): # module_path = os.path.dirname(__file__) doc = docxtpl.DocxTemplate(path + "/" + "package/" + 'docxs' + "/" + docxname + ".docx") doc.render(new_json) doc.save(save_path + "/" + docxname + '.docx')
def get(self, request, *args, **kwargs): data = self.kwargs['slug'] docx = self.kwargs['docx'] tfsid = [int(x) for x in self.request.GET.getlist('tfids')] companyid = self.kwargs['id'] departid = self.kwargs['pk'] company = Enterprises.objects.get(id=companyid) department = Departs.objects.get(id=departid) ois = Offinsts.objects.filter(departs_id=departid) ois_len = len(ois) user = self.request.user paidactivdate = request.user.profiles.paidactivdate stop_paidactivdate = True if paidactivdate: datenow = datetime.now().date() if (paidactivdate - datenow).days + 1 > 0: stop_paidactivdate = False cmpd0 = {'company': company, 'department': department} if data != None: morph = pymorphy2.MorphAnalyzer() pos_list = ['NOUN', 'ADJF', 'ADJS', 'PRTF', 'PRTS'] # Chast' rechi & padezh jt = Jobtitles.objects.filter(slug=data) ######### company-department data ####################################### company = Enterprises.objects.get(id=companyid) department = Departs.objects.get(id=departid) e_name = company.e_name e_op_form = company.e_op_form e_director = company.e_director e_fam_ul = company.e_fam_ul e_name_ul = company.e_name_ul e_otch_ul = company.e_otch_ul depname = department.name cheef = department.cheef cheef_name = department.cheef_name cheef_otch = department.cheef_otch cheef_fam = department.cheef_fam ### roditelny, datelny padezhi ### # CEO to padezhi director_gent = [] director_datv = [] for w in e_director.split(' '): # split CEO pozition capmarker = False if not w.islower() and not w.isupper( ): # check if word is capitalized capmarker = True cleared_director = morph.parse(w)[0] if cleared_director.tag.POS in pos_list and cleared_director.tag.case == 'nomn' and cleared_director.tag.number == 'sing': # check if word is single noun e_dir_gent = cleared_director.inflect({'gent'}).word e_dir_datv = cleared_director.inflect({'datv'}).word director_gent.append(e_dir_gent.capitalize( ) if capmarker == True else e_dir_gent) director_datv.append(e_dir_datv.capitalize( ) if capmarker == True else e_dir_datv) else: director_gent.append(w.capitalize() if capmarker == True else w) director_datv.append(w.capitalize() if capmarker == True else w) e_director_gent = ' '.join(director_gent) e_director_datv = ' '.join(director_datv) # Cheef to padezhi cheef_datv = [] for w in cheef.split(' '): # split CEO pozition capmarker = False if not w.islower() and not w.isupper( ): # check if word is capitalized capmarker = True cleared_cheef = morph.parse(w)[0] print(cleared_cheef) if cleared_cheef.tag.POS in pos_list and cleared_cheef.tag.case == 'nomn' and cleared_cheef.tag.number == 'sing': # check if word is single noun d_cheef_datv = cleared_cheef.inflect({'datv'}).word cheef_datv.append(d_cheef_datv.capitalize() if capmarker == True else d_cheef_datv) else: cheef_datv.append(w.capitalize() if capmarker == True else w) d_cheef_datv = ' '.join(cheef_datv) cmpd = { 'e_name': e_name, 'e_op_form': e_op_form, 'e_director': e_director, 'e_fam_ul': e_fam_ul, 'e_name_ul': e_name_ul, 'e_otch_ul': e_otch_ul, 'e_director_gent': e_director_gent, 'e_director_datv': e_director_datv, 'depname': depname, 'cheef': cheef, 'cheef_name': cheef_name, 'cheef_otch': cheef_otch, 'cheef_fam': cheef_fam, 'd_cheef_datv': d_cheef_datv } ##### nowdate in roditelny padezh(need for docx generation)## m = pymorphy2.MorphAnalyzer() locale.setlocale(locale.LC_TIME, "ru_RU.UTF-8") today = datetime.now().strftime("%d %B %Y").lower() today, month, year = today.split(' ') nmonth = m.parse(month)[0].inflect({'gent'}).word ######### general data ####################################### ps = Psinfo.objects.filter(id=jt[0].ps_id) educationalreqs = Educationalreqs.objects.filter( gtf_id=jt[0].gtf_id).distinct() reqworkexperiences = Reqworkexperiences.objects.filter( gtf_id=jt[0].gtf_id).distinct() specialconditions = Specialconditions.objects.filter( gtf_id=jt[0].gtf_id).distinct() othercharacts = Othercharacts.objects.filter( gtf_id=jt[0].gtf_id).distinct() #tfs = Tfinfo.objects.filter(gtf_id=jt[0].gtf_id) otrasl = ps[0].otraslid generaldatas = [] #make jobtitle Roditelny padezh jt_rod = [] #cut non need padezh string beetween '( )' pattern = re.compile("[\(\[].*?[\)\]]") if re.findall(pattern, jt[0].jobtitle): cuttedstring = re.findall(pattern, jt[0].jobtitle)[0] else: cuttedstring = '' cleared_jt = re.sub("[\(\[].*?[\)\]]", "", jt[0].jobtitle) for i in cleared_jt.split(' '): p = morph.parse(i)[0] print(p) if p.tag.POS in pos_list and p.tag.case == 'nomn' and p.tag.number == 'sing': # Chast' rechi & padezh if p.inflect({'gent'}): changed_word = p.inflect({'sing', 'gent'}).word if changed_word == 'риска-менеджера': changed_word = 'риск-менеджера' if changed_word == 'бренда-менеджера': changed_word = 'бренд-менеджера' if changed_word == 'брэнда-менеджера': changed_word = 'брэнд-менеджера' if changed_word == 'поварова': changed_word = 'поваров' if changed_word == 'котлова': changed_word = 'котлов' if changed_word == 'чокерноя': changed_word = 'чокерной' jt_rod.append(changed_word) else: jt_rod.append(i) else: jt_rod.append(i) jobtitlerod = ' '.join(jt_rod) + ' ' + cuttedstring generaldatas = { 'slug': data, 'jobtitleid': jt[0].id, 'jobtitle': jt[0].jobtitle, 'jobtitlerod': jobtitlerod, 'nameotf': jt[0].nameotf, 'pspurposekind': ps[0].pspurposekind, 'nameps': ps[0].nameps, 'psregnum': ps[0].psregnum, 'psordernum': ps[0].psordernum, 'psdateappr': ps[0].psdateappr, 'otraslname': otrasl.name, 'otraslicon': otrasl.icon, 'educationalreqs': educationalreqs, 'reqworkexperiences': reqworkexperiences, 'specialconditions': specialconditions, 'othercharacts': othercharacts, 'today': today, 'month': nmonth, 'year': year } ######### requirements ####################################### laresult = [] nkresult = [] rsresult = [] ocresult = [] tfresult = [] for tfid in tfsid: # select TF only for selected jobtitle tf = Tfinfo.objects.get(id=tfid) la_get_raw = Tf_la.objects.filter(tf_id=tfid).distinct() nk_get_raw = Tf_rs.objects.filter(tf_id=tfid).distinct() rs_get_raw = Tf_nk.objects.filter(tf_id=tfid).distinct() oc_get_raw = Tf_oc.objects.filter(tf_id=tfid).distinct() tfresult.append({ 'id': tf.id, 'codetf': tf.codetf, 'nametf': tf.nametf }) for la in la_get_raw: laresult.append({ 'id': la.id, 'laboraction': la.laboraction }) for nk in nk_get_raw: nkresult.append({ 'id': nk.id, 'necessaryknowledge': nk.requiredskill }) # !!!Swap with RS becouse rosmintrud edition!!! for rs in rs_get_raw: rsresult.append({ 'id': rs.id, 'requiredskill': rs.necessaryknowledge }) # # !!!Swap with NK becouse rosmintrud edition!!! for oc in oc_get_raw: ocresult.append({ 'id': oc.id, 'othercharacteristic': oc.othercharacteristic }) ocresultnew = set(x['othercharacteristic'] for x in ocresult) requirements = { 'tf': tfresult, 'laboractions': laresult, 'necessaryknowledges': nkresult, 'requiredskills': rsresult, 'othercharacteristics': ocresultnew, } ### Doc download part ### if docx == 'msword-document-download': context = { 'generaldatas': generaldatas, 'requirements': requirements, 'cmpd': cmpd, 'cmpd0': cmpd0 } media_root = settings.MEDIA_ROOT doc = docxtpl.DocxTemplate(media_root + '/doctemplates/oitemplate.docx') doc.render(context) response = HttpResponse( content_type= 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ) response[ 'Content-Disposition'] = 'attachment; filename=%s.docx' % re.sub( r'-\d+$', '', generaldatas['slug']) doc.save(response) return response #return redirect(reverse_lazy("org-official-instructions", id=(companyid), pk=(departid), slug=(data) )) else: return render( request, self.template_name, { 'generaldatas': generaldatas, 'requirements': requirements, 'cmpd': cmpd, 'cmpd0': cmpd0, 'stop_paidactivdate': stop_paidactivdate, 'ois_len': ois_len })
def make_sub_page(self, pd_in, building_name, old_data, new_data): page_number = old_data['Building ID'].head(1).values[0] + 2 doc = docxtpl.DocxTemplate(sub_page) date_now = datetime.today().strftime('%c') page_path = os.path.join( self.reprots_folder, '%s_%s_%s_Page.docx' % (self.br, self.area_name, building_name)) # make histos x_before_histo_path = os.path.join( self.analysis_folder, 'Displacement_%s_X_BEFORE.png' % building_name) y_before_histo_path = os.path.join( self.analysis_folder, 'Displacement_%s_Y_BEFORE.png' % building_name) y_after_histo_path = os.path.join( self.analysis_folder, 'Displacement_%s_Y_AFTER.png' % building_name) x_after_histo_path = os.path.join( self.analysis_folder, 'Displacement_%s_X_AFTER.png' % building_name) x_old_series = old_data['Offset_X'] y_old_series = old_data['Offset_Y'] y_new_series = new_data['Offset_Y'] x_new_series = new_data['Offset_X'] self.make_fuzziness_histo(x_old_series, x_before_histo_path) self.make_fuzziness_histo(y_old_series, y_before_histo_path) self.make_fuzziness_histo(y_new_series, y_after_histo_path) self.make_fuzziness_histo(x_new_series, x_after_histo_path) pd_in_reset_index = pd_in.reset_index().infer_objects() pd_in_reset_index.style.set_precision(precision=2) table_in = self.build_doc(pd_in_reset_index, sub_page) # find ss image longer_name = building_name + '.' candidates = [a for a in self.image_list if building_name in a] if len(candidates) == 1: building_image = candidates[0] elif len(candidates) > 1: candidates = [a for a in self.image_list if longer_name in a] building_image = candidates[0] else: building_image = None if building_image is not None: inline_image = docxtpl.InlineImage(doc, building_image, width=Mm(100)) else: inline_image = "No image provided" x_before_histo_inline = docxtpl.InlineImage(doc, x_before_histo_path, width=Mm(70)) y_before_histo_inline = docxtpl.InlineImage(doc, y_before_histo_path, width=Mm(70)) y_after_histo_inline = docxtpl.InlineImage(doc, y_after_histo_path, width=Mm(70)) x_after_histo_inline = docxtpl.InlineImage(doc, y_before_histo_path, width=Mm(70)) context = { 'BR': self.br, 'area_name': self.area_name, 'bnum': building_name, 'building_image': inline_image, 'building_adj_summary': table_in, 'x_histo_before': x_before_histo_inline, 'x_histo_after': x_after_histo_inline, 'y_histo_before': y_before_histo_inline, 'y_histo_after': y_after_histo_inline, 'RMSE_X_before': round(pd_in.loc['X RMSE (m)', 'Before adjustment'], 2), 'RMSE_X_after': round(pd_in.loc['X RMSE (m)', 'After adjustment'], 2), 'RMSE_Y_after': round(pd_in.loc['Y RMSE (m)', 'After adjustment'], 2), 'RMSE_Y_before': round(pd_in.loc['Y RMSE (m)', 'Before adjustment'], 2), 'CI95_Y_before': round(pd_in.loc['Y CI95', 'Before adjustment'], 2), 'CI95_X_before': round(pd_in.loc['X CI95', 'Before adjustment'], 2), 'CI95_X_after': round(pd_in.loc['X CI95', 'After adjustment'], 2), 'CI95_Y_after': round(pd_in.loc['Y CI95', 'After adjustment'], 2), 'gen': date_now, 'bid': page_number } doc.render(context) doc.save(page_path)