def test_error_mode(self):
     """ Tests that a LayoutError is raised if the onOverflow
     attribute for a keepInFrame tag is set to "error" and the
     content does not fit in the frame.
     """
     rml = """
     <!DOCTYPE document SYSTEM "rml.dtd">
     <document>
         <template pageSize="(8.5in, 11in)" showBoundary="1">
             <pageTemplate id="main">
                 <frame id="i" x1="1in" y1="9in" width="2in" height="1in"/>
             </pageTemplate>
         </template>
         <stylesheet>
         </stylesheet>
         <story>
             <keepInFrame onOverflow="error">
                 <para fontSize="30">
                     This should raise a LayoutError!!!!!!!!!!!!
                 </para>
             </keepInFrame>
         </story>
     </document>
     """
     with self.assertRaises(LayoutError):
         trml2pdf.parseString(rml)
Example #2
0
def principal(sessao, lst_materias):
    arquivoPdf = str(int(time.time() * 100)) + ".pdf"
    tmp_data = ''
    tmp_data += '<?xml version="1.0" encoding="iso-8859-1" standalone="no" ?>\n'
    tmp_data += '<!DOCTYPE document SYSTEM "rml.dtd">\n'
    tmp_data += '<document filename="fichas.pdf">\n'
    tmp_data += '<template pageSize="(21cm, 29.7cm)" leftMargin="2.5cm" rightMargin="2.5cm" topMargin="0.5cm" bottomMargin="0.5cm" title="Ficha" author="Sergio Damiati" showBoundary="0" allowSplitting="20">\n'
    tmp_data += '<pageTemplate id="main">\n'
    tmp_data += '<pageGraphics>\n'
    tmp_data += '</pageGraphics>\n'
    tmp_data += '<frame id="ficha" x1="3.5cm" y1="21.4cm" width="14cm" height="7cm"/>\n'
    tmp_data += '<frame id="ficha" x1="3.5cm" y1="12.5cm" width="14cm" height="7cm"/>\n'
    tmp_data += '<frame id="ficha" x1="3.5cm" y1="3cm" width="14cm" height="7cm"/>\n'
    tmp_data += '</pageTemplate>\n'
    tmp_data += '</template>\n'
    tmp_data += paraStyle()
    tmp_data += dados(lst_materias)
    tmp_data += '</document>\n'

    try:
        tmp_pdf = parseString(unicode(tmp_data, 'iso-8859-1'))
    except:
        tmp_pdf = parseString(unicode(tmp_data, 'utf-8'))

    if hasattr(context.temp_folder, arquivoPdf):
        context.temp_folder.manage_delObjects(ids=arquivoPdf)
    context.temp_folder.manage_addFile(arquivoPdf)
    arq = context.temp_folder[arquivoPdf]
    arq.manage_edit(title='Arquivo PDF temporario.',
                    filedata=tmp_pdf,
                    content_type='application/pdf')

    return "/temp_folder/" + arquivoPdf
Example #3
0
def principal(sessao,lst_materias):
	arquivoPdf=str(int(time.time()*100)) + ".pdf"
        tmp_data=''
        tmp_data+='<?xml version="1.0" encoding="iso-8859-1" standalone="no" ?>\n'
	tmp_data+='<!DOCTYPE document SYSTEM "rml.dtd">\n'
	tmp_data+='<document filename="etiquetas.pdf">\n'
	tmp_data+='<template pageSize="(21cm, 29.7cm)" leftMargin="2.5cm" rightMargin="2.5cm" topMargin="0.5cm" bottomMargin="0.5cm" title="Etiqueta" author="Sergio Damiati" showBoundary="0" allowSplitting="20">\n'
        tmp_data+='<pageTemplate id="main">\n'
        tmp_data+='<pageGraphics>\n'
        tmp_data+='</pageGraphics>\n'
        tmp_data+='<frame id="etiqueta" x1="3.5cm" y1="25cm" width="14cm" height="4.5cm"/>\n'
        tmp_data+='<frame id="etiqueta" x1="3.5cm" y1="19.8cm" width="14cm" height="4.5cm"/>\n'
        tmp_data+='<frame id="etiqueta" x1="3.5cm" y1="14.6cm" width="14cm" height="4.5cm"/>\n'
        tmp_data+='<frame id="etiqueta" x1="3.5cm" y1="9.3cm" width="14cm" height="4.5cm"/>\n'
        tmp_data+='<frame id="etiqueta" x1="3.5cm" y1="4.1cm" width="14cm" height="4.5cm"/>\n'
        tmp_data+='<frame id="etiqueta" x1="3.5cm" y1="-1cm" width="14cm" height="4.5cm"/>\n'
        tmp_data+='</pageTemplate>\n'
        tmp_data+='</template>\n'
        tmp_data+=paraStyle()
        tmp_data+=dados(lst_materias)
        tmp_data+='</document>\n'

	try:  
  	  tmp_pdf=parseString(unicode(tmp_data, 'iso-8859-1'))  
  	except:  
  	  tmp_pdf=parseString(unicode(tmp_data, 'utf-8'))

        if hasattr(context.temp_folder,arquivoPdf):
            context.temp_folder.manage_delObjects(ids=arquivoPdf)
        context.temp_folder.manage_addFile(arquivoPdf)
        arq=context.temp_folder[arquivoPdf]
        arq.manage_edit(title='Arquivo PDF temporario.',filedata=tmp_pdf,content_type='application/pdf')

        return "/temp_folder/"+arquivoPdf
Example #4
0
 def test_error_mode(self):
     """ Tests that a LayoutError is raised if the onOverflow
     attribute for a keepInFrame tag is set to "error" and the
     content does not fit in the frame.
     """
     rml = """
     <!DOCTYPE document SYSTEM "rml.dtd">
     <document>
         <template pageSize="(8.5in, 11in)" showBoundary="1">
             <pageTemplate id="main">
                 <frame id="i" x1="1in" y1="9in" width="2in" height="1in"/>
             </pageTemplate>
         </template>
         <stylesheet>
         </stylesheet>
         <story>
             <keepInFrame onOverflow="error">
                 <para fontSize="30">
                     This should raise a LayoutError!!!!!!!!!!!!
                 </para>
             </keepInFrame>
         </story>
     </document>
     """
     with self.assertRaises(LayoutError):
         parseString(rml)
Example #5
0
def get_pdf(coll_model,ent_id):
    res = coll_model.find_one({"_id":utils.create_objectid(ent_id)})
    t = Template(open(os.path.join(get_root_path(),'static','rml.rml')).read())
    add_time = res["add_time"].split(".")[0].replace("-",".")

    report_time = datetime.datetime.now().strftime('%Y.%m.%d %H:%M:%S')
    _rml = t.generate(item=res,time=report_time,add_time=add_time)
    rml = _rml.encode('utf-8')
    name = str(time.time()).replace('.','') + "-1" + '.pdf'
    uri = os.path.join(get_root_path(),'static','report',time.strftime('%Y'),time.strftime('%m-%d'),name)
    if not os.path.exists(os.path.dirname(uri)):
                os.makedirs(os.path.dirname(uri), mode=0777)
    trml2pdf.parseString(rml,uri)
    return "http://"+options.domain+uri.split("dxb")[1]
def principal(sessao,imagem,data,lst_protocolos,dic_cabecalho,lst_rodape,dic_filtro={}):
    """Funcao pricipal que gera a estrutura global do arquivo rml"""

    arquivoPdf=str(int(time.time()*100))+".pdf"

    tmp_data=''
    tmp_data+='<?xml version="1.0" encoding="utf-8" standalone="no" ?>\n'
    tmp_data+='<!DOCTYPE document SYSTEM "rml_1_0.dtd">\n'
    tmp_data+='<document filename="etiquetas.pdf">\n'
    tmp_data+='\t<template pageSize="(10cm, 6.2cm)" title="Capas de processos" author="OpenLegis" allowSplitting="20" rightMargin="3mm" showBoundary="0">\n'
    tmp_data+='\t\t<pageTemplate id="main">\n'
    tmp_data+='\t\t<pageGraphics>\n'
    tmp_data+='\t\t</pageGraphics>\n'
    tmp_data+='\t\t\t<frame id="first" x1="4mm" y1="1mm" width="94mm" height="60mm"/>\n'
    tmp_data+='\t\t</pageTemplate>\n'
    tmp_data+='\t</template>\n'
    tmp_data+=paraStyle()
    tmp_data+=protocolos(lst_protocolos)
    tmp_data+='</document>\n'
    tmp_pdf=parseString(tmp_data)

    if hasattr(context.temp_folder,arquivoPdf):
        context.temp_folder.manage_delObjects(ids=arquivoPdf)
    context.temp_folder.manage_addFile(arquivoPdf)
    arq=context.temp_folder[arquivoPdf]
    arq.manage_edit(title='Arquivo PDF temporário.',filedata=tmp_pdf,content_type='application/pdf')

    return "/temp_folder/"+arquivoPdf
