Exemplo n.º 1
0
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
Exemplo n.º 2
0
 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__()
Exemplo n.º 3
0
 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__()
Exemplo n.º 4
0
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
Exemplo n.º 5
0
    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)
Exemplo n.º 6
0
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
Exemplo n.º 7
0
    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__()
Exemplo n.º 8
0
    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.")
Exemplo n.º 9
0
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 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
Exemplo n.º 11
0
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)
Exemplo n.º 12
0
 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()
Exemplo n.º 13
0
 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__()
Exemplo n.º 14
0
 def __init__(self, ar, template, context, result, **kw):
     self.ar = copy(ar)
     # self.ar.renderer = settings.SITE.kernel.html_renderer
     # self.ar.renderer = settings.SITE.plugins.bootstrap3.renderer
     self.ar.renderer = settings.SITE.plugins.jinja.renderer
     #~ context.update(appy_renderer=self)
     context.update(restify=self.restify_func)
     context.update(html=self.html_func)
     # context.update(E=E)
     # context.update(Decimal=Decimal)
     context.update(jinja=self.jinja_func)
     context.update(table=self.insert_table)
     context.update(as_odt=self.as_odt)
     context.update(story=self.insert_story)
     #~ context.update(html2odf=html2odf)
     context.update(ehtml=html2odf)
     context.update(toxml=toxml)
     #~ from lino.extjs import ui
     #~ self.extjs_ui = ui
     context.update(ui=settings.SITE.kernel)
     context.update(settings=settings)
     context.update(sc=settings.SITE.site_config)
     if False:
         context.update(settings.SITE.modules)
         # 20150810 removed above line because this "feature"
         # caused the name `jinja` defined above to be overridden.
     kw.update(finalizeFunction=self.finalize_func)
     OriginalAppyRenderer.__init__(self, template, context, result, **kw)
     #~ self.my_automaticstyles = odf.style.automaticstyles()
     #~ self.my_styles = odf.style.styles()
     self.my_automaticstyles = []
     self.my_styles = []
Exemplo n.º 15
0
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
Exemplo n.º 16
0
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()
Exemplo n.º 17
0
 def __init__(self, ar, template, context, result, **kw):
     self.ar = copy(ar)
     # self.ar.renderer = settings.SITE.kernel.html_renderer
     # self.ar.renderer = settings.SITE.plugins.bootstrap3.renderer
     self.ar.renderer = settings.SITE.plugins.jinja.renderer
     #~ context.update(appy_renderer=self)
     context.update(restify=self.restify_func)
     context.update(html=self.insert_html)
     context.update(jinja=self.insert_jinja)
     context.update(table=self.insert_table)
     context.update(story=self.insert_story)
     context.update(as_odt=self.as_odt)
     #~ context.update(html2odf=html2odf)
     context.update(ehtml=html2odf)
     context.update(toxml=toxml)
     #~ from lino.extjs import ui
     #~ self.extjs_ui = ui
     context.update(ui=settings.SITE.kernel)
     context.update(settings=settings)
     context.update(sc=settings.SITE.site_config)
     if False:
         context.update(settings.SITE.models)
         # 20150810 removed above line because this "feature"
         # caused the name `jinja` defined above to be overridden.
     kw.update(finalizeFunction=self.finalize_func)
     OriginalAppyRenderer.__init__(self, template, context, result, **kw)
     #~ self.my_automaticstyles = odf.style.automaticstyles()
     #~ self.my_styles = odf.style.styles()
     self.my_automaticstyles = []
     self.my_styles = []
Exemplo n.º 18
0
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
Exemplo n.º 19
0
    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 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
Exemplo n.º 21
0
 def __init__(self, ar, template, context, result, **kw):
     self.ar = ar
     #~ context.update(appy_renderer=self)
     context.update(restify=self.restify_func)
     context.update(html=self.html_func)
     context.update(jinja=self.jinja_func)
     context.update(table=self.insert_table)
     context.update(as_odt=self.as_odt)
     #~ context.update(story=self.insert_story)
     #~ context.update(html2odf=html2odf)
     context.update(ehtml=html2odf)
     context.update(toxml=toxml)
     #~ from lino.extjs import ui
     #~ self.extjs_ui = ui
     #~ self.extjs_ui = settings.SITE.ui
     #~ context.update(ui=self.extjs_ui)
     context.update(ui=settings.SITE.ui)
     context.update(settings=settings)
     context.update(sc=settings.SITE.site_config)
     context.update(settings.SITE.modules)
     kw.update(finalizeFunction=self.finalize_func)
     AppyRenderer.__init__(self,template,context,result, **kw)
     #~ self.my_automaticstyles = odf.style.automaticstyles()
     #~ self.my_styles = odf.style.styles()
     self.my_automaticstyles = []
     self.my_styles = []
Exemplo n.º 22
0
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()
Exemplo n.º 23
0
    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
Exemplo n.º 24
0
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
Exemplo n.º 25
0
    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
Exemplo n.º 26
0
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
Exemplo n.º 27
0
	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)
Exemplo n.º 28
0
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)
Exemplo n.º 29
0
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)
Exemplo n.º 30
0
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)
Exemplo n.º 31
0
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)
Exemplo n.º 32
0
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)
Exemplo n.º 33
0
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)
Exemplo n.º 34
0
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()
Exemplo n.º 35
0
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
Exemplo n.º 36
0
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)
Exemplo n.º 37
0
 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)
Exemplo n.º 38
0
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)
Exemplo n.º 39
0
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 
Exemplo n.º 40
0
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, 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 
Exemplo n.º 42
0
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)
Exemplo n.º 43
0
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 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 
Exemplo n.º 45
0
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)
Exemplo n.º 46
0
Arquivo: bhg.py Projeto: lukad/bhg
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()
Exemplo n.º 47
0
 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  
Exemplo n.º 48
0
 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)
Exemplo n.º 49
0
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)
Exemplo n.º 50
0
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
Exemplo n.º 51
0
    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)
Exemplo n.º 52
0
 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()
Exemplo n.º 53
0
 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()