from docxtpl import DocxTemplate import jinja2 doc = DocxTemplate("TemplateLGULiPADAccountRegistration.docx") context = { 'Municipality' : "Munishipariti" } doc.render(context) doc.save("generated_doc.docx")
def run(dictionnaire, template, dst): """Fonction qui prend en paramètre, le dictionnaire de contenu du fichier source, un template '.docx' où va être écrit le contenu du dictionnaire et un chemin de destination où sera enregistré le fichier final. """ tpl = DocxTemplate(template) for fiche in dictionnaire['Fiches']: for key1, value1 in fiche.iteritems(): if(isinstance(value1, basestring) and ('Exigences' in key1 or 'Pre-requis' in key1)): value1 = value1.replace('\t', '') while value1.endswith('\n'): value1 = value1[:-2] while value1.startswith('\n'): value1 = value1[1:] fiche[key1] = RichText(value1) elif isinstance(value1, list): for elem in value1: for key2, value2 in elem.iteritems(): elem[key2] = RichText(value2) context = dictionnaire tpl.render(context) tpl.save(dst)
def gen_a_doc(doc_name, preparation_module=None): """ :param doc_name: It is a string, that contains a template name to render. Like if we have a report_template.docx than to the doc_name should be passed a string 'report_template' Nota Bene! There is to be a data-cooker. Called the same as the template For example: report_template.py And it has to contain a method context(), that returns a context dictionary for jinja2 rendering engine. :return: An file name located in TMP_DEST """ if preparation_module is None: preparation_module = doc_name # WOODOO MAGIC !!!! DOC_TEMPLATES_DIR = getattr(settings, "DOC_TEMPLATES_DIR", None) DOC_CONTEXT_GEN_DIR = getattr(settings, "DOC_CONTEXT_GEN_DIR", None) PROJECT_ROOT = getattr(settings, "PROJECT_ROOT", None) TMP_DEST = getattr(settings, "TMP_DEST", None) TMP_URL = getattr(settings, "TMP_URL", None) doc = DocxTemplate(os.path.join(PROJECT_ROOT, os.path.join(DOC_TEMPLATES_DIR, doc_name + ".docx"))) print(os.path.join(PROJECT_ROOT, os.path.join(DOC_CONTEXT_GEN_DIR, preparation_module))) context_getter = import_module(preparation_module) context = getattr(context_getter, "context")() doc.render(context) ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime("%Y-%m-%d_%H:%M:%S") completeName = os.path.join(TMP_DEST, doc_name + st + ".docx") doc.save(completeName) return TMP_URL + doc_name + st + ".docx"
def download(file_type): '''下载接口''' if file_type not in ['form','scheme']:abort(404) id = request.form.get('id') type = request.form.get('type') data = query_data(type,id) #下载策划 if file_type == 'scheme': if data.filename == 'Nothing':abort(404) content = send_file(path.join(Upload_path,data.rand_filename)) filename = quote(data.filename) #if data.applicant!=current_user.name :abort(404) else : #生成context并进行渲染 context=make_context(data,type) for key,value in context.items() : context[key] = RichText(value) doc = DocxTemplate(path.join(Docx_path,type+'.docx')) doc.render(context) temp_file = path.join(Upload_path,str(current_user.id) +'result.docx') doc.save(temp_file) #读取渲染后的文件并将之删除 with open(temp_file,'rb') as f: content = f.read() if path.exists(temp_file): remove(temp_file) filename = quote(data.association+'-'+types[type][1]+'.docx') response = make_response(content) response.headers['Content-Disposition'] = \ "attachment;filename*=UTF-8''" + filename response.headers['Content-Type'] = 'application/octet-stream' return response
def export_to_word(self,**kargs): filename = kargs['filename'] path = os.path.abspath(os.path.dirname(sys.argv[0])) file = DocxTemplate(filename) # file = docx.Document(path.replace('\\', '/') +'/'+filename) fp = StringIO() file.save(fp) return request.make_response(fp.getvalue(), headers=[('Content-Disposition', content_disposition('标签.docx')), ('Content-Type', 'application/vnd.ms-word')], )
def import_excel(self, **post): fp = StringIO() datas = post['excel'] if datas: if re.match(r".*.xls.?",datas.filename): tmp = datas.stream.read() if tmp: ExcelFile = xlrd.open_workbook(filename=datas.filename,file_contents=tmp) else: return '请选择要导入的文件' if ExcelFile: word_content = [] path = os.path.abspath(os.path.dirname(sys.argv[0])) tpl = DocxTemplate(path.replace('\\', '/') + '/myaddons/abc_ipt/test_word.docx') sheet = ExcelFile.sheet_by_index(0) word_page = [] row_list = [] for i in range(1, sheet.nrows): for k in range(len(sheet.row(i)),7): sheet.row(i).append(xlrd.sheet.Cell("")) row_list = sheet.row(i) print type(row_list[1]) create_dict = { 'address': row_list[1].value or '', 'department': row_list[2].value or '', 'office': row_list[3].value or '', 'name': row_list[4].value or '', 'numbers': str(int(row_list[5].value)) if row_list[5].value else '', 'mac':str((row_list[6].value)) or '' } http.request.env['abc_ipt.ip_phone_importing'].sudo().create(create_dict) word_page.append(create_dict) if len(word_page) == 2: word_content.append(word_page) word_page = [] continue if i == sheet.nrows - 1: word_page.append({ 'address': '', 'department': '', 'office': '', 'name': '', 'number': '', 'mac':'' }) word_content.append(word_page) content = {} content['info'] = word_content tpl.render(content) filename = path.replace('\\', '/') + '/myaddons/abc_ipt/tag.docx' tpl.save(filename) return filename
def test(): """ 演示了如何使用,可以直接执行该文件,但是需要使用自己写的docx模版,和图片 """ tpl = DocxTemplate("tpls/test_tpl.docx") #读取图片的数据且使用base64编码 data = open('tpls/python_logo.png','rb').read().encode('base64') obj={'logo':data} # 需要添加模版对象 ctx={'obj':obj,'tpl':tpl} jinja_env = get_env() tpl.render(ctx,jinja_env) tpl.save('tpls/test.docx')
def document_creator(message): try: pk = int(message.get('pk').decode()) except ValueError as e: logger.error(e) return try: poll_result = PollResult.objects.get(pk=pk) except PollResult.DoesNotExist as e: logger.error(e) return for template in poll_result.poll.templates.objects.all(): doc = DocxTemplate(template.file) doc.render(poll_result.poll_result) doc.save()
def create_source_docx(self, cr, uid, ids, report, context=None): data = DataModelProxy(self.get_docx_data(cr, uid, ids, report, context)) foldname = os.getcwd() temp_out_file = os.path.join(foldname, 'temp_out_%s.docx' % os.getpid()) report_stream = '' doc = DocxTemplate(misc.file_open(report.template_file).name) doc.render({'obj': data}) doc.save(temp_out_file) with open(temp_out_file, 'rb') as input_stream: report_stream = input_stream.read() os.remove(temp_out_file) return (report_stream, report.report_type)
def memo_docx(self, request, pk=None): rotation_request = get_object_or_404(RotationRequest, pk=pk) department = rotation_request.requested_department.get_department() intern = rotation_request.internship.intern # Check if memo is expected department_requires_memo = department.requires_memo if not department_requires_memo: raise ForwardNotExpected("This rotation request does not require a forward.") template_name = "inside_request" if department.hospital.is_kamc else "outside_request" template = DocumentTemplate.objects.get(codename=template_name) docx = DocxTemplate(template.template_file) context = { 'now': timezone.now(), 'contact_name': department.contact_name, 'contact_position': department.contact_position, 'hospital': department.hospital.name, 'intern_name': intern.profile.get_en_full_name(), 'specialty': rotation_request.specialty.name, 'month': rotation_request.month.first_day().strftime("%B"), 'year': rotation_request.month.year, 'badge_number': intern.badge_number, 'mobile_number': intern.mobile_number, 'email': intern.profile.user.email, } docx.render(context) docx_file = StringIO.StringIO() docx.save(docx_file) docx_file.flush() docx_file.seek(0) file_name = "Memo - %s - %s %s" % ( intern.profile.get_en_full_name(), rotation_request.month.first_day().strftime("%B"), rotation_request.month.year, ) response = HttpResponse( FileWrapper(docx_file), content_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document" ) response['Content-Disposition'] = 'attachment; filename=%s.docx' % file_name return response
def run(dico, template, name): tpl = DocxTemplate(template) for fiche in dico['Fiches']: for key1, value1 in fiche.iteritems(): if isinstance(value1, basestring): # fiche[key1] = RichText(value1) pass elif isinstance(value1, list): for elem in value1: for key2, value2 in elem.iteritems(): elem[key2] = RichText(value2) context = dico tpl.render(context) tpl.save(name)
def create_source_docx(self, cr, uid, ids, report, context=None): data = self.get_docx_data(cr, uid, ids, report, context) foldname = os.getcwd() temp_out_file = os.path.join(foldname, 'temp_out_%s.docx' % os.getpid()) report_stream = '' try: doc = DocxTemplate(misc.file_open(report.template_file).name) doc.render({'obj': data}) doc.save(temp_out_file) with open(temp_out_file, 'r') as input_stream: report_stream = input_stream.read() except Exception: raise Exception finally: os.remove(temp_out_file) return (report_stream, report.report_type)
def generate_doc(self, file_name, prefix_name, context, progress, file_num): progress_value = 80 / file_num origin_value = progress.GetValue() new_file_name = prefix_name + "_" + file_name new_file_name = new_file_name.replace('模板', '') msg = "正在生成:" + new_file_name try: doc = DocxTemplate(file_name) progress.Update(origin_value + progress_value * 0.2, msg) doc.render(context) progress.Update(origin_value + progress_value * 0.6, msg) doc.save(new_file_name) except BaseException: print("file save error in doc") self.file_generate_error = True wx.MessageBox("文件写如错误,请检查word文件是否关闭,关闭后重试", "提示", wx.OK | wx.ICON_INFORMATION) progress.Update(origin_value + progress_value * 0.8, msg) time.sleep(0.5) self.reset_file_save_path(new_file_name) progress.Update(origin_value + progress_value * 1, msg)
def create_source_docx(self, cr, uid, ids, report, context=None): data = DataModelProxy(self.get_docx_data(cr, uid, ids, report, context)) tempname = tempfile.mkdtemp() temp_out_file = self.generate_temp_file(tempname) doc = DocxTemplate(misc.file_open(report.template_file).name) #2016-11-2 支持了图片 #1.导入依赖,python3语法 from . import report_helper #2. 需要添加一个"tpl"属性获得模版对象 doc.render({'obj': data,'tpl':doc},report_helper.get_env()) doc.save(temp_out_file) if report.output_type == 'pdf': temp_file = self.render_to_pdf(temp_out_file) else: temp_file = temp_out_file report_stream = '' with open(temp_file, 'rb') as input_stream: report_stream = input_stream.read() os.remove(temp_file) return report_stream, report.output_type
def document_template(): context_raw = request.form['context'] document = request.files['document'] context = json.loads(context_raw) template = DocxTemplate(document) template.render(context) try: template.save('template.docx') return send_file( './template.docx', as_attachment=True, attachment_filename='template.docx' ) except FileNotFoundError: template.save('/server/template.docx') return send_file( './template.docx', as_attachment=True, attachment_filename='template.docx' )
def download_file(filename): doc = DocxTemplate( "C:/Users/Danyal/Desktop/Arwentech/mainweb/upload/{}".format( filename)) if request.method == "POST": var_input = request.form['invoice'] data = requests.get( 'http://151.80.237.86:1251/ords/zkt/exprt_doc/doc?pi_no={}'.format(var_input)) data = data.json() # take_input = int(input('Please enter your invoice: ')) pythoncom.CoInitialize() for x in data['items']: # if x['pi_no'].strip() == 'GSAGROPAK- {}'.format(str()): # 17865 doc.render(x) file_stream = StringIO() # time.sleep(1) doc.save('./static/{}.docx'.format(str(file_stream))) convert('./static/{}.docx'.format(str(file_stream)), './static/{}.pdf'.format(str(file_stream))) return render_template('upload_file.html')
def create_word_file(model_path, file_path, file_content): """ 填充word模板 :param model_path: 模板文件路径 :param file_path: 新文件路径 :param file_content: 填充的内容 :return: 模板文件内容: {{t1}}去了,有再来的时候;{{t2}}枯了,有再青的时候;{{t3}}谢了,有再开的时候。 但是,聪明的,你告诉我,我们的日子为什么一去不复返呢?——是有人偷了他们罢:那是谁?又藏在何处呢? 是他们自己逃走了罢:现在又到了哪里呢? 我不知道他们给了我多少日子;但我的手确乎是渐渐空虚了。在默默里算着,八千多日子已经从我手中溜去; 像{{t4}}上一滴水滴在大海里,我的日子滴在时间的流里,没有声音,也没有影子。我不禁头{{t5}}而{{t6}}了。 {{t7}}年{{t8}}月{{t9}}日 file_content: { 't1': '燕子', 't2': '杨柳', 't3': '桃花', 't4': '针尖', 't5': '头涔涔', 't6': '泪潸潸', 't7': '2020', 't8': '10', 't9': '20', } """ doc = DocxTemplate(model_path) doc.render(file_content) doc.save(file_path) return True
def printed(self): file_name = self.get_file_name() file_name = file_name.replace("ъ", '').replace("ь", '').replace( '"', '').replace('«', '').replace('»', '') file_name = transliterate(file_name, space='_') filename = os.path.split('/')[-1].split('.')[0] if not os.path.exists(settings.DIR_FOR_TMP_FILES): os.makedirs(settings.DIR_FOR_TMP_FILES) tmp_path = tempfile.mkdtemp(dir=settings.DIR_FOR_TMP_FILES) docx_path = '%s/%s.docx' % (tmp_path, filename) try: docx = DocxTemplate(self.get_print_template()) context = self.get_print_context_data(docx_tpl=docx) if images := context.get('images'): for key, image_params in images.items(): context[key] = InlineImage(docx, image_params.path, width=image_params.width, height=image_params.height) docx.render(context) docx.save(docx_path) with open(docx_path, mode='rb') as file: # сгенерируем HttpResponse-объект с pdf response = HttpResponse( file.read(), content_type= "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ) response[ 'Content-Disposition'] = 'filename=%s.docx' % file_name return response
def prepareOtNIT(bid): otpns = OtProposalNoteSheet.objects.get(bid=bid) qr = QR.objects.get(bid=bid) indent_no = str(bid.indent_number) context = { 'indent_no': str(bid.indent_number), 'ref_no': get_ref_no(bid), 'issue_dt': "{{issue_dt}}", 'subject': bid.bid_subject, 'engineer_incharge': otpns.engineerIncharge, 'address_consigne': otpns.addressConsignee, 'doc_price': str(getDocPrice(otpns.estCost)), 'emd_price': str(getEmdPrice(otpns.estCost)), 'doc_price_words': amount2words(getDocPrice(otpns.estCost)), 'emd_price_words': amount2words(getEmdPrice(otpns.estCost)), 'bid_sub_dt': "{{bid_sub_dt}}", 'pre_bid_dt': "{{pre_bid_dt}}", 'bod_dt': "{{bod_dt}}", 'est_cost': str(otpns.estCost), 'three_order_value': str(qr.threeordervalue), 'two_order_value': str(qr.twoordervalue), 'one_order_value': str(qr.oneordervalue), 'maat_value': str(qr.maatvalue), 'est_cost_words': amount2words(otpns.estCost), 'bid_open_days': otpns.bidopendays, 'tender_cat': otpns.tenderCategory, 'product_cat': otpns.productCategory, 'intend_dpt': get_indentdept(bid), } foldername = "I-" + indent_no + "/" if not os.path.exists(os.path.dirname(foldername)): os.makedirs(os.path.dirname(foldername)) filename = foldername + "I-" + indent_no + "_Tender_Document" doc = DocxTemplate("Template_Tender_Document.docx") doc.render(context, autoescape=True) doc.save(filename + ".docx") return filename + ".docx"
def print_report(self): self.ensure_one() datadir = os.path.dirname(__file__) f = os.path.join(datadir, 'templates/BTB.docx') # if platform.system() == 'Linux': # f = os.path.join(datadir, 'templates/BTB.docx') template = DocxTemplate(f) context = self.get_data() template.render(context) filename = ('/tmp/BTB-' + str(datetime.today().date()) + '.docx') # if platform.system() == 'Linux': # filename = ('/tmp/BTB-' + str(datetime.today().date()) + '.docx') template.save(filename) fp = open(filename, "rb") file_data = fp.read() out = base64.encodestring(file_data) attach_vals = { 'po_service_btb_filename': filename, 'po_service_btb_data': out, } act_id = self.env['purchase.order.service.btb.output'].create( attach_vals) fp.close() # print_job(filename) --> print to default printer return { 'type': 'ir.actions.act_window', 'res_model': 'purchase.order.service.btb.output', 'res_id': act_id.id, 'view_type': 'form', 'view_mode': 'form', 'context': self.env.context, 'target': 'new', }
def generatereport(d): # filename = report_name # 所生成的word文档需要以.docx结尾,文档格式需要 filepath = path_name img_name = path_name + d + ".png" filename = path_name + d + ".docx" template_path = os.getcwd() + '/test.docx' #加载模板文件 template = DocxTemplate(template_path) if os.path.exists(img_name) == False: #判断下面代码使用的图片是否存在,不存在则调用函数生成 plt_fc(img_name) context = { 'text': '哈哈哈,来啦', 't1': '燕子', 't2': '杨柳', 't3': '桃花', 't4': '针尖', 't5': '头涔涔', 't6': '泪潸潸', 't7': '茫茫然', 't8': '伶伶俐俐', 'picture1': InlineImage(template, img_name, width=Mm(80), height=Mm(60)), } user_labels = ['姓名', '年龄', '性别', '入学日期'] context['user_labels'] = user_labels user_dict1 = {'number': 1, 'cols': ['林小熊', '27', '男', '2019-03-28']} user_dict2 = {'number': 2, 'cols': ['林小花', '27', '女', '2019-03-28']} user_list = [] user_list.append(user_dict1) user_list.append(user_dict2) context['user_list'] = user_list template.render(context) template.save(os.path.join(filepath, filename))
def create_dcv_admission_pdf_contents(dcv_admission): licence_template = GlobalSettings.objects.get( key=GlobalSettings.KEY_DCV_ADMISSION_TEMPLATE_FILE) if licence_template._file: path_to_template = licence_template._file.path else: raise Exception('DcvAdmission template file not found.') doc = DocxTemplate(path_to_template) serializer_context = { 'dcv_admission': dcv_admission, } # context_obj = ApprovalSerializerForLicenceDoc(approval, context=serializer_context) # context = context_obj.data # doc.render(context) doc.render({}) temp_directory = settings.BASE_DIR + "/tmp/" try: os.stat(temp_directory) except: os.mkdir(temp_directory) f_name = temp_directory + 'dcv_admission' + str(dcv_admission.id) new_doc_file = f_name + '.docx' new_pdf_file = f_name + '.pdf' doc.save(new_doc_file) os.system("libreoffice --headless --convert-to pdf " + new_doc_file + " --outdir " + temp_directory) file_contents = None with open(new_pdf_file, 'rb') as f: file_contents = f.read() os.remove(new_doc_file) os.remove(new_pdf_file) return file_contents
def doc(n): # Acessa o modelo template para tarefas em geral, e guarda na variável tmp tmp = DocxTemplate("template.docx") # Todos os tipos de edições no .docx que podem ser feitas utilizando essa função context = { 1:{"prof":"Walter Maluf Júnior","date":data,"mat":"MATEMÁTICA"}, 2:{"prof":"Rowlian Luciano Dantas","date":data,"mat":"QUÍMICA"}, 3:{"prof":"Paulo César Franco","date":data,"mat":"BIOLOGIA"}, 4:{"prof":"Ana Maria","date":data,"mat":"PORTUGUÊS"}, 5:{"prof":"Leandro Carlos Santos Rosa","date":data,"mat":"CULTURA RELIGIOSA"}, 6:{"prof":"Leandro Carlos Santos Rosa","date":data,"mat":"FILOSOFIA"}, 7:{"prof":"Thiago Carrara de Lima","date":data,"mat":"FÍSICA"}, 8:{"prof":"Gustavo Borges de Sousa","date":data,"mat":"ARTES"}, 9:{"prof":"Gustavo Borges de Sousa","date":data,"mat":"LITERATURA"}, 10:{"prof":"Fabiana Vieira da Silva","date":data,"mat":"GEOGRAFIA"}, 11:{"prof":"Edgar Luiz Carvalho Macedo de Noronha","date":data,"mat":"HISTÓRIA"}, 12:{"prof":"Ana Flávia Sabino Vilela","date":data,"mat":"INGLÊS"}, 13:{"prof":"Adriano Donizete Rodrigues da Silva","date":data,"mat":"SOCIOLOGIA"} } # Escreve as alterações baseado no número da matéria escolhida tmp.render(context[n]) # Salva o novo arquivo com o nome escolhido tmp.save("%s.docx" % (nome,))
def get_text(self): text_get = self.text_edit.get("1.0", END) text_get2 = self.text_edit2.get("1.0", END) # discip_get = self.combobox_discip.get() # stype_ed_prog_get = self.combobox_ed_prog.get() doc = DocxTemplate("data/RPD1.docx") context = { 'target': text_get, 'task': text_get2, 'mesto_discip': "{{mesto_discip}}", 'description1': "{{description1}}", 'kod_komp1': "{{kod_komp1}}", 'description2': "{{description2}}", 'kod_komp2': "{{kod_komp2}}", 'zuv1_1': "{{zuv1_1}}", 'zuv1_2': "{{zuv1_2}}", 'zuv1_3': "{{zuv1_3}}", 'zuv2_1': "{{zuv2_1}}", 'zuv2_2': "{{zuv2_2}}", 'zuv2_3': "{{zuv2_3}}" } doc.render(context) doc.save("data/RPD2.docx") mb.showinfo("Внимание", "Титульный лист сформирован")
def create_report(sample_id, template_file, output_path, output_file): """生成报告 """ dt = get_data(sample_id) # dis_detail = get_disease_detail('600974') gene_table = proc_gene_list(dt) minors_info = proc_dis(dt['minors']) var_detail = get_var_detail(dt) tpl = DocxTemplate(template_file) # read the mutation table # majors_info = [xx for xx in dt['majors']] # dis_details = map(get_disease_detail, get_disease_id(dt)) result_desc = get_result_desc(dt) dis_details = get_disease_detail(dt) content = { 'mut_info': dt['majors'], 'patient_info': dt['patient']['data'], 'minors_info': minors_info, 'null': '无', 'gene_table': gene_table, 'var_detail': var_detail, # 变异详情 'dis_details': dis_details, # 疾病简介 'result_desc': result_desc, 'gene_info': [] } tpl.render(content) if not output_file: patient_name = dt['patient']['data']['name'] output_file = '基因分析报告-{sample_id}-{patient_name}-{date}.docx'.format( sample_id=dt['patient']['data']['sn'], patient_name=patient_name, date=time.strftime('%Y-%m-%d', time.localtime(time.time()))) tpl.save(os.path.join(output_path, output_file)) # logger.info('报告路径:{path}'.format(path=os.path.join(output_path, output_file))) return open(os.path.join(output_path, output_file), 'rb')
def post(self, request): title = request.POST['title'] name = request.POST['name'] university = request.POST['university'] address = request.POST['address'] email = request.POST['email'] annotation = request.POST['annotation'] introduction = request.POST['introduction'] article = request.POST['article'] conclusion = request.POST['conclusion'] literature = request.POST['literature'] document = DocxTemplate('example.docx') context = { 'title': title, 'name': name, 'university': university, 'address': address, 'email': email, 'annotation': annotation, 'introduction': introduction, 'article': article, 'conclusion': conclusion, 'literature': literature } document.render(context) # document.save("generated_doc.docx") response = HttpResponse( content_type= 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ) response['Content-Disposition'] = 'attachment; filename=download.docx' document.save(response) return response
def write_act(): doc = DocxTemplate("tpl_invoice_2.docx") context = { 'var2': provider_inn, 'var3': provider_kpp, 'var4': provider_name, 'var8': num['number'], 'var9': datetime.datetime.today().strftime("%d.%m.%Y"), 'var10': provider_address, 'var11': data['value'], 'var12': data['data']['inn'], 'var13': client_kpp, 'var14': data['data']['address']['value'], 'var15': nds_3, 'var17': nds_4, 'var18': summa_str, 'var19': num2words(int(summa), lang='ru').capitalize(), 'var20': count, #len(data_post['invoice']), 'tbl_contents': bag, } #print (len(data_post['invoice'])) doc.render(context) doc.save("doc_2_" + key + ".docx") convert_file("doc_2_" + key + ".docx", "doc_2_" + key + ".pdf")
def generate_questionnaire_file(questionnaire): """ Generate a word Docx document for the given questionnaire. The generated docment is based on a Docx template. This is made possible thanks to docxtepl Python package. """ doc = DocxTemplate(settings.TEMPLATE_DIR + "/ecc/questionnaire.docx") context = { 'questionnaire': questionnaire, 'description': RichText(questionnaire.description) } doc.render(context) filename = f'Questionnaire-{questionnaire.numbering}.docx' # Why do we need both relative and absolte path? # For django's FileField, we need a relative path from the root of the MEDIA_ROOT. # For saving the file via DocxTemplate, we need to absolute path. relative_path = questionnaire_file_path(questionnaire, filename) absolute_path = os.path.join(settings.MEDIA_ROOT, relative_path) file_folder = ntpath.split(absolute_path)[0] if not os.path.exists(file_folder): os.makedirs(file_folder) doc.save(absolute_path) questionnaire.generated_file = relative_path questionnaire.save()
def make_doc_file(bkm_info_list): '''Gegernate a BKM meeting invitation message''' tpl = DocxTemplate('meeting_invitation_message_template.docx') result = [] for bkm_info in bkm_info_list: dic = {} dic['bkm_nums'] = bkm_info.get()[0] bkm_pdf_link = bkm_info.get()[5] rt = RichText() rt.add(bkm_info.get()[1], url_id=tpl.build_url_id(bkm_pdf_link), color='blue', underline=True) dic['bkm_titles'] = rt dic['authors'] = bkm_info.get()[2] dic['apprs'] = bkm_info.get()[3] dic['create_dates'] = bkm_info.get()[4] result.append(dic) print('成功获取BKM数据, 正在将数据写入模板......') context = {'bkm': result} tpl.render(context) tpl.save('meeting_invitation_message.docx')
def cmd_create_new(): if file["text"]: if pattern["text"]: doc = DocxTemplate(pattern["text"][8:]) if doc != "": report["text"] = "" report_name = fd.asksaveasfilename( defaultextension="*.*", filetypes=( ("Документ Word", "*.docx"), ("Документ Word 97-2003", "*.doc"), ("Текст в формате RTF", "*.rtf"), )) context = dict() context["legalName"] = legalName.get(1.0, END) context["prim"] = prim.get(1.0, END).replace("\n", "<w:br/>") context["registrationDate"] = registrationDate.get(1.0, END) context["INN"] = inn.get(1.0, END) context["OGRN"] = ogrn.get(1.0, END) context["legalAddress"] = legalAddress.get(1.0, END) context["principalActivity"] = principalActivity.get(1.0, END) context["statedCapitalSum"] = statedCapitalSum.get(1.0, END) context["uchr"] = uchr.get(1.0, END).replace("\n", "<w:br/>") context["uchrEx"] = uchrEx.get(1.0, END) context["shareholderRegister"] = shareholderRegister.get( 1.0, END) context["heads"] = heads.get(1.0, END) context["oldHeads"] = oldHeads.get(1.0, END).replace( "\n", "<w:br/>") doc.render(context) if report_name: report["text"] = f"Отчёт: {report_name}" doc.save(report_name) # смена цвета кнопок btn_3["bg"] = "lightgreen" btn_4["bg"] = "lightgrey"
def convert(self, jira_json): doc = DocxTemplate(self.templatefile) context = {} context["ticketnumber"] = jira_json["key"] context["priority"] = jira_json["fields"]["priority"]["name"] context["pref_resolution_date"] = RFCConverter.cleandate(jira_json["fields"]["duedate"]) context["createdate"] = RFCConverter.cleandate(jira_json["fields"]["created"]) context["submitter"] = jira_json["fields"]["creator"]["displayName"] context["components"] = ", ".join([x["name"] for x in jira_json["fields"]["components"]]) context["submittermail"] = jira_json["fields"]["creator"]["emailAddress"] context["description"] = R(jira_json["fields"]["description"]) context["accepted_by"] = jira_json["fields"]["creator"]["displayName"] context["print_date"] = RFCConverter.cleandate() context["verified_by"] = jira_json["fields"]["creator"]["displayName"] context["change_number"] = jira_json["key"] doc.render(context) target = StringIO() doc.save(target) target.seek(0) name = "RFC_" + jira_json["key"] + ".docx" return name, target
def download_inv_file(filename, inv, yr): x = requests.get( 'http://151.80.237.86:1251/ords/zkt/pi_doc/doc?invno={}/{}'.format(inv, yr)) data = x.json() doc = DocxTemplate( "./{}".format( filename)) # take_input = int(input('Please enter your invoice: ')) pythoncom.CoInitialize() for x in data['items']: if x['invno'].strip() == '{}/{}'.format(str(inv), str(yr)): # 17865 # if x['invno'].strip() == '{}'.format(str(inv)): doc.render(x) file_stream = StringIO() # time.sleep(1) doc.save('./static/static-base/file.docx') convert('./static/static-base/file.docx', './static/static-base/file.pdf') flash("Your file has been created, Now you can download!!") return render_template('Invoice.html')
def modifyDoc(companyName, positionName): todayDate = datetime.datetime.today().strftime('%m/%d/%Y') # Assigns each variable a dictionary value of the same name contextDict = { 'todayDate': todayDate, 'companyName': companyName, 'postionName': positionName } # Open Master CoverLetter template home = Path.home() doc = DocxTemplate("CoverLetter/mainCoverLetter.docx") # Load Variable names into file and replace template doc.render(contextDict) # Save the file with Modified filename doc.save(companyName + '_' + positionName + '_CoverLetter.docx') exportPath = Path.cwd() label[ 'text'] = 'Success!\nYour Cover Letter has been created\nIt has been placed in: ' + str( exportPath)
def generalFile(): sheet1 = readParamSheet() titles = getTitles(sheet1) print("=======>参数列表:" + str(titles)) rows = sheet1.nrows # 表格行数 cols = sheet1.ncols # 表格列数 composer = None print("======>根据模板生成结果") # 读取数据并生成文件 for i in range(1, rows): # 跳过表头一行 data = {} # 构造填充模板需要的数据 for j in range(0, cols): val = sheet1.cell_value(i, j) # 第i行代表第i行数据 title = titles[j] data[title] = val doc = DocxTemplate(TEMPLATE_DOC) # 打开一个模板 doc.render(data) # 填充数据data到模板 doc.save("temp.docx") composer = composeDoc(composer, i, rows) print(">>>>>>>>>正在保存结果") composer.save("结果.docx") os.remove("temp.docx")
def get(self, request, *args, **kwargs): tpl = DocxTemplate( '/application/static-backend/export_template/RPD_shablon_2020_new.docx' ) queryset = WorkProgram.objects.get(pk=kwargs['pk']) serializer = WorkProgramSerializer(queryset) data = dict(serializer.data) context, filename = render_context(data, field_of_study_id=kwargs['fs_id'], academic_plan_id=kwargs['ap_id'], year=kwargs['year']) tpl.render(context) # tpl.save('/application/'+str(filename)) #-- сохранение в папку локально (нужно указать актуальный путь!) response = HttpResponse( content_type= 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ) response['Content-Disposition'] = 'inline; filename="%s"' % filename tpl.save(response) return response
def print_report(self): self.ensure_one() datadir = os.path.dirname(__file__) if platform.system() == 'Linux': f = os.path.join(datadir, 'templates/kontrabon_template.docx') else: f = os.path.join(datadir, 'templates\kontrabon_template.docx') template = DocxTemplate(f) context = self.get_data() template.render(context) if platform.system() == 'Linux': filename = ('/tmp/BSPKontrabon-'+ self.kontrabon + '-' + str(datetime.today().date()) + '.docx') else: filename = ('BSPKontrabon-' + self.kontrabon + '-' + str(datetime.today().date()) + '.docx') template.save(filename) fp = open(filename, 'rb') file_data = fp.read() out = base64.encodestring(file_data) attach_vals = { 'bsp_kontrabon_data': filename, 'file_name': out, } act_id = self.env['kontra.bon.print.docx'].create(attach_vals) fp.close() return { 'type': 'ir.actions.act_window', 'res_model': 'kontra.bon.print.docx', 'res_id': act_id.id, 'view_type': 'form', 'view_mode': 'form', 'context': self.env.context, 'target': 'new', }
def export_report_docx(data, report_tpl_path, generate_report_word): tpl = DocxTemplate(report_tpl_path) context = {"empty": "N/A"} for key in data.keys(): if key not in context: if key.lower() == "version": context[key] = data[key] elif key.lower() == "testname": context[key] = data[key] else: context[key] = {} if len(data[key]) == 0: context[key]["flag"] = False else: context[key]["flag"] = True context[key]["image"] = [] for element in data[key]: context[key]["image"].append( InlineImage(tpl, element, width=Mm(159.0))) jinja_env = jinja2.Environment(autoescape=True) tpl.render(context, jinja_env) tpl.save(generate_report_word)
def generate(docket): doc = DocxTemplate("template.docx") case = db.collection('cases').document(docket).get() datestr = date.today().strftime("%b-%d-%Y") opinions = db.collection('cases').document(docket).collection( 'opinions').stream() users = [] for opinion in opinions: thought = opinion.to_dict() user = db.collection('users').document(opinion.id).get() if user.exists: user = user.to_dict() else: print("this should never happen") print('opinion stored uid', opinion.id) continue user.update({'thought': thought}) users.append(user) if (len(users) == 0): return 'not enough data' case = case.to_dict() doc.render({ 'users': users, 'date': datestr, 'case': case, 'supportedgroup': case['respondent'] if (case['totalCount'] - case['plantiffCount'] > case['plantiffCount'] ) else case['petitioner'] }) title = "generated_doc.docx" doc.save(title) return send_file(title, attachment_filename=(docket + '-amicus.docx'))
def get_report_doc(self): self.ensure_one() req = self.env['purchase.request'].browse( self._context.get('active_ids', list())) datadir = os.path.dirname(__file__) f = os.path.join(datadir, 'templates//bppb.docx') template = DocxTemplate(f) context = self.get_data() template.render(context) if platform.system() == 'Linux': filename = ('/tmp/BPPB-' + str(datetime.today().date()) + '.docx') else: filename = ('BPPB-' + str(datetime.today().date()) + '.docx') template.save(filename) fp = open(filename, "rb") file_data = fp.read() out = base64.encodestring(file_data) # Files actions attach_vals = { 'purchase_request_data': filename, 'file_name': out, } act_id = self.env['qcf.report.out'].create(attach_vals) fp.close() return { 'type': 'ir.actions.act_window', 'res_model': 'qcf.report.out', 'res_id': act_id.id, 'view_type': 'form', 'view_mode': 'form', 'context': self.env.context, 'target': 'new', }
def post(self, request, *args, **kwargs): logger.debug("PetitionFormView post") form = self.form_class(request.POST) profile = request.user.expungerprofile logger.debug("petition post with: %s" % form) if form.is_valid(): context = { "organization": profile.organization, "attorney": profile.attorney, "petitioner": form.get_petitioner(), "petition": form.get_petition(), "docket": form.get_docket_id(), "restitution": form.get_restitution(), } docx = os.path.join(BASE_DIR, "petition", "templates", "petition", "petition.docx") document = DocxTemplate(docx) jinja_env = jinja2.Environment() jinja_env.filters['comma_join'] = lambda v: ",".join(v) document.render(context, jinja_env) response = HttpResponse( content_type= "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ) response[ 'Content-Disposition'] = 'attachment; filename="petition.docx"' document.save(response) logger.debug("petition form: %s" % form) return response logger.debug("invalid petition form: %s" % form) return render(request, PetitionFormView.template_name, {"form": form})
def save_file(template, pop_context): layout = [[sg.Text('Please Select save location')], [sg.Input(), sg.FolderBrowse()], [sg.Text("Filename:"), sg.InputText('populated')], [sg.OK(), sg.Cancel()]] window = sg.Window('Select save', layout) event, values = window.Read() if values[0]: save = values[0] doc = DocxTemplate(template) context = pop_context doc.render(context) save_path = f"{save}/{datetime.now().strftime('%m%d_%H%M%S')}_{values[1]}.docx" doc.save(save_path) else: error_msg('You did not select a document') raise window.close() sg.Popup('Success', f"Successfully saved populated document to {save_path}")
def generate_service(request_json, users, mail, minio_client, owner_email): try: doc = DocxTemplate("templates/request.docx") user = users.find_one({"email": get_jwt_identity()}) context = build_document_input(user, request_json) doc.render(context) doc.save("result.docx") file_name = f'Cerere-{user["firstName"]}-{user["lastName"]}-{str(uuid.uuid1())}.docx' with open("result.docx", "rb") as f: minio_client.upload_fileobj(f, 'lexbox', file_name) os.remove('result.docx') download_link = f'http://localhost:9000/lexbox/{file_name}' msg = Message('Notificare LexBox', sender=os.getenv('EMAIL'), recipients=[owner_email]) msg.html = render_template("NotificationEmail.html", firstName=user['firstName'], lastName=user['lastName'], documentUrl=download_link) mail.send(msg) return ResponseBuilder.success({"download_link": download_link}) except Exception as e: return ResponseBuilder.failure(str(e))
def redactDocx(path_to_shablon, path_to_save_docx, Data, response): '''изменяет шаблон документа doc''' doc = DocxTemplate(path_to_shablon) context = { 'act_number': Data['act_number'], 'date': Data['date'], 'time': Data['time'], 'position01': Data['position01'], 'name01': Data['name01'], 'position02': Data['position02'], 'name02': Data['name02'], 'position03': Data['position03'], 'name03': Data['name03'], 'position04': Data['position04'], 'name04': Data['name04'], 'seller_name': Data['seller_name'], 'seller_addres': Data['seller_addres'], 'number_date_contract': Data['number_date_contract'], 'contract_date': Data['contract_date'], 'type_transport': Data['type_transport'], 'number_transport': Data['number_transport'], 'type_documents': Data['type_documents'], 'number_documents': Data['number_documents'], 'date_documents': Data['date_documents'], 'date_arrival': Data['date_arrival'], 'weight_consignment': Data['weight_consignment'], 'weight_transport_with_cargo': Data['weight_transport_with_cargo'], 'weight_transport_without_cargo': Data['weight_transport_without_cargo'], 'actual_weight': Data['actual_weight'], 'weight_deficit': Data['weight_deficit'], 'weediness': Data['weediness'], 'load_weight': Data['load_weight'] } doc.render(context) return doc.save(response)
def export_resume(self,ids): # 定义压缩文件流 zip_stream = StringIO() resume_zip = zipfile.ZipFile(zip_stream,'w') # 将参数转为列表 id_list = json.loads(ids) # 获取要到处简历的员工 Model = request.session.model('hr.employee') employees = Model.search_read([('id','in',id_list)]) job='' for i,employee in enumerate(employees): # 获取模板 path = os.path.abspath(os.path.dirname(sys.argv[0])) tpl = DocxTemplate(path.replace('\\','/')+'/myaddons/nantian_erp/resume_template.docx') # 简历写入的文件流 fp = StringIO() experiences_list = [] certifications_dict=[] if employee['job_id']: job = employee['job_id'][1] if employee['work_experience_ids']: Model = request.session.model('nantian_erp.work_experience') experiences = Model.search_read([('id','in',employee['work_experience_ids'])]) for exper in experiences: exper_dict = {'date':exper['date'] or '','name':exper['name'].replace('&','&') or '','job':exper['job'].replace('&','&') or '','description':exper['description'].replace('&','&') or ''} experiences_list.append(exper_dict) if employee['certificate_ids']: count = 0 Model = request.session.model('nantian_erp.certificate') certificates = Model.search_read([('id','in',employee['certificate_ids'])]) for cer in certificates: count = count + 1 image = '' name = '' if cer['image']: # 将base64 转为图片 f = StringIO(base64.b64decode(str(cer['image']))) print "查看图片名称%d"%count try: image = InlineImage(tpl,f) except Exception: pass #image = InlineImage(tpl,f,height=Mm(30)) f.close() if cer['name']: name = cer['name'].replace('&','&') certificate = {'name':name or '','image': image or '',} certifications_dict.append(certificate) gender = '' if employee['gender'] == 'male': gender = u'男' elif employee['gender'] == 'female': gender = u'女' # 模板所需数据 resume_dict = {'name':employee['name'] or '', 'gender':gender or '', 'birthday':employee['birthday']or '', 'education':employee['education']or '', 'graduction':employee['graduation']or '', 'major':employee['major']or '', 'job':job or '', 'work_time':employee['work_time']or '', 'specialty':employee['specialty']or '', 'work_experiences':experiences_list or [], 'certifications':certifications_dict or [], } # encode_json = json.dumps(resume_dict) # rep_resume_dict = encode_json.replace('&','&') # resume_dict = json.loads(rep_resume_dict) # print resume_dict tpl.render(resume_dict) tpl.save(fp) fp.seek(0) resume_zip.writestr(employee['name']+u'简历'+'.docx',fp.getvalue()) fp.close() resume_zip.close() zip_stream.seek(0) # 返回压缩文件 return request.make_response(zip_stream.getvalue() , headers=[('Content-Disposition',content_disposition(u'简历'+'.zip')), ('Content-Type', 'application/zip')], )
from docxtpl import DocxTemplate tpl=DocxTemplate('test_files/dynamic_table_tpl.docx') context = { 'col_labels' : ['fruit', 'vegetable', 'stone', 'thing'], 'tbl_contents': [ {'label': 'yellow', 'cols': ['banana', 'capsicum', 'pyrite', 'taxi']}, {'label': 'red', 'cols': ['apple', 'tomato', 'cinnabar', 'doubledecker']}, {'label': 'green', 'cols': ['guava', 'cucumber', 'aventurine', 'card']}, ] } tpl.render(context) tpl.save('test_files/dynamic_table.docx')
# -*- coding: utf-8 -*- ''' Created : 2015-03-12 @author: Eric Lapouyade ''' from docxtpl import DocxTemplate tpl=DocxTemplate('test_files/header_footer_entities_tpl.docx') context = { 'title' : 'Header and footer test', } tpl.render(context) tpl.save('test_files/header_footer_entities.docx')
# -*- coding: utf-8 -*- ''' Created : 2016-07-19 @author: AhnSeongHyun Edited : 2016-07-19 by Eric Lapouyade ''' from docxtpl import DocxTemplate tpl=DocxTemplate('test_files/header_footer_tpl_utf8.docx') sd = tpl.new_subdoc() p = sd.add_paragraph(u'This is a sub-document to check it does not break header and footer with utf-8 characters inside the template .docx') context = { 'title' : u'헤더와 푸터', 'company_name' : u'세계적 회사', 'date' : u'2016-03-17', 'mysubdoc' : sd, } tpl.render(context) tpl.save('test_files/header_footer_utf8.docx')
# -*- coding: utf-8 -*- ''' Created : 2015-03-12 @author: Eric Lapouyade ''' from docxtpl import DocxTemplate tpl=DocxTemplate('test_files/order_tpl.docx') context = { 'customer_name' : 'Eric', 'items' : [ {'desc' : 'Python interpreters', 'qty' : 2, 'price' : 'FREE' }, {'desc' : 'Django projects', 'qty' : 5403, 'price' : 'FREE' }, {'desc' : 'Guido', 'qty' : 1, 'price' : '100,000,000.00' }, ], 'in_europe' : True, 'is_paid': False, 'company_name' : 'The World Wide company', 'total_price' : '100,000,000.00' } tpl.render(context) tpl.save('test_files/order.docx')
p.add_run('python-docx').italic = True p.add_run(' library') sd.add_heading('Heading, level 1', level=1) sd.add_paragraph('This is an Intense quote', style='IntenseQuote') sd.add_paragraph('A picture :') sd.add_picture('python_logo.png', width=Inches(1.25)) sd.add_paragraph('A Table :') table = sd.add_table(rows=1, cols=3) hdr_cells = table.rows[0].cells hdr_cells[0].text = 'Qty' hdr_cells[1].text = 'Id' hdr_cells[2].text = 'Desc' recordset=( (1,101,'Spam'), (2,42,'Eggs'), (3,631,'Spam,spam, eggs, and ham') ) for item in recordset: row_cells = table.add_row().cells row_cells[0].text = str(item[0]) row_cells[1].text = str(item[1]) row_cells[2].text = item[2] context = { 'mysubdoc' : sd, } tpl.render(context) tpl.save('test_files/subdoc.docx')
def main(): config = configparser.ConfigParser() config.read('autotemplation.ini') template_folder_ids = config['DEFAULT']['TemplateFolderID'].split(',') destination_folder_name = config['DEFAULT']['DestinationFolderName'] credentials = get_credentials() http = credentials.authorize(httplib2.Http()) drive_service = discovery.build('drive', 'v3', http=http) destination_folder_id = get_or_create_destination_folder_id( drive_service, destination_folder_name) template_file = get_template(drive_service, template_folder_ids) mime_type, is_sheet = get_mime_type(template_file['mimeType']) request = drive_service.files().export_media( fileId=template_file['id'], mimeType=mime_type) fh = io.BytesIO() downloader = MediaIoBaseDownload(fh, request) done = False while done is False: status, done = downloader.next_chunk() print("Download %d%%." % int(status.progress() * 100)) if is_sheet: print("Spreadsheet selected, converting to Doc. (Slow)") table_data = get_sheet_data(fh) row_count = len(table_data) col_count = len(table_data[0]) document = Document() doc_table = document.add_table(rows=row_count, cols=col_count) for r, row in enumerate(table_data): row_cells = doc_table.rows[r].cells print("Converting row {}/{}...".format(r+1, row_count), end="\r") for i, cell in enumerate(row): if cell: row_cells[i].text = cell print("Conversion complete. " "Warning: Processing large sheets will take some time.") temp_doc_file = io.BytesIO() document.save(temp_doc_file) doc = DocxTemplate(temp_doc_file) else: doc = DocxTemplate(fh) full_doc = doc.get_docx() template_vars = get_template_variables(full_doc, template_file['name']) if any('__' in x for x in template_vars): worksheet = get_worksheet(credentials) worksheet_headers = get_worksheet_headers(worksheet) context = dict() get_date_and_set_context(context) for var in template_vars: if var not in context: if '__' in var: context[var] = worksheet_lookup( worksheet, worksheet_headers, var) else: context[var] = input("Enter a value for {}: ".format(var)) new_file_name = get_target_name(template_file['name'], context) doc.render(context) temp_file = tempfile.NamedTemporaryFile() doc.save(temp_file) if is_sheet: csv_name = '{}.csv'.format(new_file_name) doc_csv = DocxTemplate(temp_file) csv_data = get_table_data_for_csv(doc_csv) if csv_data: with open(csv_name, 'w') as output: writer = csv.writer(output, lineterminator='\n') writer.writerows(csv_data) print('{} created in local folder'.format(csv_name)) else: print('Unable to create CSV. ' 'Less than or more than 1 table found.') workbook = Workbook() sheet = workbook.get_active_sheet() for row in csv_data: sheet.append(row) workbook.save(temp_file) upload_mimetype = 'application/vnd.google-apps.spreadsheet' else: upload_mimetype = 'application/vnd.google-apps.document' file_metadata = { 'name': new_file_name, 'parents': [destination_folder_id], 'mimeType': upload_mimetype } media = MediaFileUpload(temp_file.name, mimetype=mime_type, resumable=True) drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute() print('{} placed in folder {}.'.format(new_file_name, destination_folder_name)) temp_file.close()
#!/usr/bin/env python import json import sys from docxtpl import DocxTemplate doc = DocxTemplate("order-template.docx") context = json.load(open(sys.argv[1])) doc.render(context) doc.save(sys.argv[1].replace(".json", ".docx")) #print(list(context['fields'].keys())) #print(list(context.keys()))
# -*- coding: utf-8 -*- ''' Created : 2017-09-03 @author: Eric Lapouyade ''' from docxtpl import DocxTemplate DEST_FILE = 'test_files/header_footer_image.docx' tpl=DocxTemplate('test_files/header_footer_image_tpl.docx') context = { 'mycompany' : 'The World Wide company', } tpl.replace_media('test_files/dummy_pic_for_header.png','test_files/python.png') tpl.render(context) tpl.save(DEST_FILE)
#!/usr/bin/env python from docxtpl import DocxTemplate import jinja2 import subprocess doc = DocxTemplate("invite.docx") context = { 'title' : "Lord Commander", 'name' : "John Snow" } jinja_env = jinja2.Environment() # jinja_env.filters['myfilter'] = myfilterfunc doc.render(context,jinja_env) filename = "JohnSnow.docx" doc.save(filename) #unoconv -f pdf invite.docx out = subprocess.check_output(['/usr/bin/python3', '/usr/bin/unoconv', '-f', 'pdf', 'invite.docx']) print out
from docxtpl import DocxTemplate, RichText tpl=DocxTemplate('test_files/richtext_tpl.docx') rt = RichText('an exemple of ') rt.add('a rich text', style='myrichtextstyle') rt.add(' with ') rt.add('some italic', italic=True) rt.add(' and ') rt.add('some violet', color='#ff00ff') rt.add(' and ') rt.add('some striked', strike=True) rt.add(' and ') rt.add('some small', size=14) rt.add(' or ') rt.add('big', size=60) rt.add(' text.') rt.add(' Et voilà ! ') rt.add('\n1st line') rt.add('\n2nd line') rt.add('\n3rd line') rt.add('\n\n<cool>') context = { 'example' : rt, } tpl.render(context) tpl.save('test_files/richtext.docx')
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 tpl=DocxTemplate('test_files/inline_image_tpl.docx') context = { 'myimage' : InlineImage(tpl,'test_files/python_logo.png',width=Mm(20)), 'myimageratio': InlineImage(tpl, 'test_files/python_jpeg.jpg', width=Mm(30), height=Mm(60)), 'frameworks' : [{'image' : InlineImage(tpl,'test_files/django.png',height=Mm(10)), 'desc' : 'The web framework for perfectionists with deadlines'}, {'image' : InlineImage(tpl,'test_files/zope.png',height=Mm(10)), 'desc' : 'Zope is a leading Open Source Application Server and Content Management Framework'}, {'image': InlineImage(tpl, 'test_files/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,'test_files/bottle.png',height=Mm(10)), 'desc' : 'Bottle is a fast, simple and lightweight WSGI micro web-framework for Python'}, {'image': InlineImage(tpl, 'test_files/tornado.png', height=Mm(10)), 'desc': 'Tornado is a Python web framework and asynchronous networking library.'}, ] } tpl.render(context) tpl.save('test_files/inline_image.docx')
class MianWindow(noname.MyFrame1): def __init__(self, master): super(MianWindow, self).__init__(master) self.temp_dath = None self.data_dath = None self.dir_dath = None self.desktop = os.path.join(os.path.expanduser('~'), 'Desktop') self.tempPicker.SetInitialDirectory(self.desktop) self.dataPicker.SetInitialDirectory(self.desktop) self.dirPicker.SetInitialDirectory(self.desktop) self.textShow.WriteText('Welcome to the batch Template software.'+'\n\n') self.date1 = time.strftime('%Y-%m-%d', time.localtime()) self.time1 = time.strftime('%H-%M-%S', time.localtime()) self.expired = self.loadDate() self.textShow.WriteText('Data: '+self.date1+'\n') self.textShow.WriteText('Time: '+self.time1+'\n\n') self.textShow.WriteText('The software will expire on '+self.expired+'\n\n') self.textShow.WriteText('') def loadDate(self): return '2019-04-30' def openTempFile(self, event): if self.date1 > self.expired: self.textShow.WriteText('The software has expired.\n') return self.temp_dath = self.tempPicker.GetPath() print('Trmplate File:', self.temp_dath) self.textShow.WriteText('Trmplate File:'+self.temp_dath+"\n") event.Skip() def openDataFile(self, event): if self.date1 > self.expired: self.textShow.WriteText('The software has expired.\n') return self.data_dath = self.dataPicker.GetPath() print('Data File:', self.data_dath) self.textShow.WriteText('Data File:'+self.data_dath+"\n") wookbook = xlrd.open_workbook(self.data_dath) sheet01 = wookbook.sheet_by_index(0) self.temp_list = [] if sheet01.nrows > 1: tt = [i.value for i in sheet01.row(0)] for i in range(1, sheet01.nrows): td = [i.value for i in sheet01.row(i)] self.temp_list.append({k:v for k,v in zip(tt, td)}) event.Skip() def openDataDir(self, event): if self.date1 > self.expired: self.textShow.WriteText('The software has expired.\n') return self.dir_dath = self.dirPicker.GetPath() self.textShow.WriteText('Saved Dir:'+self.dir_dath+"\n") print('Saved Dir:', self.dir_dath) event.Skip() def startButtonFunc( self, event ): if self.date1 > self.expired: self.textShow.WriteText('The software has expired.\n') return if self.temp_dath == None or len(self.temp_dath) == 0: self.textShow.WriteText('Please choice a template file.\n') return if self.data_dath == None or len(self.data_dath) == 0: self.textShow.WriteText('Please choice a data file.\n') return if self.dir_dath == None or len(self.dir_dath) == 0: self.textShow.WriteText('Please choice a destination folder.\n') return print(f'Batch Deal Start: Total {len(self.temp_list)}') listlen = len(self.temp_list) for i in range(100): if i < listlen: v = (i+1)*100/listlen v = v if 0 <= v <= 100 else 100 self.gauge.SetValue(v) self.doc = DocxTemplate(self.temp_dath) dtmp = self.temp_list[i] tname = str([i for i in dtmp.values()][0]) +'.docx' self.doc.render(dtmp) name = os.path.join(self.dir_dath, tname) print('Create File:', name) self.textShow.WriteText('Create File:'+name+"\n"); self.doc.save(name) print('Batch Deal End')
# -*- coding: utf-8 -*- ''' Created : 2015-03-12 @author: Eric Lapouyade ''' from docxtpl import DocxTemplate, RichText tpl=DocxTemplate('test_files/cellbg_tpl.docx') context = { 'alerts' : [ {'date' : '2015-03-10', 'desc' : RichText('Very critical alert',color='FF0000', bold=True), 'type' : 'CRITICAL', 'bg': 'FF0000' }, {'date' : '2015-03-11', 'desc' : RichText('Just a warning'), 'type' : 'WARNING', 'bg': 'FFDD00' }, {'date' : '2015-03-12', 'desc' : RichText('Information'), 'type' : 'INFO', 'bg': '8888FF' }, {'date' : '2015-03-13', 'desc' : RichText('Debug trace'), 'type' : 'DEBUG', 'bg': 'FF00FF' }, ], } tpl.render(context) tpl.save('test_files/cellbg.docx')
def create_source_docx_partner(self, cr, uid, ids, report, records, init_pay, context=None): # 2016-11-2 支持了图片 # 1.导入依赖,python3语法 # from . import report_helper # 2. 需要添加一个"tpl"属性获得模版对象 tempname = tempfile.mkdtemp() temp_out_file = self.generate_temp_file(tempname) doc = DocxTemplate(misc.file_open(report.template_file).name) env = api.Environment(cr, uid, context) partner = env.get('partner').search([('id', '=', context.get('partner_id'))]) simple_dict = {'partner_name': partner.name, 'from_date': context.get('from_date'), 'to_date': context.get('to_date'), 'report_line': [], 'init_pay': {}, 'final_pay': {}} if not records: if init_pay: simple_dict['init_pay'] = init_pay simple_dict['final_pay'] = init_pay doc.render({'obj': simple_dict, 'tpl': doc}, report_helper.get_env()) doc.save(temp_out_file) report_stream = '' with open(temp_out_file, 'rb') as input_stream: report_stream = input_stream.read() os.remove(temp_out_file) return report_stream, report.output_type data = DataModelProxy(records) for p_value in data: simple_dict['report_line'].append({ 'date': p_value.date, 'name': p_value.name, 'note': p_value.note, 'amount': p_value.amount, 'pay_amount': p_value.pay_amount, 'discount_money': p_value.discount_money, 'balance_amount': p_value.balance_amount }) if data: simple_dict['init_pay'] = data[0].balance_amount - data[0].amount + data[0].pay_amount - data[ 0].discount_money simple_dict['final_pay'] = data[-1].balance_amount doc.render({'obj': simple_dict, 'tpl': doc}, report_helper.get_env()) doc.save(temp_out_file) if report.output_type == 'pdf': temp_file = self.render_to_pdf(temp_out_file) else: temp_file = temp_out_file report_stream = '' with open(temp_file, 'rb') as input_stream: report_stream = input_stream.read() os.remove(temp_file) return report_stream, report.output_type
@author: Eric Lapouyade ''' from docxtpl import DocxTemplate tpl=DocxTemplate('test_files/nested_for_tpl.docx') context = { 'dishes' : [ {'name' : 'Pizza', 'ingredients' : ['bread','tomato', 'ham', 'cheese']}, {'name' : 'Hamburger', 'ingredients' : ['bread','chopped steak', 'cheese', 'sauce']}, {'name' : 'Apple pie', 'ingredients' : ['flour','apples', 'suggar', 'quince jelly']}, ], '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.save('test_files/nested_for.docx')