Example #7
0
def displayDoc(request, id, doc):
    import trml2pdf
    # Create the HttpResponse object with the appropriate PDF headers for an invoice or a packing slip
    order = get_object_or_404(Order, pk=id)
    shopDetails = Config.objects.get_current()
    filename_prefix = shopDetails.site.domain
    if doc == "invoice":
        filename = "%s-invoice.pdf" % filename_prefix
        template = "invoice.rml"
    elif doc == "packingslip":
        filename = "%s-packingslip.pdf" % filename_prefix
        template = "packing-slip.rml"
    elif doc == "shippinglabel":
        filename = "%s-shippinglabel.pdf" % filename_prefix
        template = "shipping-label.rml"
    else:
        return HttpResponseRedirect('/admin')
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=%s' % filename
    icon_uri = config_value('SHOP', 'LOGO_URI')
    t = loader.get_template(os.path.join('shop/pdf', template))
    c = Context({
        'filename': filename,
        'iconURI': icon_uri,
        'shopDetails': shopDetails,
        'order': order,
    })
    pdf = trml2pdf.parseString(smart_str(t.render(c)))
    response.write(pdf)
    return response
Example #8
0
def principal(imagem, lst_splen, lst_pauta, dic_cabecalho, lst_rodape):
    """Funcao principal que gera a estrutura global do arquivo rml contendo o relatorio de uma ordem do dia.
    ordem_dia_[data da ordem do dia do relatório].pdf
    Retorna:
    Parâmetros:
    dat_ordem       => A data da ordem do dia.
        splen       => Uma lista de dicionários contendo as sessões plenárias do dia.
        pauta       => Uma lista de dicionários contendo a pauta da ordem do dia numa sessão plenária.
        cabecalho   => Um dicionário contendo informações para o Cabeçalho do relatório, incluindo a imagem.
        rodapé      => Uma lista contendo informações para o Rodapé do relatório.
    """

    arquivoPdf = str(int(time.time() * 100)) + ".pdf"

    tmp = ''
    tmp += '<?xml version="1.0" encoding="utf-8" standalone="no" ?>\n'
    tmp += '<!DOCTYPE document SYSTEM "rml_1_0.dtd">\n'
    tmp += '<document filename="relatorio.pdf">\n'
    tmp += '\t<template pageSize="(21cm, 29.7cm)" title="Relatorio de Materias" author="Interlegis" allowSplitting="20">\n'
    tmp += '\t\t<pageTemplate id="first">\n'
    tmp += '\t\t\t<pageGraphics>\n'
    tmp += cabecalho(dic_cabecalho, dat_ordem, imagem)
    tmp += rodape(lst_rodape)
    tmp += '\t\t\t</pageGraphics>\n'
    tmp += '\t\t\t<frame id="first" x1="2cm" y1="4cm" width="17cm" height="21cm"/>\n'
    tmp += '\t\t</pageTemplate>\n'
    tmp += '\t</template>\n'
    tmp += paraStyle()
    #   tmp+=splen(lst_splen)
    tmp += pauta(lst_splen, lst_pauta)
    tmp += '</document>\n'
    tmp_pdf = parseString(tmp)

    return tmp_pdf
Example #9
0
    def generate_pdf(self, data, template, save_path):
        """
            从二进制流中创建PDF并返回
            @param data  渲染XML的数据字典
            @param template 需要渲染的XML文件地址(全路径)
            @param save_file PDF文件保存的地址(全路径)
        """

        if save_path and not os.path.exists(save_path):
            file_path_array = save_path.split("/")
            save_file_dir = file_path_array[:-1]

            if not os.path.exists("/".join(save_file_dir)):
                os.makedirs("/".join(save_file_dir))

        # 读取模板文件
        empty_template = preppy.getModule(template)

        # 渲染模板文件
        render_data = {'data': data, 'static': self.statics_dir}

        # 渲染PDF页面
        render_rml = empty_template.getOutput(render_data)

        # 生成PDF
        binary_pdf = trml2pdf.parseString(render_rml)

        if save_path:
            # 保存PDF
            open(save_path, 'wb').write(binary_pdf)

        return binary_pdf
Example #10
0
def principal(sessao,imagem,data,lst_materias,dic_cabecalho,lst_rodape,dic_filtro={}):
    """Funcao pricipal que gera a estrutura global do arquivo rml"""

    arquivoPdf=str(int(time.time()*100))+".pdf"

    tmp_data=''
    tmp_data+='<?xml version="1.0" encoding="utf-8" standalone="no" ?>\n'
    tmp_data+='<!DOCTYPE document SYSTEM "rml_1_0.dtd">\n'
    tmp_data+='<document filename="relatorio.pdf">\n'
    tmp_data+='\t<template pageSize="(21cm, 29.7cm)" title="Relatório de Matérias" author="OpenLegis" allowSplitting="20">\n'
    tmp_data+='\t\t<pageTemplate id="first">\n'
    tmp_data+='\t\t\t<pageGraphics>\n'
    tmp_data+=cabecalho(dic_cabecalho,imagem)
    tmp_data+=rodape(lst_rodape)
    tmp_data+='\t\t\t</pageGraphics>\n'
    tmp_data+='\t\t\t<frame id="first" x1="3cm" y1="2cm" width="16cm" height="23cm"/>\n'
    tmp_data+='\t\t</pageTemplate>\n'
    tmp_data+='\t</template>\n'
    tmp_data+=paraStyle()
    tmp_data+=materias(lst_materias)
    tmp_data+='</document>\n'
    tmp_pdf=parseString(tmp_data)

    if hasattr(context.temp_folder,arquivoPdf):
        context.temp_folder.manage_delObjects(ids=arquivoPdf)
    context.temp_folder.manage_addFile(arquivoPdf)
    arq=context.temp_folder[arquivoPdf]
    arq.manage_edit(title='Arquivo PDF temporário.',filedata=tmp_pdf,content_type='application/pdf')

    return "/temp_folder/"+arquivoPdf
def principal(cabecalho, rodape, sessao, imagem, inf_basicas_dic,lst_presidente):
    """
    """

    arquivoPdf=str(int(time.time()*100))+".pdf"

    tmp=''
    tmp+='<?xml version="1.0" encoding="utf-8" standalone="no" ?>\n'
    tmp+='<!DOCTYPE document SYSTEM "rml_1_0.dtd">\n'
    tmp+='<document filename="relatorio.pdf">\n'
    tmp+='\t<template pageSize="(21cm, 29.7cm)" title="Sessao Plenaria" author="OpenLegis" allowSplitting="20">\n'
    tmp+='\t\t<pageTemplate id="first">\n'
    tmp+='\t\t\t<pageGraphics>\n'
    tmp+='\t\t\t</pageGraphics>\n'
    tmp+='\t\t\t<frame id="first" x1="2.5cm" y1="1.5cm" width="17cm" height="26cm"/>\n'
    tmp+='\t\t</pageTemplate>\n'
    tmp+='\t</template>\n'
    tmp+=paraStyle()
    tmp+=inf_basicas(inf_basicas_dic)
    tmp+=expedientes(lst_expedientes)
    tmp+=oradores_expediente(lst_oradores_expediente)
    tmp+=presidente(lst_presidente)
    tmp+='\t</document>\n'
    tmp_pdf=parseString(tmp)
    
    if hasattr(context.temp_folder,arquivoPdf):
        context.temp_folder.manage_delObjects(ids=arquivoPdf)
    context.temp_folder.manage_addFile(arquivoPdf)
    arq=context.temp_folder[arquivoPdf]
    arq.manage_edit(title='Arquivo PDF temporario.',filedata=tmp_pdf,content_type='application/pdf')

    return "/temp_folder/"+arquivoPdf
Example #12
0
def principal(imagem, lst_materias, dic_cabecalho, lst_rodape):
    """Funcao pricipal que gera a estrutura global do arquivo rml"""

#	if sessao:
#		arquivoPdf=sessao+".pdf"
#	else:
#		arquivoPdf=str(int(time.time()*100))+".pdf"
    arquivoPdf = str(int(time.time() * 100)) + ".pdf"

    tmp_data = ''
    tmp_data += '<?xml version="1.0" encoding="utf-8" standalone="no" ?>\n'
    tmp_data += '<!DOCTYPE document SYSTEM "rml_1_0.dtd">\n'
    tmp_data += '<document filename="relatorio.pdf">\n'
    tmp_data += '\t<template pageSize="(21cm, 29.7cm)" title="Relatorio de Materias" author="Interlegis" allowSplitting="20">\n'
    tmp_data += '\t\t<pageTemplate id="first">\n'
    tmp_data += '\t\t\t<pageGraphics>\n'
    tmp_data += cabecalho(dic_cabecalho, imagem)
    tmp_data += rodape(lst_rodape)
    tmp_data += '\t\t\t</pageGraphics>\n'
    tmp_data += '\t\t\t<frame id="first" x1="2cm" y1="4cm" width="17cm" height="21cm"/>\n'
    tmp_data += '\t\t</pageTemplate>\n'
    tmp_data += '\t</template>\n'
    tmp_data += paraStyle()
    tmp_data += materias(lst_materias)
    tmp_data += '</document>\n'
    tmp_pdf = parseString(tmp_data)

    return tmp_pdf
