def print_time_sheet(self): from py3o.template import Template #import for every invoice or there is #an error about invalid magic header numbers self.time_card_name = "/tmp/time_card_" + self.name.split()[0] self.time_card_odt = self.time_card_name + ".odt" self.time_card_pdf = self.time_card_name + ".pdf" #self.tmp_timecard_file = "/tmp/" + self.document_odt t = Template("./templates/time_card_template.odt", self.time_card_odt, True) t.render( self.data ) #the self.data holds all the info to be passed to the template subprocess.call("odt2pdf " + self.time_card_odt, shell=True) p = printing.Operation(settings_file='time_card', file_to_print=self.time_card_pdf, parent=self.window) if self.print_directly == False: result = p.print_dialog() else: result = p.print_directly() f = open(self.time_card_pdf, 'rb') dat = f.read() f.close() self.cursor.execute( "UPDATE payroll.pay_stubs SET timecard_pdf = %s WHERE id = %s", (dat, self.paystubs_id))
def print_10_env_clicked(self, button): contact = Item() self.cursor.execute( "SELECT name, address, city, state, zip, phone, " "fax, email FROM contacts WHERE id = %s", (self.contact_id, )) for row in self.cursor.fetchall(): contact.name = row[0] contact.street = row[1] contact.city = row[2] contact.state = row[3] contact.zip = row[4] contact.phone = row[5] contact.fax = row[6] contact.email = row[7] company = Item() self.cursor.execute("SELECT * FROM company_info") for row in self.cursor.fetchall(): company.name = row[1] company.street = row[2] company.city = row[3] company.state = row[4] company.zip = row[5] company.country = row[6] company.phone = row[7] company.fax = row[8] company.email = row[9] company.website = row[10] data = dict(contact=contact, company=company) from py3o.template import Template env_file = "/tmp/env10_template.odt" t = Template(main.template_dir + "env10_template.odt", env_file, True) t.render(data) #the data holds all the info of the invoice subprocess.Popen("soffice --headless -p " + env_file, shell=True)
def generate_label(self): label = Item() label.aisle = self.get_object('entry5').get_text() label.cart = self.get_object('entry6').get_text() label.rack = self.get_object('entry7').get_text() label.shelf = self.get_object('entry8').get_text() label.cabinet = self.get_object('entry9').get_text() label.drawer = self.get_object('entry10').get_text() label.bin = self.get_object('entry11').get_text() self.cursor.execute( "SELECT name, description, barcode FROM products " "WHERE id = (%s)", [self.product_id]) for row in self.cursor.fetchall(): label.name = row[0] label.description = row[1] label.code128 = barcode_generator.makeCode128(row[2]) label.barcode = row[2] price = pricing.product_retail_price(self.product_id) label.price = '${:,.2f}'.format(price) data = dict(label=label) from py3o.template import Template self.label_file = "/tmp/product_label.odt" t = Template(template_dir + "/product_label_template.odt", self.label_file) t.render(data) DB.rollback()
def print_shipping_label_clicked(self, button): contact = Item() self.cursor.execute( "SELECT name, address, city, state, zip, phone, " "fax, email FROM contacts WHERE id = %s", (self.contact_id, )) for row in self.cursor.fetchall(): contact.name = row[0] contact.street = row[1] contact.city = row[2] contact.state = row[3] contact.zip = row[4] contact.phone = row[5] contact.fax = row[6] contact.email = row[7] company = Item() self.cursor.execute("SELECT * FROM company_info") for row in self.cursor.fetchall(): company.name = row[1] company.street = row[2] company.city = row[3] company.state = row[4] company.zip = row[5] company.country = row[6] company.phone = row[7] company.fax = row[8] company.email = row[9] company.website = row[10] data = dict(contact=contact, company=company) from py3o.template import Template label_file = "/tmp/contact_label_template.odt" t = Template("./templates/contact_label_template.odt", label_file, True) t.render(data) #the data holds all the info of the invoice subprocess.call("libreoffice " + label_file, shell=True)
def renderdoc(data_input, outputfile): t = Template(os.path.abspath("masterdata/bestellung_template.odt"), outputfile) t.set_image_path('staticimage.logo', os.path.abspath("masterdata/logo.png")) supplier = data_input['supplier'] responsible = Staff04.objects.get(id=data_input['responsible']) items = [] total = '%.2f' % sum(item['amount'] for item in data_input['data']) for item in data_input['data']: if item['packing'] != '': item['packing'] = 'Verpackt als: %s' % item['packing'] items.append( {'id': item['prodid'], 'name': item['name'], 'unit': item['unit'], 'quantity': '%.3f' % item['quantity'], 'price': '%.2f' % item['price'], 'amount': '%.2f' % item['amount'], 'packing': item['packing'], 'comment': item['comment']}) recipient = {'address': format_py3o_context_value( '%s\n%s\n\n%s %s' % (supplier['namea'], supplier['address'], supplier['zipcode'], supplier['city']))} sender = {'address': data_input['adr_kurz'], 'info': 'info'} # company specific info = {'kostenstelle': data_input['kostenstelle'], 'bez_kostenstelle': data_input['bez_kostenstelle'], 'id': data_input['id'], 'date': data_input['docdate'], 'bauleiter': '%s %s' % (responsible.firstname, responsible.lastname), 'bauleitertel': responsible.mobile, 'polier': '', 'lieferadresse': data_input['adr_lang'], 'infotext': format_py3o_context_value(unicode(data_input['infotext']))} data = dict(items=items, recipient=recipient, sender=sender, info=info, total=total) t.render(data)
def test_ignore_undefined_variables_1(self): template_name = pkg_resources.resource_filename( "py3o.template", "tests/templates/py3o_undefined_variables_1.odt" ) outname = get_secure_filename() template = Template(template_name, outname) data = {} error = True try: template.render(data) print( "Error: template contains variables that must be " "replaced" ) except TemplateError: error = False assert error is False template = Template( template_name, outname, ignore_undefined_variables=True ) error = False try: template.render(data) except Exception: traceback.print_exc() error = True assert error is False
def test_ignore_undefined_variables_image_injection(self): """Test ignore undefined variables for injected image""" template_name = pkg_resources.resource_filename( "py3o.template", "tests/templates/py3o_image_injection.odt" ) outname = get_secure_filename() data = {"items": [], "document": Mock(total=6)} template = Template(template_name, outname) error = True try: template.render(data) print( "Error: template contains variables that must be " "replaced" ) except TemplateError: error = False self.assertFalse(error) template = Template( template_name, outname, ignore_undefined_variables=True ) error = False try: template.render(data) except Exception: traceback.print_exc() error = True self.assertFalse(error)
def test_template_with_function_call(self): template_name = pkg_resources.resource_filename( "py3o.template", "tests/templates/py3o_template_function_call.odt" ) outname = get_secure_filename() template = Template(template_name, outname) data_dict = {"amount": 32.123} template.render(data_dict) outodt = zipfile.ZipFile(outname, "r") content_list = lxml.etree.parse( BytesIO(outodt.read(template.templated_files[0])) ) result_a = lxml.etree.tostring(content_list, pretty_print=True).decode( "utf-8" ) result_e = open( pkg_resources.resource_filename( "py3o.template", "tests/templates/template_with_function_call_result.xml", ) ).read() result_a = result_a.replace("\n", "").replace(" ", "") result_e = result_e.replace("\n", "").replace(" ", "") assert result_a == result_e
def _create_single_report(self, model_instance, data, save_in_attachment): """ This function to generate our py3o report """ self.ensure_one() result_fd, result_path = tempfile.mkstemp(suffix='.ods', prefix='p3o.report.tmp.') tmpl_data = self.get_template(model_instance) in_stream = StringIO(tmpl_data) with closing(os.fdopen(result_fd, 'w+')) as out_stream: template = Template(in_stream, out_stream, escape_false=True) localcontext = self._get_parser_context(model_instance, data) template.render(localcontext) out_stream.seek(0) tmpl_data = out_stream.read() if self.env.context.get('report_py3o_skip_conversion'): return result_path result_path = self._convert_single_report(result_path, model_instance, data) if len(model_instance) == 1: self._postprocess_report(result_path, model_instance.id, save_in_attachment) return result_path
def _renderiza_documento(self): ''' Renderiza o documento e salva o pdf do tipo de documento especificado de acordo com o template correspondente :return: ''' script_dir = os.path.dirname(__file__) template_path = os.path.join(script_dir, self.tipo_impressao + '.odt') template = open(template_path, 'rb') arq_template = tempfile.NamedTemporaryFile() arq_template.write(template.read()) arq_template.seek(os.SEEK_SET) template.close() arq_odt = tempfile.NamedTemporaryFile(suffix=".odt") t = Template(arq_template.name, arq_odt.name) t.render({'danfe': self}) lo = sh.libreoffice('--headless', '--invisible', '--convert-to', 'pdf', '--outdir', tempfile.gettempdir(), arq_odt.name, _bg=True) lo.wait() arq_pdf = arq_odt.name[:-3] + 'pdf' self.pdf = open(arq_pdf, 'rb').read() arq_template.close() arq_odt.close()
def compile_template(instance, template, additionnal_context=None): """ Fill the given template with the instance's datas and return the odt file For every instance class, common values are also inserted in the context dict (and so can be used) : * config values :param obj instance: the instance of a model (like Userdatas, Company) :param template: the template object to use :param dict additionnal_context: A dict containing datas we'd like to add to the py3o compilation template :return: a stringIO object filled with the resulting odt's informations """ py3o_context = get_compilation_context(instance) if additionnal_context is not None: py3o_context.update(additionnal_context) output_doc = BytesIO() odt_builder = Template(template, output_doc) odt_builder.render(py3o_context) return output_doc
def test_link_validation_missing_equal(self): """test a missing equal sign in a link raises a template error""" template_name = pkg_resources.resource_filename( "py3o.template", "tests/templates/py3o_missing_eq_in_link.odt" ) outname = get_secure_filename() template = Template(template_name, outname) class Item(object): def __init__(self, val): self.val = val data_dict = {"items": [Item(1), Item(2), Item(3), Item(4)]} template.set_image_path( "staticimage.logo", pkg_resources.resource_filename( "py3o.template", "tests/templates/images/new_logo.png" ), ) except_occured = False error_text = "" try: template.render(data_dict) except TemplateException as e: except_occured = True error_text = "{}".format(e) assert except_occured is True assert error_text == ( "Missing '=' in instruction 'for \"item in items\"'" )
def gera_pdf_boletos(lista_boletos, template_boleto=None): if template_boleto is None: boleto = lista_boletos[0] if boleto.template_boleto is not None: if isinstance(boleto.template_boleto, basestring): template_boleto = BytesIO().write( open(boleto.arquivo_template_boleto, 'rb').read()) else: template_boleto = boleto.template_boleto else: template_boleto = boleto.banco.template_boleto arquivo_renderizado = tempfile.NamedTemporaryFile(delete=False) arquivo_pdf = arquivo_renderizado.name + '.pdf' template = Template(template_boleto, arquivo_renderizado.name) template.render({'boletos': lista_boletos}) sh.libreoffice('--headless', '--invisible', '--convert-to', 'pdf', '--outdir', '/tmp', arquivo_renderizado.name) pdf = open(arquivo_pdf, 'rb').read() os.remove(arquivo_pdf) os.remove(arquivo_renderizado.name) return pdf
def populate_template_clicked(self, button): from py3o.template import Template product_list = dict() self.cursor.execute("SELECT " "'name'||p.barcode, p.name, " "'price'||p.barcode, price::money " "FROM products AS p " "JOIN products_markup_prices AS pmp " "ON pmp.product_id = p.id " "JOIN customer_markup_percent AS cmp " "ON cmp.id = pmp.markup_id " "WHERE (p.catalog, cmp.standard) = (True, True)") for row in self.cursor.fetchall(): name_id = row[0] name = row[1] price_id = row[2] price = row[3] product_list[name_id] = name product_list[price_id] = price catalog_file = "/tmp/catalog.odt" t = Template(main.template_dir + "/catalog_template.odt", catalog_file, False) try: t.render( product_list) #the product_list holds all the catalog info except Exception as e: print(e) dialog = Gtk.MessageDialog(self.window, 0, Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE, e) dialog.run() dialog.destroy() return subprocess.Popen(["soffice", catalog_file])
def test_remove_soft_breaks_without_tail(self): template_xml = pkg_resources.resource_filename( 'py3o.template', 'tests/templates/py3o_page_break_without_tail.odt') t = Template(template_xml, get_secure_filename()) soft_breaks = get_soft_breaks(t.content_trees[0], t.namespaces) assert len(soft_breaks) > 0 t.remove_soft_breaks() soft_breaks = get_soft_breaks(t.content_trees[0], t.namespaces) assert len(soft_breaks) == 0 t = Template(template_xml, get_secure_filename()) soft_breaks = get_soft_breaks(t.content_trees[0], t.namespaces) assert len(soft_breaks) > 0 t.render( data={ "items": [ { 'Amount': 3, 'Currency': 'D' }, { 'Amount': 2, 'Currency': 'E' }, { 'Amount': 1, 'Currency': 'C' }, ] }) soft_breaks = get_soft_breaks(t.content_trees[0], t.namespaces) assert len(soft_breaks) == 0
def test_input_fields_with_function(self): template_name = pkg_resources.resource_filename( 'py3o.template', 'tests/templates/py3o_template_input_fields_for_function.odt') outname = get_secure_filename() template = Template(template_name, outname) data_dict = { 'datestring': '2017-10-02', } template.render(data_dict) outodt = zipfile.ZipFile(outname, 'r') content_list = lxml.etree.parse( BytesIO(outodt.read(template.templated_files[0]))) result_a = lxml.etree.tostring( content_list, pretty_print=True, ).decode('utf-8') result_e = open( pkg_resources.resource_filename( 'py3o.template', 'tests/templates/input_fields_function_result.xml')).read() result_a = result_a.replace("\n", "").replace(" ", "") result_e = result_e.replace("\n", "").replace(" ", "") assert result_a == result_e
def test_ignore_undefined_variables_logo(self): template_name = pkg_resources.resource_filename( 'py3o.template', 'tests/templates/py3o_logo.odt') outname = get_secure_filename() template = Template(template_name, outname) data = {} error = True try: template.render(data) print("Error: template contains a logo variable that must be " "replaced") except ValueError: error = False assert error is False template = Template(template_name, outname, ignore_undefined_variables=True) error = False try: template.render(data) except: traceback.print_exc() error = True assert error is False
def test_missing_opening(self): """test orphaned /for raises a TemplateException""" template_name = pkg_resources.resource_filename( 'py3o.template', 'tests/templates/py3o_missing_open_template.odt') outname = get_secure_filename() try: template = Template(template_name, outname) finally: os.remove(outname) class Item(object): def __init__(self, val): self.val = val data_dict = {"items": [Item(1), Item(2), Item(3), Item(4)]} template.set_image_path( 'staticimage.logo', pkg_resources.resource_filename( 'py3o.template', 'tests/templates/images/new_logo.png')) # this will raise a TemplateException... or the test will fail error_occured = False try: template.render(data_dict) except TemplateException as e: error_occured = True # make sure this is the correct TemplateException that pops assert e.message == "No open instruction for /for" # and make sure we raised assert error_occured is True
def test_variable_type_checking(self): template_name = pkg_resources.resource_filename( 'py3o.template', 'tests/templates/py3o_ods_variable_type.ods') outname = get_secure_filename() template = Template(template_name, outname) data_dict = { 'items': [ Mock(val1=10, val2='toto'), Mock(val1=50.12, val2='titi'), ] } template.render(data_dict) outodt = zipfile.ZipFile(outname, 'r') content_list = lxml.etree.parse( BytesIO(outodt.read(template.templated_files[0]))) result_a = lxml.etree.tostring( content_list, pretty_print=True, ).decode('utf-8') result_e = open( pkg_resources.resource_filename( 'py3o.template', 'tests/templates/py3o_ods_variable_type_result.xml')).read() result_a = result_a.replace("\n", "").replace(" ", "") result_e = result_e.replace("\n", "").replace(" ", "") assert result_a == result_e
def test_input_fields_with_control(self): template_name = pkg_resources.resource_filename( "py3o.template", "tests/templates/py3o_template_for_loop_input_field.odt", ) outname = get_secure_filename() template = Template(template_name, outname) data_dict = {"items": ["one", "two", "three"]} template.render(data_dict) outodt = zipfile.ZipFile(outname, "r") content_list = lxml.etree.parse( BytesIO(outodt.read(template.templated_files[0])) ) result_a = lxml.etree.tostring(content_list, pretty_print=True).decode( "utf-8" ) result_e = open( pkg_resources.resource_filename( "py3o.template", "tests/templates/input_fields_for_loop_result.xml", ) ).read() result_a = result_a.replace("\n", "").replace(" ", "") result_e = result_e.replace("\n", "").replace(" ", "") assert result_a == result_e
def test_remove_soft_breaks_without_tail(self): template_xml = pkg_resources.resource_filename( "py3o.template", "tests/templates/py3o_page_break_without_tail.odt" ) t = Template(template_xml, get_secure_filename()) soft_breaks = get_soft_breaks(t.content_trees[0], t.namespaces) assert len(soft_breaks) > 0 t.remove_soft_breaks() soft_breaks = get_soft_breaks(t.content_trees[0], t.namespaces) assert len(soft_breaks) == 0 t = Template(template_xml, get_secure_filename()) soft_breaks = get_soft_breaks(t.content_trees[0], t.namespaces) assert len(soft_breaks) > 0 t.render( data={ "items": [ {"Amount": 3, "Currency": "D"}, {"Amount": 2, "Currency": "E"}, {"Amount": 1, "Currency": "C"}, ] } ) soft_breaks = get_soft_breaks(t.content_trees[0], t.namespaces) assert len(soft_breaks) == 0
def print_dialog(self, window): from py3o.template import Template purchase_order_file = "/tmp/" + self.document_odt t = Template(main.template_dir+"/document_template.odt", purchase_order_file , True) t.render(self.data) #the self.data holds all the info of the purchase_order subprocess.call("odt2pdf " + purchase_order_file, shell = True) p = printing.Setup("/tmp/" + self.document_pdf, "document") p.print_dialog (window)
def view(self): from py3o.template import Template purchase_order_file = "/tmp/" + self.document_odt t = Template(main.template_dir + "/purchase_order_template.odt", purchase_order_file, True) t.render( self.data) #the self.data holds all the info of the purchase_order subprocess.Popen("libreoffice " + purchase_order_file, shell=True)
def print_directly(self): from py3o.template import Template #import for every purchase order or there is an error about invalid magic header numbers purchase_order_file = "/tmp/" + self.document_odt t = Template(template_dir+"/document_template.odt", purchase_order_file , True) t.render(self.data) subprocess.Popen("libreoffice --nologo --headless -p " + purchase_order_file, shell = True) subprocess.call("odt2pdf " + purchase_order_file, shell = True) self.store = []
def _create_single_report(self, model_instance, data, save_in_attachment): """ This function to generate our py3o report """ self.ensure_one() report_xml = self.ir_actions_report_xml_id filetype = report_xml.py3o_filetype result_fd, result_path = tempfile.mkstemp( suffix='.' + filetype, prefix='p3o.report.tmp.') tmpl_data = self.get_template(model_instance) in_stream = StringIO(tmpl_data) with closing(os.fdopen(result_fd, 'w+')) as out_stream: template = Template(in_stream, out_stream, escape_false=True) localcontext = self._get_parser_context(model_instance, data) is_native = Formats().get_format(filetype).native if report_xml.py3o_is_local_fusion: template.render(localcontext) out_stream.seek(0) tmpl_data = out_stream.read() datadict = {} else: expressions = template.get_all_user_python_expression() py_expression = template.convert_py3o_to_python_ast( expressions) convertor = Py3oConvertor() data_struct = convertor(py_expression) datadict = data_struct.render(localcontext) # if not is_native or not report_xml.py3o_is_local_fusion: # # Call py3o.server to render the template in the desired format # files = { # 'tmpl_file': tmpl_data, # } # fields = { # "targetformat": filetype, # "datadict": json.dumps(datadict), # "image_mapping": "{}", # "escape_false": "on", # } # if report_xml.py3o_is_local_fusion: # fields['skipfusion'] = '1' # r = requests.post( # report_xml.py3o_server_id.url, data=fields, files=files) # if r.status_code != 200: # # server says we have an issue... let's tell that to enduser # raise UserError( # _('Fusion server error %s') % r.text, # ) # chunk_size = 1024 # with open(result_path, 'w+') as fd: # for chunk in r.iter_content(chunk_size): # fd.write(chunk) if len(model_instance) == 1: self._postprocess_report( result_path, model_instance.id, save_in_attachment) return result_path
def test_remove_soft_page_breaks(self): template_xml = pkg_resources.resource_filename( "py3o.template", "tests/templates/py3o_soft_page_break.odt" ) outname = get_secure_filename() template = Template(template_xml, outname) soft_breaks = get_soft_breaks( template.content_trees[0], template.namespaces ) self.assertEqual(len(soft_breaks), 2) template.remove_soft_breaks() soft_breaks = get_soft_breaks( template.content_trees[0], template.namespaces ) self.assertEqual(len(soft_breaks), 0) template = Template(template_xml, outname) soft_breaks = get_soft_breaks( template.content_trees[0], template.namespaces ) self.assertEqual(len(soft_breaks), 2) template.render(data={"list1": [1, 2, 3]}) soft_breaks = get_soft_breaks( template.content_trees[0], template.namespaces ) self.assertEqual(len(soft_breaks), 0) outodt = zipfile.ZipFile(outname, "r") content_list = lxml.etree.parse( BytesIO(outodt.read(template.templated_files[0])) ) nmspc = template.namespaces paragraphs = content_list.findall("//text:p", nmspc) bottom_break_paragraphs, middle_break_paragraphs = 0, 0 for p in paragraphs: if not p.text: continue text = p.text.strip() if text == ( u"This is a text with a margin at the bottom and a " u"soft-page-break" ): bottom_break_paragraphs += 1 elif text == ( u"This is a paragraph that is cut in half by a " u"soft-page-break. This text should not remain cut " u"in half after rendering." ): middle_break_paragraphs += 1 else: self.fail(u"Unidentified text in result: {}".format(text)) self.assertEqual(bottom_break_paragraphs, 3) self.assertEqual(middle_break_paragraphs, 3)
def render_template(): finder = config['pylons.app_globals'].dotted_filename_finder odt_template_file = finder.get_dotted_filename( template_name=template_name, template_extension=".odt") output = NamedTemporaryFile() t = Template(odt_template_file, output.name) t.render(dict(document=template_vars)) return output.read()
def print_serial_number(self, serial_number): document = Item() document.serial_number = serial_number data = dict(label = document) from py3o.template import Template sn_file = "/tmp/job_serial.odt" t = Template(template_dir+"/job_serial_template.odt", sn_file, True) t.render(data) subprocess.Popen(["soffice", sn_file])
def view_report(self): self.cursor.execute("SELECT * FROM contacts WHERE id = (%s)", [self.employee_id]) customer = Item() for row in self.cursor.fetchall(): self.customer_id = row[0] customer.name = row[1] name = row[1] customer.ext_name = row[2] customer.street = row[3] customer.city = row[4] customer.state = row[5] customer.zip = row[6] customer.fax = row[7] customer.phone = row[8] customer.email = row[9] company = Item() self.cursor.execute("SELECT * FROM company_info") for row in self.cursor.fetchall(): company.name = row[1] company.street = row[2] company.city = row[3] company.state = row[4] company.zip = row[5] company.country = row[6] company.phone = row[7] company.fax = row[8] company.email = row[9] company.website = row[10] company.tax_number = row[11] actual_hours = self.actual_seconds / 3600 adjusted_hours = self.adjusted_seconds / 3600 cost_sharing_hours = self.cost_sharing_seconds / 3600 profit_sharing_hours = self.profit_sharing_seconds / 3600 time = Item() time.actual = round(actual_hours, 2) time.adjusted = round(adjusted_hours, 2) time.cost_sharing = round(cost_sharing_hours, 2) time.profit_sharing = round(profit_sharing_hours, 2) time.efficiency = round(self.efficiency, 2) payment = Item() time.payment_due = '${:,.2f}'.format(self.payment) wage = self.builder.get_object('spinbutton1').get_value() time.wage = '${:,.2f}'.format(wage) self.data = dict(contact=customer, time=time, company=company, payment=payment) from py3o.template import Template #import for every use or there is an error about invalid magic header numbers self.time_file = "/tmp/employee_time.odt" self.time_file_pdf = "/tmp/employee_time.pdf" t = Template(main.template_dir + "/employee_time.odt", self.time_file, True) t.render(self.data) #the self.data holds all the info of the invoice subprocess.call('soffice ' + self.time_file, shell=True)
def test_escape_false_template(self): template_name = pkg_resources.resource_filename( "py3o.template", "tests/templates/test_false_value.odt" ) outname = get_secure_filename() template = Template(template_name, outname) template.render({"false_value": False}) outodt = zipfile.ZipFile(outname, "r") content_list = lxml.etree.parse( BytesIO(outodt.read(template.templated_files[0])) ) result_a = lxml.etree.tostring(content_list, pretty_print=True).decode( "utf-8" ) result_e = open( pkg_resources.resource_filename( "py3o.template", "tests/templates/template_test_false_value_result.xml", ) ).read() result_a = result_a.replace("\n", "").replace(" ", "") result_e = result_e.replace("\n", "").replace(" ", "") self.assertEqual(result_a, result_e) outname = get_secure_filename() template = Template(template_name, outname, escape_false=True) template.render({"false_value": False}) outodt = zipfile.ZipFile(outname, "r") content_list = lxml.etree.parse( BytesIO(outodt.read(template.templated_files[0])) ) result_a = lxml.etree.tostring(content_list, pretty_print=True).decode( "utf-8" ) result_e = open( pkg_resources.resource_filename( "py3o.template", "tests/templates/template_test_escape_false_value_result.xml", ) ).read() result_a = result_a.replace("\n", "").replace(" ", "") result_e = result_e.replace("\n", "").replace(" ", "") self.assertEqual(result_a, result_e)
def print_directly(self): from py3o.template import Template purchase_order_file = "/tmp/" + self.document_odt t = Template(main.template_dir + "/purchase_order_template.odt", purchase_order_file, True) t.render(self.data) subprocess.call("odt2pdf " + purchase_order_file, shell=True) p = printing.Setup("/tmp/" + self.document_pdf, 'purchase_order') p.print_direct(window) self.store = []
def print_dialog(self, window): from py3o.template import Template purchase_order_file = "/tmp/" + self.document_odt t = Template(template_dir+"/document_template.odt", purchase_order_file , True) t.render(self.data) #the self.data holds all the info of the purchase_order subprocess.call("odt2pdf " + purchase_order_file, shell = True) p = printing.Operation(settings_file = "document") p.set_parent(window) p.set_file_to_print ("/tmp/" + self.document_pdf) p.print_dialog ()
def renderdoc1(data_input, outputfile): t = Template(os.path.abspath("masterdata/lagerausgang_template.odt"), outputfile) t.set_image_path('staticimage.logo', os.path.abspath("masterdata/logo_sofico.png")) #responsible = Staff01.objects.get(id=data_input['responsible']) items = [] #total = '%.2f' % sum(item['amount'] for item in data_input['data']) for item in data_input['data']: packing = item['packing'] if item['packing'] else '' comment = item['comment'] if item['comment'] else '' items.append( {'id': item['prodid'], 'name': item['name'], 'unit': item['unit'], 'quantity': '%.3f' % item['quantity'], 'price': '%.2f' % item['price'], 'packing': packing, 'comment': comment}) # company specific info = {'kostenstelle': data_input['modulerefid'], 'stock': data_input["stockid"], 'bez_kostenstelle': data_input['subject'], 'id':data_input['id'], 'date': data_input['docdate'], 'recipient':'%s'%(data_input['responsible']), 'polier': data_input['leader'], 'abholer': data_input['abholer']} data = dict(items=items, info=info) t.render(data)
def render(data): t = Template(TEMPLATE, OUTPUT) t.render(data)
def create(self, cr, uid, ids, data, context=None): # Find the report definition to get its settings. pool = pooler.get_pool(cr.dbname) report_xml_obj = pool.get('ir.actions.report.xml') report_xml_ids = report_xml_obj.search( cr, uid, [('report_name', '=', self.name[7:])], # Ignore "report." context=context, ) if not report_xml_ids: return super(py3o_report, self).create(cr, uid, ids, data, context=context) report_xml = report_xml_obj.browse(cr, uid, report_xml_ids[0], context=context) tmpl_def = report_xml.py3o_template_id filetype = report_xml.py3o_fusion_filetype # py3o.template operates on filenames so create temporary files. with NamedTemporaryFile( suffix='.odt', prefix='py3o-template-' ) as in_temp, NamedTemporaryFile( suffix='.odt', prefix='py3o-report-' ) as out_temp: in_temp.write(b64decode(tmpl_def.py3o_template_data)) in_temp.flush() in_temp.seek(0) datadict = self.get_values(cr, uid, ids, data, context) template = Template(in_temp.name, out_temp.name) template.render(datadict) out_temp.seek(0) # TODO: use py3o.formats to know native formats instead # of hardcoding this value # TODO: why use the human readable form when you're a machine? # this is non-sense AND dangerous... please use technical name if filetype.human_ext != 'odt': # Now we ask fusion server to convert our template fusion_server_obj = pool.get('py3o.server') fusion_server_id = fusion_server_obj.search( cr, uid, [], context=context )[0] fusion_server = fusion_server_obj.browse( cr, uid, fusion_server_id, context=context ) files = { 'tmpl_file': out_temp, } fields = { "targetformat": filetype.fusion_ext, "datadict": "{}", "image_mapping": "{}", "skipfusion": True, } # Here is a little joke about Odoo # we do nice chunked reading from the network... r = requests.post(fusion_server.url, data=fields, files=files) if r.status_code == 400: # server says we have an issue... let's tell that to enduser raise osv.except_osv( _('Fusion server error'), r.json(), ) else: chunk_size = 1024 with NamedTemporaryFile( suffix=filetype.human_ext, prefix='py3o-template-' ) as fd: for chunk in r.iter_content(chunk_size): fd.write(chunk) fd.seek(0) # ... but odoo wants the whole data in memory anyways :) return fd.read(), filetype.human_ext return out_temp.read(), 'odt'
class Item(object): pass items = list() item1 = Item() item1.val1 = 'Item1 Value1' item1.val2 = 'Item1 Value2' item1.val3 = 'Item1 Value3' item1.Currency = 'EUR' item1.Amount = '12,345.35' item1.InvoiceRef = '#1234' items.append(item1) for i in xrange(1000): item = Item() item.val1 = 'Item%s Value1' % i item.val2 = 'Item%s Value2' % i item.val3 = 'Item%s Value3' % i item.Currency = 'EUR' item.Amount = '6,666.77' item.InvoiceRef = 'Reference #%04d' % i items.append(item) document = Item() document.total = '9,999,999,999,999.999' data = dict(items=items, document=document) t.render(data)
def gerar_danfce(self): if self.NFe is None: raise ValueError('Não é possível gerar um DANFCE sem a informação de uma NFC-e') if self.protNFe is None: self.protNFe = ProtNFe_310() if self.procEventoCancNFe is None: self.procEventoCancNFe = ProcEventoCancNFe_100() # # Prepara o queryset para impressão # self.NFe.monta_chave() self.NFe.monta_qrcode() self.NFe.site = self.site # Emissão para simples conferência / sem protocolo de autorização self.mensagem_protocolo = '' self.mensagem_sem_valor = '' if (not self.protNFe.infProt.nProt.valor) or self.NFe.infNFe.ide.tpAmb.valor == 2: self.mensagem_sem_valor = u'Sem valor fiscal' # NF-e denegada if self.protNFe.infProt.cStat.valor in ('110', '301', '302'): self.mensagem_protocolo = u'Protocolo de Denegação ' self.mensagem_protocolo += self.protNFe.protocolo_formatado # Emissão normal elif self.protNFe.infProt.nProt.valor: self.mensagem_protocolo = u'Protocolo de Autorização ' self.mensagem_protocolo += self.protNFe.protocolo_formatado # A NF-e foi cancelada por um evento de cancelamento, , no DANFCE imprimir o "carimbo" de cancelamento self.mensagem_cancelamento = '' self.motivo_cancelamento = '' if self.procEventoCancNFe.retEvento.infEvento.nProt.valor: self.mensagem_cancelamento = self.procEventoCancNFe.retEvento.protocolo_formatado self.motivo_cancelamento = self.procEventoCancNFe.evento.infEvento.detEvento.xJust.valor ## ## Observação de impressão ## #if self.nome_sistema: #self.obs_impressao = self.nome_sistema + ' - ' + self.obs_impressao #else: #self.obs_impressao = self.obs_impressao if self.template: if isinstance(self.template, file): template = self.template else: template = open(self.template) else: template = open(os.path.join(DIRNAME, 'danfce_a4.odt')) self.caminho_temporario = self.caminho_temporario or '/tmp/' nome_arq_template = self.caminho_temporario + uuid4().hex open(nome_arq_template, 'w').write(template.read()) template.close() nome_arq_temp = uuid4().hex nome_arq_odt = self.caminho_temporario + nome_arq_temp + '.odt' nome_arq_pdf = self.caminho_temporario + nome_arq_temp + '.pdf' t = Template(nome_arq_template, nome_arq_odt) t.render({'danfce': self}) print(sh.libreoffice('--headless', '--invisible', '--convert-to', 'pdf', '--outdir', '/tmp', nome_arq_odt)) self.conteudo_pdf = open(nome_arq_pdf, 'r').read() os.remove(nome_arq_template) os.remove(nome_arq_odt) os.remove(nome_arq_pdf) if self.salvar_arquivo: nome_arq = self.caminho + self.NFe.chave + '.pdf' open(nome_arq, 'w').write(self.conteudo_pdf)