def resumido(self, data0, data1, subtotal0,tax0,total0, fechai0,fechaf0): global data, subtotal,tax,total, fechai,fechaf data = data0 dataD = data1 subtotal = subtotal0 tax = tax0 total = total0 fechai = fechai0 fechaf = fechaf0 date = time.localtime()[:6] for i in data: totales[0] = totales[0]+i[5] totales[1] = totales[1]+i[2] totales[2] = totales[2]+(i[2]-i[5]) totales[3] = totales[3]+(i[3]*i[5]) totales[4] = totales[4]+(i[3]*(i[2]-i[5])) totales[5] = totales[5]+(i[3]*i[2]) f_name = "Ventas_%d-%d-%d-%d-%d-%d.ods" % date renderer = Renderer(self.ResourcePath('reports/templates/ventas.ods'), globals(), self.ResourcePath('reports/sales/'+f_name)) renderer.run() path = self.ResourcePath('reports/sales/'+f_name) if sys.platform.startswith("linux"): os.system("libreoffice "+path) else: import subprocess p = subprocess.Popen(path, shell=True, bufsize=255, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
def __call__(self): self.request.response.setHeader('Content-type', 'application/pdf') self.request.response.setHeader('Content-disposition', 'inline;filename="' + removeSecurityProxy(self.report.report_type) + "_" + removeSecurityProxy(self.report.start_date).strftime('%Y-%m-%d') + '.pdf"') session = Session() report = session.query(domain.Report).get(self.report.report_id) d = dict([(f.file_title, f.file_data) for f in report.attached_files]) if "pdf" not in d.keys(): params = {} params['body_text'] = self.cleanupText() openofficepath = getUtility(IOpenOfficeConfig).getPath() renderer = Renderer(self.odt_file, params, self.tempFileName, pythonWithUnoPath=openofficepath) renderer.run() f = open(self.tempFileName, 'rb') doc = f.read() f.close() os.remove(self.tempFileName) attached_file = domain.AttachedFile() attached_file.file_title = "pdf" attached_file.file_data = doc attached_file.language = report.language report.attached_files.append(attached_file) notify(ObjectCreatedEvent(attached_file)) session.add(report) session.commit() return doc else: return d["pdf"].__str__()
def protocolo_imprimir(request, idot): #ruta de la plantilla plantilla_odt_path = os.path.join(labutiles.PLANTILLA_ODT_PATH, 'protocolo_impresion.odt') #Necesito un nombre aleatorio en la carpeta de temporales file_odt_resultado = tempfile.NamedTemporaryFile(delete=True, prefix='proto_', suffix='.odt') odt_resultado_path = file_odt_resultado.name #path al archivo de resultado file_odt_resultado.close() #Se debería eliminar el archivo plantilla = protocolo_impresion.protocoloimpresion(idot) contexto = {"plantilla": plantilla} renderer = Renderer(plantilla_odt_path, contexto, odt_resultado_path) renderer.run() archivo_resultado = File(open(odt_resultado_path)) wrapper = FileWrapper(archivo_resultado) response = HttpResponse(wrapper, content_type='text/html') response[ 'Content-Disposition'] = 'attachment; filename=%s' % os.path.basename( odt_resultado_path) response['Content-Length'] = os.path.getsize(odt_resultado_path) return response
def presupuesto_impresion_odt_full(request, idpresupuesto): #ruta de la plantilla plantilla_odt_path = os.path.join(labutiles.PLANTILLA_ODT_PATH,'presupuesto_impresion_odt_full.odt') #Necesito un nombre aleatorio en la carpeta de temporales file_odt_resultado = tempfile.NamedTemporaryFile(delete=True,prefix='lab_', suffix='.odt') odt_resultado_path = file_odt_resultado.name #path al archivo de resultado file_odt_resultado.close() #Se debería eliminar el archivo #print 'origen>>' + str(plantilla_odt_path) #print 'destino>>'+ str(file_odt_resultado) dummy = presupuesto_impresion_odt.impresion(idpresupuesto) contexto = {"dummy":dummy} renderer = Renderer(plantilla_odt_path, contexto, odt_resultado_path) #estilos = renderer.getStyles() #Para consultar los estilos en la plantilla del documento #print estilos renderer.run() archivo_resultado = File(open(odt_resultado_path)) wrapper = FileWrapper(archivo_resultado) response = HttpResponse(wrapper, content_type='text/html') response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(odt_resultado_path) response['Content-Length'] = os.path.getsize(odt_resultado_path) return response
def __call__(self): self.request.response.setHeader("Content-type", "application/vnd.oasis.opendocument.text") self.request.response.setHeader("Content-disposition", 'inline;filename="' + removeSecurityProxy(self.report.report_type) + "_" + removeSecurityProxy(self.report.start_date).strftime("%Y-%m-%d") + '.odt"') session = Session() report = session.query(domain.Report).get(self.report.report_id) d = dict([(f.file_title, f.file_data) for f in report.attached_files]) if "odt" not in d.keys(): params = {} params["body_text"] = self.cleanupText() renderer = Renderer(self.odt_file, params, self.tempFileName) renderer.run() f = open(self.tempFileName, "rb") doc = f.read() f.close() os.remove(self.tempFileName) attached_file = domain.AttachedFile() attached_file.file_title = "odt" attached_file.file_data = doc attached_file.language = report.language report.attached_files.append(attached_file) notify(ObjectCreatedEvent(attached_file)) session.add(report) session.commit() return doc else: return d["odt"].__str__()
def createReport( self, inf_basicas_dic, num_proposicao, nom_arquivo, des_tipo_materia, num_ident_basica, ano_ident_basica, txt_ementa, materia_vinculada, dat_apresentacao, nom_autor, apelido_autor, modelo_proposicao, ): # Criacao ODT url = self.sapl_documentos.modelo.materia.absolute_url() + "/%s" % modelo_proposicao template_file = cStringIO.StringIO(urllib.urlopen(url).read()) output_file_odt = "%s" % nom_arquivo renderer = Renderer(template_file, locals(), output_file_odt, pythonWithUnoPath="/usr/bin/python", forceOoCall=True) renderer.run() data = open(output_file_odt, "rb").read() for file in [output_file_odt]: os.unlink(file) self.sapl_documentos.materia_odt.manage_addFile(id=nom_arquivo, file=data)
def _generate_facture(g, ncf, with_logo=True): cursor = g.db.cursor() commande = pg.select1r(cursor, 'commande', where={'no_commande_facture':ncf}) client = pg.select1r(cursor, 'client', where={'no_client': commande['no_client']}) doc_values = {'elems': []} doc_values.update(commande) doc_values.update(client) doc_values['representant_nom'] = pg.select1(cursor, 'representant', 'representant_nom', where={'representant_id': client['representant_id']}) rows = pg.select(cursor, {'produit':'p', 'commande_item':'ci', 'producteur':'r', 'inventaire':'i'}, join={'p.no_produit_interne':'ci.no_produit_interne', 'p.no_producteur':'r.no_producteur', 'ci.no_produit_saq':'i.no_produit_saq'}, where={'ci.no_commande_facture': ncf, 'statut_item': 'OK'}, order_by='type_vin') for row in rows: doc_values['elems'].append([row['quantite_bouteille'], row['type_vin'], row['nom_domaine'], row['millesime'], row['no_produit_saq'], row['format'], as_currency(row['montant_commission']), as_currency(row['montant_commission'] * row['quantite_bouteille'])]) for f in ['sous_total', 'tps', 'tvq', 'montant']: doc_values[f] = as_currency(doc_values[f]) out_fn = '/tmp/vinum_facture_%s.%s' % (ncf, 'odt' if hasattr(app, 'is_dev') else 'pdf') tmpl_fn = 'facture.odt' if with_logo else 'facture_sans_logo.odt' ren = Renderer('/home/christian/vinum/docs/%s' % tmpl_fn, doc_values, out_fn, overwriteExisting=True) ren.run() return out_fn
def generate_price(self, folder): res_path=path.join(folder, self.get_price_name()) context=self.get_template_context() if platform.system() == 'Linux': template=settings.PROJECT_PATH+self.template_file.url file_name=ntpath.basename(template) file_path=os.path.dirname(os.path.abspath(template)) styles = '' fonts = '' images = [] chunks_dict = {} for whole_chunk in Chunk.objects.all(): res_chanks=whole_chunk.langchunk_set.filter(language=self.language, site=self.site) if len(res_chanks) == 0: res_chanks=whole_chunk.langchunk_set.filter(language='default', site=self.site) if len(res_chanks) !=0: chunk = res_chanks[0] styles += self.replace_style_names(chunk.styles, whole_chunk.slug) fonts += chunk.fonts if chunk.image: images.append(url_to_path(chunk.image.url)) chunk_with_no_blank = chunk.content.replace(' ','').replace('\n','').replace('\r','') chunks_dict[whole_chunk.slug] = self.replace_style_names(chunk_with_no_blank, whole_chunk.slug) res_templ, path_to_temp = self.add_info_to_odt(file_name, file_path, chunks_dict, styles, fonts, images) renderer = Renderer(res_templ, context, res_path, overwriteExisting=True, pythonWithUnoPath="/usr/bin/python3") renderer.run() shutil.rmtree(path_to_temp, ignore_errors=False) pages=Page.objects.filter(reverse_id=self.price.price_page, published=True) for page in pages: page.last_publish_date=datetime.now() page._publisher_keep_state = True page.save()
def render_template(): # we are expecting a json payload payload = request.get_json() if not payload: abort(400, "No JSON content found") try: context = payload["context"] except KeyError: abort(400, "No context, no document!") suffix = payload.get("format", "pdf") template = _fetch_template(**payload['template']) fd, target = tempfile.mkstemp(suffix=".{}".format(suffix)) os.close(fd) os.remove(target) try: # FIXME: we are not cleaning up our target documents, are we? r = Renderer(template, context, target, pythonWithUnoPath=UNOPYTHON, forceOoCall=True, overwriteExisting=True) r.run() return send_file(target, as_attachment=True) finally: try: os.remove(target) except: pass
def test_01(self): if V(version.short) < V('0.9.0'): # "not supported with appy version %s" % version.short) return tpl = join(MYDIR, 'appy', 'template.odt') context = dict() context.update( appy_version=version.verbose, python_version=sys.version, platform=sys.platform, ) target = join(tempfile.gettempdir(), 'result.odt') if exists(target): os.remove(target) renderer = Renderer(tpl, context, target, **PARAMS) try: renderer.run() self.fail("appy renderer failed to raise an error.") except Exception as e: s = str(e) if not s.startswith('Error while evaluating expression "foo".'): self.fail("Incorrect appy error message.") if not s.endswith("name 'foo' is not defined"): self.fail("Incorrect appy error message.")
def main(): template = os.path.join(dirname, 'testreport.odt') output = os.path.join(dirname, 'testreport-%s.pdf' % time.time()) context = {'timestr': time.ctime()} print 'Rendering %s -> %s with %s' % (template, output, context) renderer = Renderer(template, context, output) renderer.run()
def download_invitationletter(self): if not self.get_review_state() in ('accepted', 'confirmed'): return "Error: paper not accepted?" from appy.pod.renderer import Renderer values = { 'title': self.title.strip(), 'name': ','.join(self.Creators()) } pdfoutput = os.path.join(self._tempd, "TODOx.pdf") templatename = os.path.join("/tmp", "Letter.odt") renderer = Renderer(templatename, values, pdfoutput, pythonWithUnoPath='/usr/bin/python3') renderer.run() pdffile = open(pdfoutput, "rb") output = StringIO() output.write(pdffile.read()) ### TODO del file pdffile.close() output.seek(0) return output
def pod_save(filename, ext, data, template, get_tmp_file=False): import time # strip comma's from filename filename = filename.replace(",", "") file_name = tempfile.gettempdir() + "/appy" + str(time.time()) + ext renderer = Renderer(template, data, file_name) renderer.run() if ext == ".doc": content = "application/msword" elif ext == ".docx": content = "application/vnd.openxmlformats-officedocument.wordprocessingml.document" elif ext == ".pdf": content = "application/pdf" elif ext == ".rtf": content = "application/rtf" else: # odt, prefered content = "application/vnd.oasis.opendocument.text" if get_tmp_file: return file_name wrapper = FileWrapper(file(file_name)) # notice not using the tmp file! Not ideal. response = HttpResponse(wrapper, content_type=content) response["Content-Length"] = os.path.getsize(file_name) response["Content-Disposition"] = "attachment; filename=" + filename + ext try: os.remove(file_name) except: pass # this sucks. But Ubuntu can't run ooo as www-data return response
def _render_document(self, pod_template, output_format, sub_documents, raiseOnError=False, **kwargs): """ Render a single document of type 'output_format' using the odt file 'document_template' as the generation template. Subdocuments is a dictionnary of previously generated subtemplate that will be merged into the current generated document. """ document_template = pod_template.get_file() temp_filename = tempfile.mktemp('.{extension}'.format(extension=output_format)) # Prepare rendering context helper_view = self.get_generation_context_helper() generation_context = self._get_generation_context(helper_view, pod_template=pod_template) # enrich the generation context with previously generated documents utils.update_dict_with_validation(generation_context, sub_documents, _("Error when merging merge_templates in generation context")) # enable optimalColumnWidths if enabled in the config and/or on ConfigurablePodTemplate stylesMapping = {} optimalColumnWidths = False template_optimize_tables = pod_template.get_optimize_tables() if (template_optimize_tables == -1 and config.get_optimize_tables()) or \ template_optimize_tables == 1: stylesMapping = {'table': TableProperties(optimalColumnWidths=True)} optimalColumnWidths = "OCW_.*" # if raiseOnError is not enabled, enabled it in the config excepted if user is a Manager # and currently generated document use odt format if not raiseOnError: if config.get_raiseOnError_for_non_managers(): raiseOnError = True if 'Manager' in api.user.get_roles() and output_format == 'odt': raiseOnError = False renderer = Renderer( StringIO(document_template.data), generation_context, temp_filename, pythonWithUnoPath=config.get_uno_path(), ooPort=config.get_oo_port(), raiseOnError=raiseOnError, imageResolver=api.portal.get(), forceOoCall=True, optimalColumnWidths=optimalColumnWidths, stylesMapping=stylesMapping, **kwargs ) # it is only now that we can initialize helper view's appy pod renderer all_helper_views = self.get_views_for_appy_renderer(generation_context, helper_view) for view in all_helper_views: view._set_appy_renderer(renderer) renderer.run() # return also generation_context to test ist content in tests return temp_filename, generation_context
def renderOdt(dictionary, tempfilename='tempcv', template=DEFAULT_TEMPLATE): # filename = dictionary['p'].name.encode('ascii', 'ignore') + ' - ' + dictionary['c'].title.encode('ascii', 'ignore').replace(",","").replace('/','') + ".odt" rsltFile = '/var/tmp/%s.odt' % tempfilename r = Renderer(template, dictionary, rsltFile, overwriteExisting=True) r.run() return rsltFile
def post(self, request, **kwargs): download_type = request.GET.get('type') context = self.get_context_data(**kwargs) if request.POST.get('data', None): data = simplejson.loads(request.POST['data']) self.report.handle_post_data(data) context['object_list'] = self.report.report_to_list( user=self.request.user, preview=True) context['headers'] = self.report.get_preview_fields() if download_type == "preview": preview_html = render_to_string(self.template_name, context) response_data = {} response_data['preview_html'] = preview_html response_data['filter_errors'] = self.report.filter_errors return HttpResponse(json.dumps(response_data), content_type="application/json") elif download_type == "xlsx": data = self.report.report_to_list(self.request.user) return self.list_to_xlsx_response(data) elif download_type == 'django_admin': ids = self.report.get_queryset().values_list('id', flat=True) ids = ",".join(str(x) for x in ids) response = redirect('admin:{}_{}_changelist'.format( self.model._meta.app_label, self.model._meta.model_name)) response['Location'] += '?id__in={}'.format(ids) return response elif download_type == "appy": filename = 'report' ext = '.odt' appy_context = self.report.get_appy_context() template_name = self.report.get_appy_template() from appy.pod.renderer import Renderer outfile_name = tempfile.gettempdir() + '/appy' + str(time.time()) + ext renderer = Renderer(template_name, appy_context, outfile_name) renderer.run() if ext == ".doc": content = "application/msword" elif ext == ".docx": content = "application/vnd.openxmlformats-officedocument.wordprocessingml.document" elif ext == ".pdf": content = "application/pdf" elif ext == ".rtf": content = "application/rtf" elif ext == '.ods': content = "application/vnd.oasis.opendocument.spreadsheet" else: # odt content = "application/vnd.oasis.opendocument.text" wrapper = FileWrapper(file(outfile_name)) response = HttpResponse(wrapper, content_type=content) response['Content-Length'] = os.path.getsize(outfile_name) response['Content-Disposition'] = 'attachment; filename=' + filename + ext try: os.remove(file_name) except: pass # At least it's in the tmp folder return response
def createReport(self): fileName = '%sdeliver%d.pdf' % ('reports/', self.deliver.id) if path.exists(fileName): os.popen('evince %s' % fileName) else: opts = {'deliver': self.deliver} renderer = Renderer('appy/templates/deliver.odt', opts, fileName) renderer.run() os.popen('evince %s' % fileName)
def createReport(self,inf_basicas_dic,nom_arquivo,nom_comissao, materia, nom_autor, txt_ementa, tip_apresentacao, tip_conclusao, data_parecer, nom_relator, lst_composicao,modelo_proposicao): # Criacao ODT url = self.sapl_documentos.modelo.materia.parecer.absolute_url() + "/%s"%modelo_proposicao template_file = cStringIO.StringIO(urllib.urlopen(url).read()) output_file_odt = "%s"%nom_arquivo renderer = Renderer(template_file, locals(), output_file_odt, pythonWithUnoPath='/usr/bin/python3',forceOoCall=True) renderer.run() data = open(output_file_odt, "rb").read() for file in [output_file_odt]: os.unlink(file) self.sapl_documentos.parecer_comissao.manage_addFile(id=nom_arquivo,file=data)
def createReport(self,inf_basicas_dic,nom_arquivo, sgl_tipo_documento, num_documento, ano_documento, txt_ementa, dat_documento, dia_documento, nom_autor,modelo_documento): # Criacao ODT url = self.sapl_documentos.modelo.documento_administrativo.absolute_url() + "/%s"%modelo_documento template_file = cStringIO.StringIO(urllib.urlopen(url).read()) output_file_odt = "%s"%nom_arquivo renderer = Renderer(template_file, locals(), output_file_odt, pythonWithUnoPath='/usr/bin/python',forceOoCall=True) renderer.run() data = open(output_file_odt, "rb").read() for file in [output_file_odt]: os.unlink(file) self.sapl_documentos.administrativo.manage_addFile(id=nom_arquivo,file=data)
def createReport(self, inf_basicas_dic, lst_oradores, lst_presidente, nom_arquivo): # Criacao ODT url = self.sapl_documentos.modelo.sessao_plenaria.absolute_url() + "/oradores.odt" template_file = cStringIO.StringIO(urllib.urlopen(url).read()) output_file_odt = "%s"%nom_arquivo renderer = Renderer(template_file, locals(), output_file_odt, pythonWithUnoPath='/usr/bin/python3',forceOoCall=True) renderer.run() data = open(output_file_odt, "rb").read() for file in [output_file_odt]: os.unlink(file) self.sapl_documentos.oradores_expediente.manage_addFile(id=output_file_odt,file=data)
def process_pod(template,context,outfile): #template_name = r"c:\temp\sales\invoice.odt" params = context params['time'] = time #resultFile = outfile #tmpFolder = os.path.join(os.path.dirname(outfile), 'temp') #resultFile = os.path.join(tmpFolder, 'tmp.%s' % docFormat) try: renderer = Renderer(template, params, outfile, coOpenOfficePath) renderer.run() except PodError, pe: raise pe
def createReport(self,inf_basicas_dic,nom_arquivo,des_tipo_norma,num_norma,ano_norma,dat_norma,data_norma,txt_ementa,modelo_norma): # Criacao ODT url = self.sapl_documentos.modelo.norma.absolute_url() + "/%s"%modelo_norma template_file = cStringIO.StringIO(urllib.urlopen(url).read()) #output_file_odt = os.path.normpath(nom_arquivo_odt) output_file_odt = "%s"%nom_arquivo renderer = Renderer(template_file, locals(), output_file_odt, pythonWithUnoPath='/usr/bin/python',forceOoCall=True) renderer.run() data = open(output_file_odt, "rb").read() for file in [output_file_odt]: os.unlink(file) self.sapl_documentos.norma_juridica.manage_addFile(id=nom_arquivo,file=data)
def download_rapport_transaction(): start_date = request.args['start_date'] end_date = request.args['end_date'] or start_date representant = request.args['representant_nom'] if request.args['representant_nom'] else 'tous' type_client = request.args['type_client'] if request.args['type_client'] else 'tous' rows = _get_rapport_transaction_data(request) # each row: {top: <list of 7 items>, [bottom: str,] # subitems: <list of 4 items>} items = [] ncf_rows = defaultdict(list) # ncf -> [] for row in rows: ncf_rows[int(row['no_commande_facture'])].append(row) totals = [0] * 6 for ncf in sorted(ncf_rows.iterkeys()): row0 = ncf_rows[ncf][0] exp = '' if row0['expedition'] == 'direct': exp = 'direct%s' % (' (%s)' % row0['date_direct'] if row0['date_direct'] else '') elif row0['expedition'] == 'pickup': exp = 'pickup%s' % (' (%s)' % row0['date_pickup'] if row0['date_pickup'] else '') elif row0['expedition'] == 'succursale': exp = 'succursale%s' % (' (%s)' % row0['no_succursale_saq'] if row0['no_succursale_saq'] else '') note = row0['note_commande'] if row0['note_commande'] else '' item = {'top': ['%s (%s)' % (row0['nom_social'], row0['no_client_saq'] if row0['no_client_saq'] else '?'), row0['no_commande_facture'], row0['no_commande_saq'], '%s %s' % (exp, note), as_currency(row0['montant']), as_currency(row0['sous_total']), as_currency(row0['tps']), as_currency(row0['tvq'])]} if representant == 'tous': item['bottom'] = row0['representant_nom'] subitems = [] for row in ncf_rows[ncf]: nd = ', %s' % row['nom_domaine'] if row['nom_domaine'] else '' subitems.append(['%s%s' % (row['type_vin'], nd), row['format'], '%s(cs)' % row['quantite_caisse'], '%s(bt)' % row['quantite_par_caisse']]) for i, f in enumerate(['quantite_caisse', 'quantite_bouteille']): totals[i] += row[f] if row[f] else 0 item['subitems'] = subitems items.append(item) for i, f in enumerate(['montant', 'sous_total', 'tps', 'tvq'], 2): totals[i] += row0[f] if row0[f] else 0 totals[2:] = [as_currency(v) for v in totals[2:]] doc_values = {'start_date': start_date, 'end_date': end_date, 'representant_nom': representant, 'type_client': type_client, 'items': items, 'totals': totals} out_fn = 'rapport_des_transactions_%s_au_%s_repr=%s_clients=%s.%s' % (start_date, end_date, representant, type_client, 'odt' if hasattr(app, 'is_dev') else 'pdf') out_fn = unidecode(out_fn) tmpl_fn = '/home/christian/vinum/docs/rapport_des_transactions.odt' if representant == 'tous' else \ '/home/christian/vinum/docs/rapport_des_transactions_1repr.odt' ren = Renderer(tmpl_fn, doc_values, '/tmp/%s' % out_fn, overwriteExisting=True) ren.run() return send_file('/tmp/%s' % out_fn, mimetype='application/pdf', attachment_filename=out_fn, as_attachment=True)
def createReport(self, inf_basicas_dic, lst_materia_apresentada): # Criacao ODT url = self.sapl_documentos.modelo.sessao_plenaria.absolute_url() + "/materia_apresentada.odt" template_file = cStringIO.StringIO(urllib.urlopen(url).read()) output_file_odt = "materia_apresentada.odt" renderer = Renderer(template_file, locals(), output_file_odt, pythonWithUnoPath='/usr/bin/python3',forceOoCall=True) renderer.run() data = open(output_file_odt, "rb").read() for file in [output_file_odt]: os.unlink(file) self.REQUEST.RESPONSE.headers['Content-Type'] = 'application/vnd.oasis.opendocument.text' self.REQUEST.RESPONSE.headers['Content-Disposition'] = 'attachment; filename="%s"'%output_file_odt return data
def createReport(self, inf_basicas_dic, num_ident_basica, nom_autor): # Criacao ODT url = self.sapl_documentos.modelo.documento_administrativo.absolute_url() + "/oficio_requerimento_pres.odt" template_file = cStringIO.StringIO(urllib.urlopen(url).read()) output_file_odt = "oficio_req_presidencia.odt" renderer = Renderer(template_file, locals(), output_file_odt, pythonWithUnoPath='/usr/bin/python3',forceOoCall=True) renderer.run() data = open(output_file_odt, "rb").read() for file in [output_file_odt]: os.unlink(file) self.REQUEST.RESPONSE.headers['Content-Type'] = 'application/vnd.oasis.opendocument.text' self.REQUEST.RESPONSE.headers['Content-Disposition'] = 'attachment; filename="%s"'%output_file_odt return data
def createReport(self, inf_basicas_dic, lst_indicacao, lst_presidente): # Criacao ODT url = self.sapl_documentos.modelo.sessao_plenaria.absolute_url() + "/oficio_indicacao.odt" template_file = cStringIO.StringIO(urllib.urlopen(url).read()) output_file_odt = "oficio_indicacao.odt" renderer = Renderer(template_file, locals(), output_file_odt, pythonWithUnoPath='/usr/bin/python3',forceOoCall=True) renderer.run() data = open(output_file_odt, "rb").read() for file in [output_file_odt]: os.unlink(file) self.REQUEST.RESPONSE.headers['Content-Type'] = 'application/vnd.oasis.opendocument.text' self.REQUEST.RESPONSE.headers['Content-Disposition'] = 'attachment; filename="%s"'%output_file_odt return data
def convertFile(self,cod_materia): # Conversao para PDF nom_arquivo_odt = "%s"%cod_materia+'_texto_integral.odt' nom_arquivo_pdf = "%s"%cod_materia+'_texto_integral.pdf' url = self.sapl_documentos.materia_odt.absolute_url() + "/%s"%nom_arquivo_odt odtFile = cStringIO.StringIO(urllib.urlopen(url).read()) output_file_pdf = os.path.normpath(nom_arquivo_pdf) renderer = Renderer(odtFile,locals(),output_file_pdf,pythonWithUnoPath='/usr/bin/python3',forceOoCall=True) renderer.run() data = open(output_file_pdf, "rb").read() for file in [output_file_pdf]: self.sapl_documentos.materia.manage_addProduct['ExtFile'].manage_addExtFile(id=file,title=file,file=file) os.unlink(file)
def download_bottin(): assert current_user.u['representant_id'] cur = g.db.cursor() out_fn = 'bottin_des_restaurateurs_repr=%s.%s' % (current_user.u['usager_nom'], 'odt' if hasattr(app, 'is_dev') else 'pdf') restos = pg.select(cur, 'client', where={'representant_id': current_user.u['representant_id'], 'type_client': 'restaurant', 'est_actif': True}, order_by='nom_social') rn = pg.select1(cur, 'representant', 'representant_nom', where={'representant_id': current_user.u['representant_id']}) doc_values = {'items': restos, 'representant_nom': rn} ren = Renderer('/home/christian/vinum/docs/bottin.odt', doc_values, '/tmp/%s' % out_fn, overwriteExisting=True) ren.run() return send_file('/tmp/%s' % out_fn, mimetype='application/pdf', attachment_filename=out_fn, as_attachment=True)
def createReport(self, inf_basicas_dic, lst_votacao, lst_presidente): # Criacao ODT url = self.sapl_documentos.modelo.sessao_plenaria.absolute_url() + "/ordem_dia.odt" template_file = cStringIO.StringIO(urllib.urlopen(url).read()) output_file_odt = "ordem_dia.odt" renderer = Renderer(template_file, locals(), output_file_odt, pythonWithUnoPath="/usr/bin/python") renderer.run() data = open(output_file_odt, "rb").read() for file in [output_file_odt]: os.unlink(file) self.REQUEST.RESPONSE.headers["Content-Type"] = "application/vnd.oasis.opendocument.text" self.REQUEST.RESPONSE.headers["Content-Disposition"] = 'attachment; filename="%s"' % output_file_odt return data
def createReport(self, inf_basicas_dic, lst_mesa, lst_presenca_sessao, lst_materia_apresentada, lst_reqplen, lst_reqpres, lst_indicacao, lst_presenca_ordem_dia, lst_votacao, lst_presenca_expediente, lst_oradores, lst_presenca_encerramento, lst_presidente, lst_psecretario, lst_ssecretario): # Criacao ODT url = self.sapl_documentos.modelo.sessao_plenaria.absolute_url() + "/iom.odt" template_file = cStringIO.StringIO(urllib.urlopen(url).read()) output_file_odt = "publicacao_iom.odt" renderer = Renderer(template_file, locals(), output_file_odt, pythonWithUnoPath='/usr/bin/python',forceOoCall=True) renderer.run() data = open(output_file_odt, "rb").read() for file in [output_file_odt]: os.unlink(file) self.REQUEST.RESPONSE.headers['Content-Type'] = 'application/vnd.oasis.opendocument.text' self.REQUEST.RESPONSE.headers['Content-Disposition'] = 'attachment; filename="%s"'%output_file_odt return data
def __call__(self): params = {} params['body_text'] = self.cleanupText() renderer = Renderer(self.odt_file, params, self.tempFileName) renderer.run() self.request.response.setHeader('Content-type', 'application/vnd.oasis.opendocument.text') self.request.response.setHeader('Content-disposition', 'inline;filename="'+ removeSecurityProxy(self.context.report_type)+"_"+ removeSecurityProxy(self.context.start_date).strftime('%Y-%m-%d')+'.odt"') f = open(self.tempFileName, 'rb') doc = f.read() f.close() os.remove(self.tempFileName) return doc
def crear_reporte(self, dic_data, nombre_doc, formato_salida, nombre_plantilla, nombre_parametro_plantilla): """ dic_data -- Data que se alojará en el documento reporte nombre_doc -- Nombre para el archivo a descargar formato_salida -- Extensión de salida para el reporte EJ -> pdf, xls nombre_plantilla -- Nombre del documento fuente alojado en /modulo/reports/ EJ -> plantilla_visitas.odt nombre_parametro_plantilla -- ir.config_parameter Nombre del parametro donde se especifica la ruta de la plantilla EJ -> plan_mejoramiento_ruta_plantilla_reportes """ # ruta para plantilla parametro_ruta = self.env['ir.config_parameter'].get_param(nombre_parametro_plantilla, context=None) if (parametro_ruta == ' '): raise ValidationError("Debe establecer la ruta para el parametro " + nombre_parametro_plantilla) plantilla = parametro_ruta + nombre_plantilla # get extencion de plantilla extencion_plantilla = nombre_plantilla.split(".")[-1] # nombres para archivos inicial_nombre = "REPORTE_" nombre_archivo_result = inicial_nombre + nombre_doc + '_' + str(self.id) + '.' + extencion_plantilla nombre_archivo_result_transf = inicial_nombre + nombre_doc + '_' + str(self.id) +'.'+formato_salida # Carpeta Contenedora de los reportes carpeta = '/tmp/reportres/' archivo_result = carpeta + nombre_archivo_result archivo_result_transf = carpeta + nombre_archivo_result_transf # Verificar si existe carpeta, si no la crea if not os.path.exists(carpeta): os.makedirs(carpeta) # Crear archivo basado en la plantilla y los datos try: globals_dict = globals() globals_dict['data'] = dic_data renderer = Renderer(plantilla, globals_dict, archivo_result) renderer.run() except IOError as e: raise ValidationError("I/O Error: {0}".format(e)) except: raise ValidationError("Error en la ruta del Archivo") # Convierte a Formato Salida kill_libreoffice() subprocess.Popen("libreoffice --headless --invisible --convert-to {} {} --outdir {} ".format(formato_salida, archivo_result, carpeta) ,shell=True) # ya esta creado xls? while not os.path.isfile(archivo_result_transf): sleep(1) # codificar archivo with open(archivo_result_transf, "rb") as reporte: encoded_report = base64.b64encode(reporte.read()) # Elinimar archivos creados en disco if(encoded_report): os.remove(archivo_result) os.remove(archivo_result_transf) return encoded_report, nombre_archivo_result_transf
def generateDocument(self): '''Generates the document from field-related info. UID of object that is the template target is given in the request.''' rq = self.REQUEST appyTool = self.appy() # Get the object objectUid = rq.get('objectUid') obj = self.uid_catalog(UID=objectUid)[0].getObject() appyObj = obj.appy() # Get information about the document to render. specificPodContext = None fieldName = rq.get('fieldName') format = rq.get('podFormat') podInfo = self.getPodInfo(obj, fieldName) template = podInfo['template'].content podTitle = podInfo['title'] if podInfo['context']: if type(podInfo['context']) == types.FunctionType: specificPodContext = podInfo['context'](appyObj) else: specificPodContext = podInfo['context'] doAction = rq.get('askAction') == 'True' # Temporary file where to generate the result tempFileName = '%s/%s_%f.%s' % ( getOsTempFolder(), obj.UID(), time.time(), format) # Define parameters to pass to the appy.pod renderer currentUser = self.portal_membership.getAuthenticatedMember() podContext = {'tool': appyTool, 'user': currentUser, 'self': appyObj, 'now': self.getProductConfig().DateTime(), 'projectFolder': appyTool.getDiskFolder(), } if specificPodContext: podContext.update(specificPodContext) rendererParams = {'template': StringIO.StringIO(template), 'context': podContext, 'result': tempFileName} if appyTool.unoEnabledPython: rendererParams['pythonWithUnoPath'] = appyTool.unoEnabledPython if appyTool.openOfficePort: rendererParams['ooPort'] = appyTool.openOfficePort # Launch the renderer try: renderer = Renderer(**rendererParams) renderer.run() except appy.pod.PodError, pe: if not os.path.exists(tempFileName): # In some (most?) cases, when OO returns an error, the result is # nevertheless generated. appyTool.log(str(pe), type='error') appyTool.say(POD_ERROR) return self.goto(rq.get('HTTP_REFERER'))