def principal(cabecalho, rodape, sessao, imagem, inf_basicas_dic):
    """
    """

    arquivoPdf=str(int(time.time()*100))+".pdf"

    tmp=''
    tmp+='<?xml version="1.0" encoding="utf-8" standalone="no" ?>\n'
    tmp+='<!DOCTYPE document SYSTEM "rml_1_0.dtd">\n'
    tmp+='<document filename="relatorio.pdf">\n'
    tmp+='\t<template pageSize="(21cm, 29.7cm)" title="Pauta da Sessao" author="OpenLegis" allowSplitting="20">\n'
    tmp+='\t\t<pageTemplate id="first">\n'
    tmp+='\t\t\t<pageGraphics>\n'
    tmp+=cabecalho(inf_basicas_dic,imagem)
    tmp+=rodape(rodape_dic)
    tmp+='\t\t\t</pageGraphics>\n'
    tmp+='\t\t\t<frame id="first" x1="2cm" y1="4cm" width="17cm" height="20.5cm"/>\n'
    tmp+='\t\t</pageTemplate>\n'
    tmp+='\t</template>\n'
    tmp+=paraStyle()
    tmp+='\t<story>\n'
    tmp+=inf_basicas(inf_basicas_dic)
    tmp+=expediente_materia(lst_expediente_materia)
    tmp+=votacao(lst_votacao)
    tmp+='\t</story>\n'
    tmp+='</document>\n'
    tmp_pdf=parseString(tmp)

    if hasattr(context.temp_folder,arquivoPdf):
        context.temp_folder.manage_delObjects(ids=arquivoPdf)
    context.temp_folder.manage_addFile(arquivoPdf)
    arq=context.temp_folder[arquivoPdf]
    arq.manage_edit(title='Arquivo PDF temporario.',filedata=tmp_pdf,content_type='application/pdf')

    return "/temp_folder/"+arquivoPdf
def principal(cabecalho_dic, rodape_dic, sessao, imagem, inf_basicas_dic,
              lst_expediente_materia, lst_votacao):
    """
    """

    arquivoPdf = str(int(time.time() * 100)) + ".pdf"

    tmp = ''
    tmp += '<?xml version="1.0" encoding="utf-8" standalone="no" ?>\n'
    tmp += '<!DOCTYPE document SYSTEM "rml_1_0.dtd">\n'
    tmp += '<document filename="relatorio.pdf">\n'
    tmp += '\t<template pageSize="(21cm, 29.7cm)" title="Pauta da Sessao Plenaria" author="Interlegis" allowSplitting="20">\n'
    tmp += '\t\t<pageTemplate id="first">\n'
    tmp += '\t\t\t<pageGraphics>\n'
    tmp += cabecalho(inf_basicas_dic, imagem)
    tmp += rodape(rodape_dic)
    tmp += '\t\t\t</pageGraphics>\n'
    tmp += '\t\t\t<frame id="first" x1="2cm" y1="4cm" width="17cm" height="20.5cm"/>\n'
    tmp += '\t\t</pageTemplate>\n'
    tmp += '\t</template>\n'
    tmp += paraStyle()
    tmp += '\t<story>\n'
    tmp += inf_basicas(inf_basicas_dic)
    tmp += expediente_materia(lst_expediente_materia)
    tmp += votacao(lst_votacao)
    tmp += '\t</story>\n'
    tmp += '</document>\n'

    tmp_pdf = parseString(tmp)

    return tmp_pdf
Example #15
0
def displayDoc(request, id, doc):
    import trml2pdf
    # Create the HttpResponse object with the appropriate PDF headers for an invoice or a packing slip
    order = get_object_or_404(Order, pk=id)
    shopDetails = Config.objects.get_current()
    filename_prefix = shopDetails.site.domain
    if doc == "invoice":
        filename = "%s-invoice.pdf" % filename_prefix
        template = "invoice.rml"
    elif doc == "packingslip":
        filename = "%s-packingslip.pdf" % filename_prefix
        template = "packing-slip.rml"
    elif doc == "shippinglabel":
        filename = "%s-shippinglabel.pdf" % filename_prefix
        template = "shipping-label.rml"
    else:
        return HttpResponseRedirect('/admin')
    response = HttpResponse(mimetype='application/pdf')
    if config_value('SHIPPING','DOWNLOAD_PDFS'):
        response['Content-Disposition'] = 'attachment; filename=%s' % filename
    icon_uri = config_value('SHOP', 'LOGO_URI')
    t = loader.get_template(os.path.join('shop/pdf', template))
    c = Context({
                'filename' : filename,
                'iconURI' : icon_uri,
                'shopDetails' : shopDetails,
                'order' : order,
                'default_view_tax': config_value('TAX','DEFAULT_VIEW_TAX')
                })
    pdf = trml2pdf.parseString(smart_str(t.render(c)))
    response.write(pdf)
    return response
Example #16
0
def displayDoc(request, id, doc):
    # Create the HttpResponse object with the appropriate PDF headers
    # for an invoice or a packing slip
    order = get_object_or_404(Order, pk=id)
    shopDetails = Config.objects.get_current()
    filename_prefix = Site.objects.get_current().domain
    if doc == "invoice":
        filename = "%s-invoice.pdf" % filename_prefix
        template = "invoice.rml"
    elif doc == "packingslip":
        filename = "%s-packingslip.pdf" % filename_prefix
        template = "packing-slip.rml"
    elif doc == "shippinglabel":
        filename = "%s-shippinglabel.pdf" % filename_prefix
        template = "shipping-label.rml"
    else:
        return HttpResponseRedirect("/admin")
    response = HttpResponse(mimetype="application/pdf")
    response["Content-Disposition"] = "attachment; filename=%s" % filename
    icon_uri = config_value("SHOP", "LOGO_URI")
    t = loader.get_template(os.path.join("pdf", template))
    c = Context(
        {
            "filename": filename,
            "iconURI": icon_uri,
            "shopDetails": shopDetails,
            "order": order,
        }
    )
    pdf = trml2pdf.parseString(smart_str(t.render(c)))
    response.write(pdf)
    return response
Example #17
0
def principal(sessao, linha1, linha2, lst_destinatarios):
    """Funcao pricipal que gera a estrutura global do arquivo rml"""

    arquivoPdf = str(int(time.time() * 100)) + ".pdf"

    tmp_data = ''
    tmp_data += '<?xml version="1.0" encoding="utf-8" standalone="no" ?>\n'
    tmp_data += '<!DOCTYPE document SYSTEM "rml_1_0.dtd">\n'
    tmp_data += '<document filename="envelopes.pdf">\n'
    tmp_data += '\t<template pageSize="(21cm, 29.7cm)" title="Envelopes" author="OpenLegis" allowSplitting="20" rightMargin="3mm" showBoundary="0">\n'
    tmp_data += '\t\t<pageTemplate id="main">\n'
    tmp_data += '\t\t<pageGraphics>\n'
    tmp_data += '\t\t</pageGraphics>\n'
    tmp_data += '\t\t\t<frame id="main" x1="3cm" y1="5cm" width="15cm" height="13cm"/>\n'
    tmp_data += '\t\t</pageTemplate>\n'
    tmp_data += '\t</template>\n'
    tmp_data += paraStyle()
    tmp_data += destinatarios(lst_destinatarios)
    tmp_data += '</document>\n'
    tmp_pdf = parseString(tmp_data)

    if hasattr(context.temp_folder, arquivoPdf):
        context.temp_folder.manage_delObjects(ids=arquivoPdf)
    context.temp_folder.manage_addFile(arquivoPdf)
    arq = context.temp_folder[arquivoPdf]
    arq.manage_edit(title='Arquivo PDF temporário.',
                    filedata=tmp_pdf,
                    content_type='application/pdf')

    return "/temp_folder/" + arquivoPdf
Example #18
0
def displayDoc(request, id, doc):
    # Create the HttpResponse object with the appropriate PDF headers for an invoice or a packing slip
    order = get_object_or_404(Order, pk=id)
    shopDetails = Config.objects.get_current()
    filename_prefix = shopDetails.site.domain
    if doc == "invoice":
        filename = "%s-invoice.pdf" % filename_prefix
        template = "invoice.rml"
    elif doc == "packingslip":
        filename = "%s-packingslip.pdf" % filename_prefix
        template = "packing-slip.rml"
    elif doc == "shippinglabel":
        filename = "%s-shippinglabel.pdf" % filename_prefix
        template = "shipping-label.rml"
    else:
        return HttpResponseRedirect("/admin")
    response = HttpResponse(mimetype="application/pdf")
    response["Content-Disposition"] = "attachment; filename=%s" % filename
    icon_uri = config_value("SHOP", "LOGO_URI")
    t = loader.get_template(os.path.join("pdf", template))
    c = Context(
        {
            "filename": filename,
            "iconURI": icon_uri,
            "shopDetails": shopDetails,
            "order": order,
        }
    )
    pdf = trml2pdf.parseString(smart_str(t.render(c)))
    response.write(pdf)
    return response
