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 __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 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 do(self): tempFileName = '%s.%s' % (self.data['Name'], self.data['Result']) self.result = sjoin(self.tempFolder, tempFileName) # Get the path to the template to use for this test if self.data['Template'].endswith('.ods'): suffix = '' else: # For ODT, which is the most frequent case, no need to specify the # file extension. suffix = '.odt' template = sjoin(self.templatesFolder, self.data['Template'] + suffix) if not os.path.exists(template): raise TesterError(TEMPLATE_NOT_FOUND % template) # Get the context context = self.getContext(self.data['Context']) # Get the LibreOffice port ooPort = self.data['LibreOfficePort'] pythonWithUno = self.config['pythonWithUnoPath'] # Get the styles mapping. Dicts are not yet managed by the TablesParser stylesMapping = eval('{' + self.data['StylesMapping'] + '}') # Call the renderer params = { 'ooPort': ooPort, 'pythonWithUnoPath': pythonWithUno, 'stylesMapping': stylesMapping } params.update(self.rendererParams) Renderer(template, context, self.result, **params).run()
def do(self): self.result = os.path.join( self.tempFolder, '%s.%s' % (self.data['Name'], self.data['Result'])) # Get the path to the template to use for this test if self.data['Template'].endswith('.ods'): suffix = '' else: # For ODT, which is the most frequent case, no need to specify the # file extension. suffix = '.odt' template = os.path.join(self.templatesFolder, self.data['Template'] + suffix) if not os.path.exists(template): raise TesterError(TEMPLATE_NOT_FOUND % template) # Get the context context = self.getContext(self.data['Context']) # Get the OpenOffice port ooPort = self.data['OpenOfficePort'] pythonWithUno = self.config['pythonWithUnoPath'] # Get the styles mapping stylesMapping = eval('{' + self.data['StylesMapping'] + '}') # Mmh, dicts are not yet managed by RtfTablesParser # Call the renderer. Renderer(template, context, self.result, ooPort=ooPort, pythonWithUnoPath=pythonWithUno, stylesMapping=stylesMapping).run()
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 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( ) + "/ata.odt" template_file = cStringIO.StringIO(urllib.urlopen(url).read()) output_file_odt = "ata_sessao.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 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 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 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 prepare_odt(template, template_parameters, output_path): template_path = os.path.join(template_dir, template) renderer = Renderer( template_path, template_parameters, output_path ) renderer.run()
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 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 createReport(self,inf_basicas_dic,nom_arquivo,nom_comissao, materia, nom_autor, txt_ementa, tip_apresentacao, tip_conclusao, data_parecer, nom_relator, lst_composicao): # Criacao ODT url = self.sapl_documentos.modelo.materia.parecer.absolute_url() + "/parecer.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/python',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, 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(template_path, generation_context, destination_path): renderer = Renderer( "/storage/" + template_path, generation_context, "/storage/" + destination_path, pythonWithUnoPath=os.getenv("PYTHON_WITH_UNO_PATH", default=""), ooServer="localhost", ooPort=2002, stream=False, overwriteExisting=True, ) renderer.run()
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 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, 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_substitutivo): # Conversao para PDF nom_arquivo_odt = "%s"%cod_substitutivo+'_substitutivo.odt' nom_arquivo_pdf = "%s"%cod_substitutivo+'_substitutivo.pdf' url = self.sapl_documentos.substitutivo.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.substitutivo.manage_addFile(id=file,file=file) os.unlink(file)
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 gerar_proposicao_pdf(self, cod_proposicao): # Conversao para PDF nom_arquivo_odt = "%s"%cod_proposicao+'.odt' nom_arquivo_pdf1 = "%s"%cod_proposicao+'.pdf' url = self.sapl_documentos.proposicao.absolute_url() + "/%s"%nom_arquivo_odt odtFile = cStringIO.StringIO(urllib.urlopen(url).read()) output_file_pdf = os.path.normpath(nom_arquivo_pdf1) renderer = Renderer(odtFile,locals(),output_file_pdf,pythonWithUnoPath='/usr/bin/python3') renderer.run() data = open(output_file_pdf, "rb").read() for file in [output_file_pdf]: self.sapl_documentos.proposicao.manage_addFile(id=nom_arquivo_pdf1, file=data) os.unlink(file)
def save_week(begin, end, month, number, days): renderer = Renderer( args.template, { 'days': days, 'begin': begin, 'end': end, 'month': months[month - 1], 'number': number, 'name': args.name, 'year': begin.year, 'lastname': args.lastname, 'division': args.division }, "%s-%s.odt" % (begin, end)) renderer.run()
def gerar_norma_pdf(self, cod_norma): # Conversao para PDF nom_arquivo_odt = "%s"%cod_norma+'_texto_integral.odt' nom_arquivo_pdf1 = "%s"%cod_norma+'_texto_consolidado.pdf' nom_arquivo_pdf2 = "%s"%cod_norma+'_texto_consolidado' url = self.sapl_documentos.norma_juridica.absolute_url() + "/%s"%nom_arquivo_odt odtFile = cStringIO.StringIO(urllib.urlopen(url).read()) output_file_pdf = os.path.normpath(nom_arquivo_pdf1) renderer = Renderer(odtFile,locals(),output_file_pdf,pythonWithUnoPath='/usr/bin/python3') renderer.run() data = open(output_file_pdf, "rb").read() for file in [output_file_pdf]: self.sapl_documentos.norma_juridica.manage_addFile(id=nom_arquivo_pdf1, file=data) os.unlink(file)
def report_cartaAbsentisme(request, carta): #from django.template import Context from appy.pod.renderer import Renderer import cgi import os from django import http import time excepcio = None contingut = None try: #resultat = StringIO.StringIO( ) resultat = "/tmp/DjangoAula-temp-{0}-{1}.odt".format( time.time(), request.session.session_key) #context = Context( {'reports' : reports, } ) path = None path = os.path.join(settings.PROJECT_DIR, '../customising/docs/cartesFaltesAssistencia.odt') if not os.path.isfile(path): path = os.path.join(os.path.dirname(__file__), 'templates/cartesFaltesAssistencia.odt') dades_report = { 'professor': carta.professor, 'alumne': unicode(carta.alumne), 'grup': unicode(carta.alumne.grup), 'nfaltes': carta.nfaltes, 'year': carta.data_carta.year, 'fins_a_data': carta.faltes_fins_a_data.strftime('%d/%m/%Y'), 'tipus1': carta.tipus_carta == 'tipus1', 'tipus2': carta.tipus_carta == 'tipus2', 'tipus3A': carta.tipus_carta == 'tipus3A', 'tipus3B': carta.tipus_carta == 'tipus3B', 'tipus3C': carta.tipus_carta == 'tipus3C', 'tipus3D': carta.tipus_carta == 'tipus3D', } renderer = Renderer(path, dades_report, resultat) renderer.run() docFile = open(resultat, 'rb') contingut = docFile.read() docFile.close() os.remove(resultat) except Exception, e: excepcio = unicode(e)
def render_to_odt(target_file, startfile=False, **context): """ Render a chunk to an odt file using a default template. """ from appy.pod.renderer import Renderer dir = os.path.abspath(os.path.dirname(__file__)) template_file = os.path.join(dir, "Template.odt") #~ target_file = os.path.join(dir,"tmp.odt") if os.path.exists(target_file): os.remove(target_file) #~ context = dict(body=body,self="lino.utils.xmlgen.odf example") renderer = Renderer(template_file, context, target_file) renderer.run() if startfile: os.startfile(target_file) return "File %s has been created." % target_file
def gerar_oficio_odt(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()) brasao_file = self.get_brasao() # atribui o brasao no locals exec 'brasao = brasao_file' output_file_odt = "%s" % nom_arquivo renderer = Renderer(template_file, locals(), output_file_odt, pythonWithUnoPath='/usr/bin/python3') 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 gerar_substitutivo_odt(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.substitutivo.absolute_url() + "/%s"%modelo_proposicao template_file = cStringIO.StringIO(urllib.urlopen(url).read()) brasao_file = self.get_brasao() # atribui o brasao no locals exec 'brasao = brasao_file' output_file_odt = "%s"%nom_arquivo renderer = Renderer(template_file, locals(), output_file_odt, pythonWithUnoPath='/usr/bin/python3') renderer.run() data = open(output_file_odt, "rb").read() for file in [output_file_odt]: os.unlink(file) self.sapl_documentos.substitutivo.manage_addFile(id=nom_arquivo,file=data)