Example #19
0
def principal(cabecalho_dic, rodape_dic, imagem, sessao, inf_basicas_dic, lst_mesa, lst_presenca_sessao, lst_expedientes, lst_expediente_materia, lst_oradores_expediente, lst_presenca_ordem_dia, lst_votacao, lst_oradores):
    """
    """
    arquivoPdf = str(int(time.time() * 100)) + ".pdf"

    tmp = ''
    tmp += '<?xml version="1.0" encoding="utf-8" standalone="no" ?>\n'
    tmp += '<!DOCTYPE document SYSTEM "rml_1_0.dtd">\n'
    tmp += '<document filename="relatorio.pdf">\n'
    tmp += '\t<template pageSize="(21cm, 29.7cm)" title="Sessao Plenaria" author="Interlegis" allowSplitting="20">\n'
    tmp += '\t\t<pageTemplate id="first">\n'
    tmp += '\t\t\t<pageGraphics>\n'
    tmp += cabecalho(inf_basicas_dic, imagem)
    tmp += rodape(rodape_dic)
    tmp += '\t\t\t</pageGraphics>\n'
    tmp += '\t\t\t<frame id="first" x1="2cm" y1="4cm" width="17cm" height="20.5cm"/>\n'
    tmp += '\t\t</pageTemplate>\n'
    tmp += '\t</template>\n'
    tmp += paraStyle()
    tmp += '\t<story>\n'
    tmp += inf_basicas(inf_basicas_dic)
    tmp += mesa(lst_mesa)
    tmp += presenca(lst_presenca_sessao)
    tmp += expedientes(lst_expedientes)
    tmp += expediente_materia(lst_expediente_materia)
    tmp += oradores_expediente(lst_oradores_expediente)
    tmp += presenca_ordem_dia(lst_presenca_ordem_dia)
    tmp += votacao(lst_votacao)
    tmp += oradores(lst_oradores)
    tmp += '\t</story>\n'
    tmp += '</document>\n'
    tmp_pdf = parseString(tmp)
    return tmp_pdf
Example #20
0
    def write_pdf(self, output):
        # get plain pdf from rml
        template = select_template([
            'leprikon/{}/{}.rml'.format(self.pdf_export, self.subject.subject_type.slug),
            'leprikon/{}/{}.rml'.format(self.pdf_export, self.subject.subject_type.subject_type),
            'leprikon/{}/subject.rml'.format(self.pdf_export),
        ])
        rml_content = template.render({
            'object': self,
            'site': LeprikonSite.objects.get_current(),
        })
        pdf_content = trml2pdf.parseString(rml_content.encode('utf-8'))

        # merge with background
        if self.print_setup.background:
            template_pdf = PdfFileReader(self.print_setup.background.file)
            registration_pdf = PdfFileReader(BytesIO(pdf_content))
            writer = PdfFileWriter()
            # merge pages from both template and registration
            for i in range(registration_pdf.getNumPages()):
                if i < template_pdf.getNumPages():
                    page = template_pdf.getPage(i)
                    page.mergePage(registration_pdf.getPage(i))
                else:
                    page = registration_pdf.getPage(i)
                writer.addPage(page)
            # write result to output
            writer.write(output)
        else:
            # write basic pdf registration to response
            output.write(pdf_content)
        return output
Example #21
0
def principal(imagem, lst_materias, dic_cabecalho, lst_rodape):
	"""Funcao pricipal que gera a estrutura global do arquivo rml"""

#	if sessao:
#		arquivoPdf=sessao+".pdf"
#	else:
#		arquivoPdf=str(int(time.time()*100))+".pdf"
	arquivoPdf = str(int(time.time() * 100)) + ".pdf"

	tmp_data = ''
	tmp_data += '<?xml version="1.0" encoding="utf-8" standalone="no" ?>\n'
	tmp_data += '<!DOCTYPE document SYSTEM "rml_1_0.dtd">\n'
	tmp_data += '<document filename="relatorio.pdf">\n'
	tmp_data += '\t<template pageSize="(21cm, 29.7cm)" title="Relatorio de Materias" author="Interlegis" allowSplitting="20">\n'
	tmp_data += '\t\t<pageTemplate id="first">\n'
	tmp_data += '\t\t\t<pageGraphics>\n'
	tmp_data += cabecalho(dic_cabecalho, imagem)
	tmp_data += rodape(lst_rodape)
	tmp_data += '\t\t\t</pageGraphics>\n'
	tmp_data += '\t\t\t<frame id="first" x1="2cm" y1="4cm" width="17cm" height="21cm"/>\n'
	tmp_data += '\t\t</pageTemplate>\n'
	tmp_data += '\t</template>\n'
	tmp_data += paraStyle()
	tmp_data += materias(lst_materias)
	tmp_data += '</document>\n'
	tmp_pdf = parseString(tmp_data)
	
	return tmp_pdf
def principal(sessao,linha1,linha2,lst_destinatarios):
    """Funcao pricipal que gera a estrutura global do arquivo rml"""

    arquivoPdf=str(int(time.time()*100))+".pdf"

    tmp_data=''
    tmp_data+='<?xml version="1.0" encoding="utf-8" standalone="no" ?>\n'
    tmp_data+='<!DOCTYPE document SYSTEM "rml_1_0.dtd">\n'
    tmp_data+='<document filename="envelopes.pdf">\n'
    tmp_data+='\t<template pageSize="(21cm, 29.7cm)" title="Envelopes" author="OpenLegis" allowSplitting="20" rightMargin="3mm" showBoundary="0">\n'
    tmp_data+='\t\t<pageTemplate id="main">\n'
    tmp_data+='\t\t<pageGraphics>\n'
    tmp_data+='\t\t</pageGraphics>\n'
    tmp_data+='\t\t\t<frame id="first" x1="3cm" y1="5cm" width="15cm" height="14cm"/>\n'
    tmp_data+='\t\t</pageTemplate>\n'
    tmp_data+='\t</template>\n'
    tmp_data+=paraStyle()
    tmp_data+=destinatarios(lst_destinatarios)
    tmp_data+='</document>\n'
    tmp_pdf=parseString(tmp_data)

    if hasattr(context.temp_folder,arquivoPdf):
        context.temp_folder.manage_delObjects(ids=arquivoPdf)
    context.temp_folder.manage_addFile(arquivoPdf)
    arq=context.temp_folder[arquivoPdf]
    arq.manage_edit(title='Arquivo PDF temporário.',filedata=tmp_pdf,content_type='application/pdf')

    return "/temp_folder/"+arquivoPdf
Example #23
0
def displayDoc(request, id, doc):
    # Create the HttpResponse object with the appropriate PDF headers for an invoice or a packing slip
    order = get_object_or_404(Order, pk=id)

    if doc == "invoice":
        filename = "mystore-invoice.pdf"
        template = "invoice.rml"
    elif doc == "packingslip":
        filename = "mystore-packingslip.pdf"
        template = "packing-slip.rml"
    elif doc == "shippinglabel":
        filename = "mystore-shippinglabel.pdf"
        template = "shipping-label.rml"
    else:
        return HttpResponseRedirect('/admin')
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=%s' % filename
    shopDetails = Config.get_shop_config()
    t = loader.get_template('pdf/%s' % template)
    templatedir = os.path.normpath(settings.TEMPLATE_DIRS[0])
    c = Context({
                'filename' : filename,
                'templateDir' : templatedir,
                'shopDetails' : shopDetails,
                'order' : order
                })
    pdf = trml2pdf.parseString(smart_str(t.render(c)))
    response.write(pdf)
    return response
def handler_pdf(req):

    # Check for existance of RML source file.

    path = os.path.splitext(req.filename)[0] + ".rml"

    if not os.path.exists(path):
        return apache.DECLINED

    # Create the document.

    import trml2pdf

    content = trml2pdf.parseString(file(path, 'r').read())

    # Return the rendered page content.

    req.content_type = "application/pdf"
    req.headers_out['Content-Length'] = str(len(content))

    # Internet Explorer chokes on this with PDFs.
    #req.headers_out['Pragma'] = 'no-cache'
    #req.headers_out['Cache-Control'] = 'no-cache'
    #req.headers_out['Expires'] = '-1'

    req.send_http_header()
    req.write(content)

    return apache.OK
Example #25
0
 def _run_all_examples(self):
     for name in os.listdir('.'):
         if name.endswith(".rml"):
             path = name  # '{}/{}'.format(EXAMPLES_DIR, name)
             print('running: {}'.format(path))
             output = trml2pdf.parseString(open(path, "r").read())
             self.assertIsNotNone(output)
Example #26
0
def principal(imagem, lst_splen, lst_pauta, dic_cabecalho, lst_rodape):
    """Funcao principal que gera a estrutura global do arquivo rml contendo o relatorio de uma ordem do dia.
    ordem_dia_[data da ordem do dia do relatório].pdf
    Retorna:
    Parâmetros:
    dat_ordem       => A data da ordem do dia.
        splen       => Uma lista de dicionários contendo as sessões plenárias do dia.
        pauta       => Uma lista de dicionários contendo a pauta da ordem do dia numa sessão plenária.
        cabecalho   => Um dicionário contendo informações para o Cabeçalho do relatório, incluindo a imagem.
        rodapé      => Uma lista contendo informações para o Rodapé do relatório.
    """

    arquivoPdf = str(int(time.time() * 100)) + ".pdf"

    tmp = ''
    tmp += '<?xml version="1.0" encoding="utf-8" standalone="no" ?>\n'
    tmp += '<!DOCTYPE document SYSTEM "rml_1_0.dtd">\n'
    tmp += '<document filename="relatorio.pdf">\n'
    tmp += '\t<template pageSize="(21cm, 29.7cm)" title="Relatorio de Materias" author="Interlegis" allowSplitting="20">\n'
    tmp += '\t\t<pageTemplate id="first">\n'
    tmp += '\t\t\t<pageGraphics>\n'
    tmp += cabecalho(dic_cabecalho, dat_ordem, imagem)
    tmp += rodape(lst_rodape)
    tmp += '\t\t\t</pageGraphics>\n'
    tmp += '\t\t\t<frame id="first" x1="2cm" y1="4cm" width="17cm" height="21cm"/>\n'
    tmp += '\t\t</pageTemplate>\n'
    tmp += '\t</template>\n'
    tmp += paraStyle()
#   tmp+=splen(lst_splen)
    tmp += pauta(lst_splen, lst_pauta)
    tmp += '</document>\n'
    tmp_pdf = parseString(tmp)

    return tmp_pdf
Example #27
0
def principal(sessao,imagem,data,lst_materias,dic_cabecalho,lst_rodape,dic_filtro={}):
    """Funcao principal que gera a estrutura global do arquivo rml"""

    arquivoPdf=str(int(time.time()*100))+".pdf"

    tmp_data=''
    tmp_data+='<?xml version="1.0" encoding="utf-8" standalone="no" ?>\n'
    tmp_data+='<!DOCTYPE document SYSTEM "rml_1_0.dtd">\n'
    tmp_data+='<document filename="relatorio.pdf">\n'
    tmp_data+='\t<template pageSize="(21cm, 29.7cm)" title="Relatorio de Materias" author="Interlegis" allowSplitting="20">\n'
    tmp_data+='\t\t<pageTemplate id="first">\n'
    tmp_data+='\t\t\t<pageGraphics>\n'
    tmp_data+=cabecalho(dic_cabecalho,imagem)
    tmp_data+=rodape(lst_rodape)
    tmp_data+='\t\t\t</pageGraphics>\n'
    tmp_data+='\t\t\t<frame id="first" x1="2cm" y1="4cm" width="17cm" height="21cm"/>\n'
    tmp_data+='\t\t</pageTemplate>\n'
    tmp_data+='\t</template>\n'
    tmp_data+=paraStyle()
    tmp_data+=materias(lst_materias)
    tmp_data+='</document>\n'
    tmp_pdf=parseString(tmp_data)

    if hasattr(context.temp_folder,arquivoPdf):
        context.temp_folder.manage_delObjects(ids=arquivoPdf)
    context.temp_folder.manage_addFile(arquivoPdf)
    arq=context.temp_folder[arquivoPdf]
    arq.manage_edit(title='Arquivo PDF temporário.',filedata=tmp_pdf,content_type='application/pdf')

    return "/temp_folder/"+arquivoPdf
def principal(sessao,imagem,data,lst_protocolos,dic_cabecalho,lst_rodape,dic_filtro={}):
    """Funcao pricipal que gera a estrutura global do arquivo rml"""

    arquivoPdf=str(int(time.time()*100))+".pdf"

    tmp_data=''
    tmp_data+='<?xml version="1.0" encoding="utf-8" standalone="no" ?>\n'
    tmp_data+='<!DOCTYPE document SYSTEM "rml_1_0.dtd">\n'
    tmp_data+='<document filename="etiquetas.pdf">\n'
    tmp_data+='\t<template pageSize="(62mm, 29mm)" title="Etiquetas de Protocolo" author="Luciano De Fazio" allowSplitting="20">\n'
    tmp_data+='\t\t<pageTemplate id="first">\n'
    tmp_data+='\t\t\t<pageGraphics>\n'
    tmp_data+='\t\t\t<frame id="first" x1="0.03cm" y1="0cm" width="61mm" height="29mm"/>\n'
    tmp_data+='\t\t\t</pageGraphics>\n'
    tmp_data+='\t\t</pageTemplate>\n'
    tmp_data+='\t</template>\n'
    tmp_data+=paraStyle()
    tmp_data+=protocolos(lst_protocolos)
    tmp_data+='</document>\n'
    tmp_pdf=parseString(tmp_data)

    if hasattr(context.temp_folder,arquivoPdf):
        context.temp_folder.manage_delObjects(ids=arquivoPdf)
    context.temp_folder.manage_addFile(arquivoPdf)
    arq=context.temp_folder[arquivoPdf]
    arq.manage_edit(title='Arquivo PDF temporário.',filedata=tmp_pdf,content_type='application/pdf')

    return "/temp_folder/"+arquivoPdf
Example #29
0
def main():
    if len(sys.argv) == 1 or sys.argv[1] == '--help':
        print(__help)
        sys.exit(0)
    else:
        # print(parseString(open(sys.argv[1], 'r').read()))
        os.write(1, trml2pdf.parseString(open(sys.argv[1], 'rt').read()))
Example #30
0
 def _run_all_examples(self):
     for name in os.listdir('.'):
         if name.endswith(".rml"):
             path = name  # '{}/{}'.format(EXAMPLES_DIR, name)
             print('running: {}'.format(path))
             output = trml2pdf.parseString(open(path, "r").read())
             self.assertIsNotNone(output)
Example #31
0
def get_documento_presupuesto(pres, cliente, direccion):
    tmpl_path = settings.DOCUMENT_TMPL
    response = BytesIO()
    file_rml = os.path.join(tmpl_path, "documento_presupuesto.xml")
    total = get_total_presupuesto(pres.pk)
    data = {
        'title': "Presupuesto num %s" % pres.id,
        "producto": pres.producto,
        "fecha": pres.fecha,
        "entrega": pres.entrega,
        "total_cobro": "{0:.2f}".format(float(total) - float(pres.entrega)),
        "num_pres": pres.id,
        "sn_imei": pres.producto.ns_imei,
        "nombre": cliente.nombre_completo,
        "domicilio": direccion,
        "telefono": cliente.telefono,
        "DNI": cliente.DNI,
        "detalle": pres.notas_cliente,
        "lineas": LineasPresupuesto.objects.filter(presupuesto__pk=pres.pk),
        "total": total,
        "firma_cliente": pres.firma,
        "firma_freak": ConfigSite.objects.all()[0].firma_tienda
    }
    template = get_template(file_rml)
    #context = Context(data)
    xmlstring = template.render(data)
    pdfstr = trml2pdf.parseString(xmlstring.encode("utf-8"))
    response.write(pdfstr)
    return response
Example #32
0
def displayDoc(request, id, doc):
    # Create the HttpResponse object with the appropriate PDF headers for an invoice or a packing slip
    order = get_object_or_404(Order, pk=id)

    if doc == "invoice":
        filename = "mystore-invoice.pdf"
        template = "invoice.rml"
    elif doc == "packingslip":
        filename = "mystore-packingslip.pdf"
        template = "packing-slip.rml"
    elif doc == "shippinglabel":
        filename = "mystore-shippinglabel.pdf"
        template = "shipping-label.rml"
    else:
        return HttpResponseRedirect('/admin')
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=%s' % filename
    shopDetails = Config.get_shop_config()
    t = loader.get_template('pdf/%s' % template)
    templatedir = os.path.normpath(settings.TEMPLATE_DIRS[0])
    c = Context({
        'filename': filename,
        'templateDir': templatedir,
        'shopDetails': shopDetails,
        'order': order
    })
    pdf = trml2pdf.parseString(smart_str(t.render(c)))
    response.write(pdf)
    return response
Example #33
0
 def create_rml_pdf(self, rml_file):
     output = '%s.pdf' % (os.path.splitext(rml_file)[0], )
     with open(rml_file, 'rb') as fd:
         outputfile = trml2pdf.parseString(fd.read(), output)
     try:
         os.unlink(rml_file)
     except EnvironmentError:
         pass
     return outputfile
Example #34
0
    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        context.setdefault('filename', 'report.pdf')

        rml = render_to_string(self.get_template_name(), context)
        print(type(rml))
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = ('filename="report.pdf"')
        response.write(trml2pdf.parseString(rml))
        return response
Example #35
0
 def get(self, request, *args, **kwargs):
     response = HttpResponse(content_type='application/pdf')
     response['Content-Disposition'] = ('attachment; filename="%s"' %
                                        self.get_output_filename())
     rml = render_to_string(self.get_template_names(),
                            self.get_context_data())
     if isinstance(rml, unicode):
         rml = rml.encode('UTF-8')
     response.write(trml2pdf.parseString(rml))
     return response
Example #36
0
 def get(self, request, *args, **kwargs):
     response = HttpResponse(content_type='application/pdf')
     response['Content-Disposition'] = ('attachment; filename="%s"'
                                        % self.get_output_filename())
     rml = render_to_string(self.get_template_names(),
                            self.get_context_data())
     if isinstance(rml, unicode):
         rml = rml.encode('UTF-8')
     response.write(trml2pdf.parseString(rml))
     return response
Example #37
0
def principal(imagem,
              dic_rodape,
              dic_inf_basicas,
              dic_orig_externa,
              lst_mat_anexadas,
              lst_autoria,
              lst_des_iniciais,
              dic_tramitacoes,
              lst_relatorias,
              lst_numeracoes,
              lst_leg_citadas,
              lst_acessorios,
              sessao=''):
    """
    Função principal responsável por chamar as funções que irão gerar o código rml apropriado
    """

    arquivoPdf = str(int(time.time() * 100)) + ".pdf"

    tmp = ''
    tmp += '<?xml version="1.0" encoding="utf-8" standalone="no" ?>\n'
    tmp += '<!DOCTYPE document SYSTEM "rml_1_0.dtd">\n'
    tmp += '<document filename="relatorio.pdf">\n'
    tmp += '\t<template pageSize="(21cm, 29.7cm)" title="Relatorio de Materias" author="OpenLegis" allowSplitting="20">\n'
    tmp += '\t\t<pageTemplate id="first">\n'
    tmp += '\t\t\t<pageGraphics>\n'
    tmp += cabecalho(dic_inf_basicas, imagem)
    tmp += rodape(dic_rodape)
    tmp += '\t\t\t</pageGraphics>\n'
    tmp += '\t\t\t<frame id="first" x1="3cm" y1="2.6cm" width="16cm" height="23cm"/>\n'
    tmp += '\t\t</pageTemplate>\n'
    tmp += '\t</template>\n'
    tmp += paraStyle()
    tmp += '\t<story>\n'
    tmp += inf_basicas(dic_inf_basicas)
    tmp += autoria(lst_autoria)
    tmp += orig_externa(dic_orig_externa)
    tmp += documentos_acessorios(lst_acessorios)
    tmp += mat_anexadas(lst_mat_anexadas)
    tmp += relatorias(lst_relatorias)
    tmp += tramitacoes(lst_tramitacoes)
    tmp += '\t</story>\n'
    tmp += '</document>\n'
    tmp_pdf = parseString(tmp)

    if hasattr(context.temp_folder, arquivoPdf):
        context.temp_folder.manage_delObjects(ids=arquivoPdf)
    context.temp_folder.manage_addFile(arquivoPdf)
    arq = context.temp_folder[arquivoPdf]
    arq.manage_edit(title='Arquivo PDF temporário.',
                    filedata=tmp_pdf,
                    content_type='application/pdf')

    return "/temp_folder/" + arquivoPdf
Example #38
0
def gen_pdf(tmpl, ctx):
    if len(settings.TEMPLATE_DIRS) > 0:
        ctx['img_path'] = "%s/images/" % (settings.TEMPLATE_DIRS[0])
    t = loader.get_template(tmpl)
    buffer = t.render(Context(ctx)).encode('utf-8')
    # no comment
    buffer = buffer.replace('é', 'e')
    buffer = buffer.replace('è', 'e')
    buffer = buffer.replace('ô', 'o')
    buffer = buffer.replace('ä', 'a')
    buffer = buffer.replace('ü', 'u')
    return trml2pdf.parseString(buffer)
Example #39
0
 def _run_all_examples(self):
     for name in os.listdir('.'):
         if name.endswith(".rml"):
             path = name  # '{}/{}'.format(INPUT_DIR, name)
             print('running: {}'.format(path))
             with open(path, "r") as f:
                 output = parseString(f.read())
             self.assertIsNotNone(output)
             with open(
                     os.path.join(TESTS_DIR, OUTPUT_DIR, name[:-3] + "pdf"),
                     "wb") as of:
                 of.write(output)
Example #40
0
File: pdf.py Project: RMLL/resarmll
def gen_pdf(tmpl, ctx):
    if len(settings.TEMPLATE_DIRS) > 0:
        ctx['img_path'] = "%s/images/" % (settings.TEMPLATE_DIRS[0])
    t = loader.get_template(tmpl)
    buffer = t.render(Context(ctx)).encode('utf-8')
    # no comment
    buffer = buffer.replace('é', 'e')
    buffer = buffer.replace('è', 'e')
    buffer = buffer.replace('ô', 'o')
    buffer = buffer.replace('ä', 'a')
    buffer = buffer.replace('ü', 'u')
    return trml2pdf.parseString(buffer)
Example #41
0
def pdf_rml(request):
    rml_context = dict(name='RML Test')

    template = preppy.getModule('hello.rml')
    rml = template.getOutput(rml_context)
    e = trml2pdf.parseString(rml)

    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="hello.pdf"'

    response.write(e)
    return response
Example #42
0
def fax_report(request, commid=None):
    fax = Fax.objects.visible_to_user(request.user).get(comm_id=commid)
    from django.template import Template, Context, loader
    import cStringIO
    import trml2pdf

    t = loader.get_template("fax/rml/comm_report.rml")
    c = Context({"fax": fax})
    rml = t.render(c)
    buf = trml2pdf.parseString(rml)
    response = HttpResponse(mimetype="application/pdf")
    response.write(buf)
    return response
Example #43
0
def principal(imagem,
              dic_rodape,
              dic_inf_basicas,
              dic_orig_externa,
              lst_mat_anexadas,
              lst_autoria,
              lst_des_iniciais,
              dic_tramitacoes,
              lst_relatorias,
              lst_numeracoes,
              lst_leg_citadas,
              lst_acessorios,
              sessao=''):
    """
    Função principal responsável por chamar as funções que irão gerar o código rml apropriado
    """

    arquivoPdf = str(int(time.time() * 100)) + ".pdf"

    tmp = ''
    tmp += '<?xml version="1.0" encoding="utf-8" standalone="no" ?>\n'
    tmp += '<!DOCTYPE document SYSTEM "rml_1_0.dtd">\n'
    tmp += '<document filename="relatorio.pdf">\n'
    tmp += '\t<template pageSize="(21cm, 29.7cm)" title="Relatorio de Materias" author="Interlegis" allowSplitting="20">\n'
    tmp += '\t\t<pageTemplate id="first">\n'
    tmp += '\t\t\t<pageGraphics>\n'
    tmp += cabecalho(dic_inf_basicas, imagem)
    tmp += rodape(dic_rodape)
    tmp += '\t\t\t</pageGraphics>\n'
    tmp += '\t\t\t<frame id="first" x1="2cm" y1="4cm" width="17cm" height="20.5cm"/>\n'
    tmp += '\t\t</pageTemplate>\n'
    tmp += '\t</template>\n'
    tmp += paraStyle()
    tmp += '\t<story>\n'
    tmp += inf_basicas(dic_inf_basicas)
    tmp += orig_externa(dic_orig_externa)
    tmp += mat_anexadas(lst_mat_anexadas)
    tmp += autoria(lst_autoria)
    tmp += despachos_iniciais(lst_des_iniciais)
    tmp += tramitacoes(dic_tramitacoes)
    tmp += relatorias(lst_relatorias)
    tmp += numeracoes(lst_numeracoes)
    tmp += legislacoes_citadas(lst_leg_citadas)
    tmp += documentos_acessorios(lst_acessorios)
    tmp += '\t</story>\n'
    tmp += '</document>\n'
    tmp_pdf = parseString(tmp)

    return tmp_pdf
def principal(imagem, dic_rodape,dic_inf_basicas,dic_orig_externa,lst_mat_anexadas,lst_autoria,lst_des_iniciais,
              dic_tramitacoes,lst_relatorias,lst_numeracoes,lst_leg_citadas,lst_acessorios,sessao=''):
    """
    Função principal responsável por chamar as funções que irão gerar o código rml apropriado
    """

    arquivoPdf=str(int(time.time()*100))+".pdf"

    tmp=''
    tmp+='<?xml version="1.0" encoding="utf-8" standalone="no" ?>\n'
    tmp+='<!DOCTYPE document SYSTEM "rml_1_0.dtd">\n'
    tmp+='<document filename="relatorio.pdf">\n'
    tmp+='\t<template pageSize="(21cm, 29.7cm)" title="Relatorio de Materias" author="Interlegis" allowSplitting="20">\n'
    tmp+='\t\t<pageTemplate id="first">\n'
    tmp+='\t\t\t<pageGraphics>\n'
    tmp+=cabecalho(dic_inf_basicas,imagem)
    tmp+=rodape(dic_rodape)
    tmp+='\t\t\t</pageGraphics>\n'
    tmp+='\t\t\t<frame id="first" x1="2cm" y1="4cm" width="17cm" height="20.5cm"/>\n'
    tmp+='\t\t</pageTemplate>\n'
    tmp+='\t</template>\n'
    tmp+=paraStyle()
    tmp+='\t<story>\n'
    tmp+=inf_basicas(dic_inf_basicas)
    tmp+=orig_externa(dic_orig_externa)
    tmp+=mat_anexadas(lst_mat_anexadas)
    tmp+=autoria(lst_autoria)
    tmp+=despachos_iniciais(lst_des_iniciais)
    tmp+=tramitacoes(dic_tramitacoes)
    tmp+=relatorias(lst_relatorias)
    tmp+=numeracoes(lst_numeracoes)
    tmp+=legislacoes_citadas(lst_leg_citadas)
    tmp+=documentos_acessorios(lst_acessorios)
    tmp+='\t</story>\n'
    tmp+='</document>\n'
    tmp_pdf=parseString(tmp)

    if hasattr(context.temp_folder,arquivoPdf):
        context.temp_folder.manage_delObjects(ids=arquivoPdf)
    context.temp_folder.manage_addFile(arquivoPdf)
    arq=context.temp_folder[arquivoPdf]
    arq.manage_edit(title='Arquivo PDF temporário.',filedata=tmp_pdf,content_type='application/pdf')

    #   try:
    #     tmp_pdf=parseString(unicode(tmp, 'utf-8'))
    #   except:
    #     tmp_pdf=parseString(unicode(tmp, 'utf-8'))

    return "/temp_folder/"+arquivoPdf
Example #45
0
def principal(sessao,imagem,dat_ordem,lst_splen,lst_pauta,dic_cabecalho,lst_rodape):
    """Funcao principal que gera a estrutura global do arquivo rml contendo o relatorio de uma ordem do dia.
    ordem_dia_[data da ordem do dia do relatório].pdf
    Retorna:
    Parâmetros:
    dat_ordem       => A data da ordem do dia.
        splen       => Uma lista de dicionários contendo as sessões plenárias do dia.
        pauta       => Uma lista de dicionários contendo a pauta da ordem do dia numa sessão plenária.
        cabecalho   => Um dicionário contendo informações para o Cabeçalho do relatório, incluindo a imagem.
        rodapé      => Uma lista contendo informações para o Rodapé do relatório.
    """

    arquivoPdf=str(int(time.time()*100))+".pdf"

    tmp=''
    tmp+='<?xml version="1.0" encoding="utf-8" standalone="no" ?>\n'
    tmp+='<!DOCTYPE document SYSTEM "rml_1_0.dtd">\n'
    tmp+='<document filename="relatorio.pdf">\n'
    tmp+='\t<template pageSize="(21cm, 29.7cm)" title="Relatorio de Materias" author="Interlegis" allowSplitting="20">\n'
    tmp+='\t\t<pageTemplate id="first">\n'
    tmp+='\t\t\t<pageGraphics>\n'
    tmp+=cabecalho(dic_cabecalho,dat_ordem,imagem)
    tmp+=rodape(lst_rodape)
    tmp+='\t\t\t</pageGraphics>\n'
    tmp+='\t\t\t<frame id="first" x1="2cm" y1="4cm" width="17cm" height="21cm"/>\n'
    tmp+='\t\t</pageTemplate>\n'
    tmp+='\t</template>\n'
    tmp+=paraStyle()
#   tmp+=splen(lst_splen)
    tmp+=pauta(lst_splen, lst_pauta)
    tmp+='</document>\n'
    
    tmp_pdf=parseString(tmp)
    

#    try:
#        tmp_pdf=parseString(unicode(tmp, 'utf-8'))
#    except:
#        tmp_pdf=parseString(unicode(tmp, 'utf-8'))

    if hasattr(context.temp_folder,arquivoPdf):
        context.temp_folder.manage_delObjects(ids=arquivoPdf)
    context.temp_folder.manage_addFile(arquivoPdf)
    arq=context.temp_folder[arquivoPdf]
    arq.manage_edit(title='Arquivo PDF temporário.',filedata=tmp_pdf,content_type='application/pdf')

    return "/temp_folder/"+arquivoPdf
Example #46
0
def principal(sessao, imagem, dat_ordem, lst_splen, lst_pauta, dic_cabecalho,
              lst_rodape, lst_presidente):
    """Funcao principal que gera a estrutura global do arquivo rml contendo o relatorio de uma ordem do dia.
    ordem_dia_[data da ordem do dia do relatório].pdf
    Retorna:
    Parâmetros:
    dat_ordem       => A data da ordem do dia.
        splen       => Uma lista de dicionários contendo as sessões plenárias do dia.
        pauta       => Uma lista de dicionários contendo a pauta da ordem do dia numa sessão plenária.
        cabecalho   => Um dicionário contendo informações para o Cabeçalho do relatório, incluindo a imagem.
        rodapé      => Uma lista contendo informações para o Rodapé do relatório.
    """

    #arquivoTemporario=str(cod_sessao_plen)+"_pauta_sessao.pdf"
    arquivoPdf = str(cod_sessao_plen) + "_pauta_sessao.pdf"

    tmp = ''
    tmp += '<?xml version="1.0" encoding="utf-8" standalone="no" ?>\n'
    tmp += '<!DOCTYPE document SYSTEM "rml_1_0.dtd">\n'
    tmp += '<document filename="relatorio.pdf">\n'
    tmp += '\t<template pageSize="(21cm, 29.7cm)" title="Ordem do Dia" author="OpenLegis" allowSplitting="20">\n'
    tmp += '\t\t<pageTemplate id="first">\n'
    tmp += '\t\t\t<pageGraphics>\n'
    tmp += cabecalho(dic_cabecalho, dat_ordem, imagem)
    tmp += rodape(lst_rodape)
    tmp += '\t\t\t</pageGraphics>\n'
    tmp += '\t\t\t<frame id="first" x1="3cm" y1="3cm" width="16cm" height="23cm"/>\n'
    tmp += '\t\t</pageTemplate>\n'
    tmp += '\t</template>\n'
    tmp += paraStyle()
    #   tmp+=splen(lst_splen)
    tmp += pauta(lst_splen, lst_pauta)
    tmp += presidente(lst_presidente)
    tmp += '</document>\n'
    tmp_pdf = parseString(tmp)

    if hasattr(context.documentos.pauta_sessao, arquivoPdf):
        context.documentos.pauta_sessao.manage_delObjects(ids=arquivoPdf)
    context.documentos.pauta_sessao.manage_addFile(arquivoPdf)
    arq = context.documentos.pauta_sessao[arquivoPdf]
    arq.manage_edit(title='Ordem do Dia',
                    filedata=tmp_pdf,
                    content_type='application/pdf')

    return "documentos/pauta_sessao/" + arquivoPdf
def principal(sessao,imagem,dat_ordem,lst_splen,lst_pauta,dic_cabecalho,lst_rodape,lst_presidente):
    """Funcao principal que gera a estrutura global do arquivo rml contendo o relatorio de uma ordem do dia.
    ordem_dia_[data da ordem do dia do relatório].pdf
    Retorna:
    Parâmetros:
    dat_ordem       => A data da ordem do dia.
        splen       => Uma lista de dicionários contendo as sessões plenárias do dia.
        pauta       => Uma lista de dicionários contendo a pauta da ordem do dia numa sessão plenária.
        cabecalho   => Um dicionário contendo informações para o Cabeçalho do relatório, incluindo a imagem.
        rodapé      => Uma lista contendo informações para o Rodapé do relatório.
    """

    #arquivoTemporario=str(cod_sessao_plen)+"_pauta_sessao.pdf"
    arquivoPdf=str(cod_sessao_plen)+"_pauta_sessao.pdf"

    tmp=''
    tmp+='<?xml version="1.0" encoding="utf-8" standalone="no" ?>\n'
    tmp+='<!DOCTYPE document SYSTEM "rml_1_0.dtd">\n'
    tmp+='<document filename="relatorio.pdf">\n'
    tmp+='\t<template pageSize="(21cm, 29.7cm)" title="Ordem do Dia" author="OpenLegis" allowSplitting="20">\n'
    tmp+='\t\t<pageTemplate id="first">\n'
    tmp+='\t\t\t<pageGraphics>\n'
    tmp+=cabecalho(dic_cabecalho,dat_ordem,imagem)
    tmp+=rodape(lst_rodape)
    tmp+='\t\t\t</pageGraphics>\n'
    tmp+='\t\t\t<frame id="first" x1="4cm" y1="3cm" width="16cm" height="24cm"/>\n'
    tmp+='\t\t</pageTemplate>\n'
    tmp+='\t</template>\n'
    tmp+=paraStyle()
#   tmp+=splen(lst_splen)
    tmp+=pauta(lst_splen, lst_pauta)
    tmp+=presidente(lst_presidente)    
    tmp+='</document>\n'
    tmp_pdf=parseString(tmp)   

    if hasattr(context.sapl_documentos.pauta_sessao,arquivoPdf):
        context.sapl_documentos.pauta_sessao.manage_delObjects(ids=arquivoPdf)
    context.sapl_documentos.pauta_sessao.manage_addFile(arquivoPdf)
    arq=context.sapl_documentos.pauta_sessao[arquivoPdf]
    arq.manage_edit(title='Ordem do Dia',filedata=tmp_pdf,content_type='application/pdf')
   
    return "/sapl/sapl_documentos/pauta_sessao/"+arquivoPdf
Example #48
0
    def generate_binary_pdf(self, data, template):
        """
            从二进制流中创建PDF并返回
            @param data  渲染XML的数据字典
            @param template 需要渲染的XML文件地址(全路径)
        """

        # 读取模板文件
        pdf_template = preppy.getModule(template)

        # 渲染模板文件
        render_data = {'data': data, 'static': self.statics_path}

        # 渲染PDF页面
        char_rml = pdf_template.getOutput(render_data)

        # 生成PDF
        pdf_binary = trml2pdf.parseString(char_rml)

        return pdf_binary
Example #49
0
def index():
    #form = MyForm(LANGUAGES=['ru',])
    form = MyForm()
    if form.validate_on_submit():
        # template (file.rml) + data (dict) | jinja (render_template) | trml2pdf(str): str | respose
        # retvalue = render_template
        # make_response
        # add content type
        # TODO: rml template as pre-loaded string
        # 1. prepare data
        #d = __tune_data(form)
        # 2. mk rml
        #rml = render_template('uvedomlenie.rml', d = d)  # str RML(str filename, dict dict)
        # 3. mk pdf
        #pdf = trml2pdf.parseString(rml) # str
        # 4. get out
        #rsp = Response(response=pdf, mimetype='application/pdf', content_type='application/pdf')
        #return rsp
        return Response(response=trml2pdf.parseString(render_template('uvedomlenie.rml', d = __tune_data(form))), mimetype='application/pdf', content_type='application/pdf')
    return render_template('index.html', form = form)
Example #50
0
def principal(imagem, dic_rodape, inf_basicas_dic, tramitacao_dic, sessao=''):
    """
    Função principal responsável por chamar as funções que irão gerar o código rml apropriado
    """

    arquivoPdf = str(cod_tramitacao) + "_tram.pdf"
    arquivoAssinado = str(cod_tramitacao) + "_tram_signed.pdf"

    tmp = ''
    tmp += '<?xml version="1.0" encoding="utf-8" standalone="no" ?>\n'
    tmp += '<!DOCTYPE document SYSTEM "rml_1_0.dtd">\n'
    tmp += '<document filename="tramitacao.pdf">\n'
    tmp += '\t<template pageSize="(21cm, 29.7cm)" title="Tramitação de Matéria" author="OpenLegis" allowSplitting="20">\n'
    tmp += '\t\t<pageTemplate id="first">\n'
    tmp += '\t\t\t<pageGraphics>\n'
    tmp += cabecalho(inf_basicas_dic, imagem)
    tmp += rodape(dic_rodape)
    tmp += '\t\t\t</pageGraphics>\n'
    tmp += '\t\t\t<frame id="first" x1="3cm" y1="3.5cm" width="16.7cm" height="23cm"/>\n'
    tmp += '\t\t</pageTemplate>\n'
    tmp += '\t</template>\n'
    tmp += paraStyle()
    tmp += '\t<story>\n'
    tmp += tramitacao(tramitacao_dic)
    tmp += '\t</story>\n'
    tmp += '</document>\n'
    tmp_pdf = parseString(tmp)

    if hasattr(context.sapl_documentos.materia.tramitacao, arquivoPdf):
        context.sapl_documentos.materia.tramitacao.manage_delObjects(
            ids=arquivoPdf)
    if hasattr(context.sapl_documentos.materia.tramitacao, arquivoAssinado):
        context.sapl_documentos.materia.tramitacao.manage_delObjects(
            ids=arquivoAssinado)
    context.sapl_documentos.materia.tramitacao.manage_addFile(arquivoPdf)
    arq = context.sapl_documentos.materia.tramitacao[arquivoPdf]
    arq.manage_edit(title='PDF Tramitação',
                    filedata=tmp_pdf,
                    content_type='application/pdf')

    return "tramitacao_mostrar_proc?hdn_cod_tramitacao=" + str(cod_tramitacao)
Example #51
0
def invoice_print(request, id):
    import trml2pdf
    order = get_object_or_404(Order, pk=id)
    shopDetails = Config.objects.get_current()
    filename_prefix = shopDetails.site.domain
    filename = "%s-invoice.pdf" % filename_prefix
    template = "invoice.rml"

    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=%s' % filename
    icon_uri = config_value('SHOP', 'LOGO_URI')
    t = loader.get_template(os.path.join('shop/pdf', template))
    c = Context({
                'filename' : filename,
                'iconURI' : icon_uri,
                'shopDetails' : shopDetails,
                'order' : order,
                })
    pdf = trml2pdf.parseString(smart_str(t.render(c)))
    response.write(pdf)
    return response
Example #52
0
def get_documento_testeo(doc):
    tmpl_path = settings.DOCUMENT_TMPL
    response = BytesIO()
    file_rml = os.path.join(tmpl_path, "documento_testeo.xml")
    data = {
        'title': "Documento de testeo %s" % doc.producto,
        "fecha": doc.fecha,
        "nombre": doc.cliente.nombre_completo,
        "telefono": doc.cliente.telefono,
        "DNI": doc.cliente.DNI.upper(),
        "firma": doc.firma,
        "modelo": doc.producto.modelo,
        "ns_imei": doc.producto.ns_imei,
        "firma_freak": ConfigSite.objects.all()[0].firma_tienda
    }
    template = get_template(file_rml)
    #context = Context(data)
    xmlstring = template.render(data)
    pdfstr = trml2pdf.parseString(xmlstring.encode("utf-8"))
    response.write(pdfstr)
    return response
Example #53
0
def principal(imagem, lst_protocolos, dic_cabecalho, lst_rodape):
    """Funcao pricipal que gera a estrutura global do arquivo rml"""

    arquivoPdf = str(int(time.time() * 100)) + ".pdf"

    tmp_data = ''
    tmp_data += '<?xml version="1.0" encoding="utf-8" standalone="no" ?>\n'
    tmp_data += '<!DOCTYPE document SYSTEM "rml_1_0.dtd">\n'
    tmp_data += '<document filename="etiquetas.pdf">\n'
    tmp_data += '\t<template pageSize="(10cm, 6.2cm)" title="Etiquetas de Protocolo" author="Luciano De Fazio" allowSplitting="20" rightMargin="3mm" showBoundary="0">\n'
    tmp_data += '\t\t<pageTemplate id="main">\n'
    tmp_data += '\t\t<pageGraphics>\n'
    tmp_data += '\t\t</pageGraphics>\n'
    tmp_data += '\t\t\t<frame id="first" x1="4mm" y1="1mm" width="94mm" height="60mm"/>\n'
    tmp_data += '\t\t</pageTemplate>\n'
    tmp_data += '\t</template>\n'
    tmp_data += paraStyle()
    tmp_data += protocolos(lst_protocolos)
    tmp_data += '</document>\n'
    tmp_pdf = parseString(tmp_data)

    return tmp_pdf
Example #54
0
def principal(imagem, dic_rodape,dic_inf_basicas,dic_orig_externa,lst_mat_anexadas,lst_autoria,lst_des_iniciais,
              dic_tramitacoes,lst_relatorias,lst_numeracoes,lst_leg_citadas,lst_acessorios,sessao=''):
    """
    Função principal responsável por chamar as funções que irão gerar o código rml apropriado
    """

    arquivoPdf=str(int(time.time()*100))+".pdf"

    tmp=''
    tmp+='<?xml version="1.0" encoding="utf-8" standalone="no" ?>\n'
    tmp+='<!DOCTYPE document SYSTEM "rml_1_0.dtd">\n'
    tmp+='<document filename="relatorio.pdf">\n'
    tmp+='\t<template pageSize="(21cm, 29.7cm)" title="Relatorio de Materias" author="Interlegis" allowSplitting="20">\n'
    tmp+='\t\t<pageTemplate id="first">\n'
    tmp+='\t\t\t<pageGraphics>\n'
    tmp+=cabecalho(dic_inf_basicas,imagem)
    tmp+=rodape(dic_rodape)
    tmp+='\t\t\t</pageGraphics>\n'
    tmp+='\t\t\t<frame id="first" x1="2cm" y1="4cm" width="17cm" height="20.5cm"/>\n'
    tmp+='\t\t</pageTemplate>\n'
    tmp+='\t</template>\n'
    tmp+=paraStyle()
    tmp+='\t<story>\n'
    tmp+=inf_basicas(dic_inf_basicas)
    tmp+=orig_externa(dic_orig_externa)
    tmp+=mat_anexadas(lst_mat_anexadas)
    tmp+=autoria(lst_autoria)
    tmp+=despachos_iniciais(lst_des_iniciais)
    tmp+=tramitacoes(dic_tramitacoes)
    tmp+=relatorias(lst_relatorias)
    tmp+=numeracoes(lst_numeracoes)
    tmp+=legislacoes_citadas(lst_leg_citadas)
    tmp+=documentos_acessorios(lst_acessorios)
    tmp+='\t</story>\n'
    tmp+='</document>\n'
    tmp_pdf=parseString(tmp)

    return tmp_pdf
Example #55
0
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

if __name__=="__main__":
    from doctest import testmod
    import trml2pdf
    testmod(trml2pdf)
    from os.path import abspath, dirname, join
    from os import chdir
    from glob import glob
    from warnings import warn
    chdir(join(dirname(dirname(abspath(__file__))), 'rmls'))
    for rml_fn in glob('*.rml'):
        try:
            # snap = file(rml_fn.replace('.rml', '.pdf'), 'rb').read()
            generated = trml2pdf.parseString(file(rml_fn, 'rb').read())
        except Exception, e:
            warn('Parsing %s failed due to: %s' %(rml_fn, str(e)))
Example #56
0
 def rtml2pdf(self, data):
     import trml2pdf
     return trml2pdf.parseString(smart_str(data))
Example #57
0
 def convert(self, data):
     return trml2pdf.parseString(smart_str(data))