Пример #1
0
def imprimir():
    import csv, time
    from gluon.contrib.pyfpdf import Template
    import os.path
    import sys
    es_para_guardar = False
    if request.args(0):
        doc_id = request.args(0)
    if request.args(1):
        es_para_guardar = True
    doc_record = db(db.fc_documento.id == request.args(0)).select()
    doc_det_rec = db(
        db.fc_documento_det.fc_documento_id == request.args(0)).select(
            orderby=db.fc_documento_det.id)
    emp_rec = db(db.cf_empresa.id == 1).select()
    #print emp_rec
    f = Template(format="A4",
                 title="Presupuesto",
                 author="w.a",
                 subject="w.a",
                 keywords="")
    if es_para_guardar:
        f.parse_csv(infile=request.folder + '/static/rpt/presupuesto_save.csv',
                    delimiter=";",
                    decimal_sep=",")
    else:
        f.parse_csv(infile=request.folder + '/static/rpt/presupuesto.csv',
                    delimiter=";",
                    decimal_sep=",")

#	 # calculate pages:
    lines = len(doc_det_rec)
    max_lines_per_page = 24
    pages = lines / (max_lines_per_page - 1)
    if lines % (max_lines_per_page - 1): pages = pages + 1
    #
    #    # fill placeholders for each page
    for page in range(1, pages + 1):
        f.add_page()
        f['page'] = 'Page %s of %s' % (page, pages)
        if pages > 1 and page < pages:
            s = 'Continues on page %s' % (page + 1)
        else:
            s = ''
# setting data from company
        for row in emp_rec:
            f["EMPRESA"] = row.razon_social
            f["Logo"] = os.path.join(request.env.web2py_path, "applications",
                                     "flota", "uploads", row.ruta_foto)
            f["membrete1"] = 'Rif.:' + row.rif + '  -   Nit.: ' + row.nit
            f["membrete2"] = 'Tel.:' + row.tlf + '  -   Fax.: ' + row.fax
            f["iva"] = 'Email.:' + row.email


#data from document
        for row in doc_record:
            f["numero"] = row.correlativo
            lafecha = row.fecha.strftime("%d/%m/%Y")
            f["Fecha.L"] = 'Fecha: ' + lafecha
            f["cliente.localidad.l"] = 'Contacto: '
            f["cliente.localidad"] = row.contacto
            lafecha2 = row.fecha_vencimiento.strftime("%d/%m/%Y")
            f["cuit"] = 'Fecha Vencimiento: ' + lafecha2
            f["vencimiento"] = ''
            f["vencimientol"] = ''
            f['PeriodoFacturadoL'] = ''
            f['Periodo.Hasta'] = ''
            f['Periodo.Desde'] = ''
            f['cae'] = ''
            #f['cae.l']=''
            f['cae.vencimiento'] = ''
            f['cae.vencimiento.l'] = ''
            f['codigobarras'] = str(row.id) + str(row.correlativo)
            f['codigobarraslegible'] = str(row.id) + str(row.correlativo)
            f['neto.L'] = 'Sub-Total'
            f['iva.L'] = 'I.V.A. 12%'
            notainf = row.nota_detalle
            #data from client
            f["cliente.iva.l"] = ''
            f["cliente.cuit.l"] = ''
            clt_rec = db(db.cf_proveedor.id == row.cf_proveedor_id).select()
            for row in clt_rec:
                f["cliente.nombre"] = row.razon_social
                f["cliente.domicilio"] = row.direccion
                f["cliente.telefono"] = row.tlf + '     Fax: ' + row.fax + '        Email: ' + row.email
        # print line item...
        li = 0
        k = 0
        total = float("0.00")
        for row in doc_det_rec:
            k = k + 1
            if k > page * (max_lines_per_page - 1):
                break
            if row.importe:
                total += float("%.6f" % row.total)
            if k > (page - 1) * (max_lines_per_page - 1):
                li += 1
                f['item.descripcion%02d' % li] = row.descripcion
                if row.importe is not None:
                    f['item.importe%02d' % li] = "%0.2f" % row.total
                if row.cantidad is not None:
                    f['item.cantidad%02d' % li] = "%0.2f" % row.cantidad

            # ojo para la nota del detalle
            # split detail into each line description
                k = k + 2
        if k > (page - 1) * (max_lines_per_page - 1):
            obs = "\n<U>Nota:</U>\n\n" + notainf
            for ds in f.split_multicell(obs, 'item.descripcion%02d' % k):
                for ml in ds.splitlines():
                    f['item.descripcion%02d' % k] = ml
                    k = k + 1

        if pages == page:
            f['neto'] = "%0.2f" % (total)
            #f['vat'] = "%0.2f" % (total*(1-1/float("1.12")))
            f['iva21'] = float("0.00")
            f['total_label'] = 'Total:'
        else:
            f['total_label'] = 'SubTotal:'
        f['total'] = "%0.2f" % total

    if es_para_guardar:
        f.render("./presupuesto_" + doc_id + ".pdf", dest='F')
        if sys.platform.startswith("linux"):
            #print os.getcwd()
            os.system("evince ./presupuesto_" + doc_id + ".pdf")
        else:
            os.system("./presupuesto_" + doc_id + ".pdf")
        redirect(
            URL(c='presupuesto',
                f='email/' + "presupuesto_" + doc_id + ".pdf"))
    else:
        f.render("./presupuesto_" + doc_id + ".pdf")
        if sys.platform.startswith("linux"):
            #print os.getcwd()
            os.system("evince ./presupuesto_" + doc_id + ".pdf")
        else:
            os.system("./presupuesto_" + doc_id + ".pdf")
        redirect(URL(c='presupuesto', f='index'))
def invoice():
    from gluon.contrib.pyfpdf import Template
    import os.path
    
    # generate sample invoice (according Argentina's regulations)

    import random
    from decimal import Decimal

    # read elements from db 
    
    elements = db(db.pdf_element.pdf_template_id==1).select(orderby=db.pdf_element.priority)

    f = Template(format="A4",
             elements = elements,
             title="Sample Invoice", author="Sample Company",
             subject="Sample Customer", keywords="Electronic TAX Invoice")
    
    detail = "Lorem ipsum dolor sit amet, consectetur. " * 5
    items = []
    for i in range(1, 30):
        ds = "Sample product %s" % i
        qty = random.randint(1,10)
        price = round(random.random()*100,3)
        code = "%s%s%02d" % (chr(random.randint(65,90)), chr(random.randint(65,90)),i)
        items.append(dict(code=code, unit='u',
                          qty=qty, price=price, 
                          amount=qty*price,
                          ds="%s: %s" % (i,ds)))

    # divide and count lines
    lines = 0
    li_items = []
    for it in items:
        qty = it['qty']
        code = it['code']
        unit = it['unit']
        for ds in f.split_multicell(it['ds'], 'item_description01'):
            # add item description line (without price nor amount)
            li_items.append(dict(code=code, ds=ds, qty=qty, unit=unit, price=None, amount=None))
            # clean qty and code (show only at first)
            unit = qty = code = None
        # set last item line price and amount
        li_items[-1].update(amount = it['amount'],
                            price = it['price'])

    obs="\n<U>Detail:</U>\n\n" + detail
    for ds in f.split_multicell(obs, 'item_description01'):
        li_items.append(dict(code=code, ds=ds, qty=qty, unit=unit, price=None, amount=None))

    # calculate pages:
    lines = len(li_items)
    max_lines_per_page = 24
    pages = lines / (max_lines_per_page - 1)
    if lines % (max_lines_per_page - 1): pages = pages + 1

    # completo campos y hojas
    for page in range(1, pages+1):
        f.add_page()
        f['page'] = 'Page %s of %s' % (page, pages)
        if pages>1 and page<pages:
            s = 'Continues on page %s' % (page+1)
        else:
            s = ''
        f['item_description%02d' % (max_lines_per_page+1)] = s

        f["company_name"] = "Sample Company"
        f["company_logo"] = os.path.join(request.env.web2py_path,"applications",request.application,"private","tutorial","logo.png")
        f["company_header1"] = "Some Address - somewhere -"
        f["company_header2"] = "http://www.example.com"        
        f["company_footer1"] = "Tax Code ..."
        f["company_footer2"] = "Tax/VAT ID ..."
        f['number'] = '0001-00001234'
        f['issue_date'] = '2010-09-10'
        f['due_date'] = '2099-09-10'
        f['customer_name'] = "Sample Client"
        f['customer_address'] = "Siempreviva 1234"
       
        # print line item...
        li = 0 
        k = 0
        total = Decimal("0.00")
        for it in li_items:
            k = k + 1
            if k > page * (max_lines_per_page - 1):
                break
            if it['amount']:
                total += Decimal("%.6f" % it['amount'])
            if k > (page - 1) * (max_lines_per_page - 1):
                li += 1
                if it['qty'] is not None:
                    f['item_quantity%02d' % li] = it['qty']
                if it['code'] is not None:
                    f['item_code%02d' % li] = it['code']
                if it['unit'] is not None:
                    f['item_unit%02d' % li] = it['unit']
                f['item_description%02d' % li] = it['ds']
                if it['price'] is not None:
                    f['item_price%02d' % li] = "%0.3f" % it['price']
                if it['amount'] is not None:
                    f['item_amount%02d' % li] = "%0.2f" % it['amount']

        if pages == page:
            f['net'] = "%0.2f" % (total/Decimal("1.21"))
            f['vat'] = "%0.2f" % (total*(1-1/Decimal("1.21")))
            f['total_label'] = 'Total:'
        else:
            f['total_label'] = 'SubTotal:'
        f['total'] = "%0.2f" % total

    response.headers['Content-Type']='application/pdf'
    return f.render('invoice.pdf', dest='S')
Пример #3
0
                 price=price,
                 amount=str(detail.amount),
                 ds="%s: %s" % (i, ds)))

    # divide and count lines
    lines = 0
    li_items = []

    unit = qty = code = None

    for it in items:
        qty = it['qty']
        code = it['code']
        unit = it['unit']

        for ds in f.split_multicell(it['ds'], 'item_description01'):
            # add item description line (without price nor amount)
            li_items.append(
                dict(code=code,
                     ds=ds,
                     qty=qty,
                     unit=unit,
                     price=None,
                     amount=None))
            # clean qty and code (show only at first)
            unit = qty = code = None

        # set last item line price and amount
        li_items[-1].update(amount=it['amount'], price=it['price'])

    obs = "\n<U>" + T("Observations") + "</U>\n\n" + str(detail.description)
Пример #4
0
def crear_pdf(el_cbte):
    from gluon.contrib.pyfpdf import Template
    import os.path
    # generate sample invoice (according Argentina's regulations)
    los_detalles = db(db.detalle.comprobante == el_cbte.id).select()
    las_variables = db(db.variables).select().first()

    import random
    from decimal import Decimal

    # read elements from db
    template = db(db.pdftemplate.title == "Demo invoice pyfpdf").select().first()
    elements = db(db.pdfelement.pdftemplate==template.id).select(orderby=db.pdfelement.priority)

    f = Template(format="A4",
             elements = elements,
             title=utftolatin(el_cbte.nombre_cliente), author=utftolatin(las_variables.empresa),
             subject=utftolatin(db.tipocbte[el_cbte.tipocbte].ds), keywords="Electronic TAX Invoice")

    if el_cbte.obs_comerciales:
        detail = el_cbte.obs_comerciales
    else:
        detail = ""

    items = []

    i = 0

    for detalle in los_detalles:
        i += 1
        ds = utftolatin(detalle.ds)
        qty = "%.3f" % float(detalle.qty)
        price = str(detalle.precio)
        code = str(detalle.codigo)
        items.append(dict(code=code, unit=str(detalle.umed.ds[:1]),
                          qty=qty, price=price,
                          amount=str(detalle.imp_total),
                          ds="%s: %s" % (i,ds)))

    # divide and count lines
    lines = 0
    li_items = []

    unit = qty = code = None

    for it in items:
        qty = it['qty']
        code = it['code']
        unit = it['unit']
        for ds in f.split_multicell(it['ds'], 'item_description01'):
            # add item description line (without price nor amount)
            li_items.append(dict(code=code, ds=ds, qty=qty, unit=unit, price=None, amount=None))
            # clean qty and code (show only at first)
            unit = qty = code = None
        # set last item line price and amount
        li_items[-1].update(amount = it['amount'],
                            price = it['price'])

    obs="\n<U>Observaciones:</U>\n\n" + detail

    # convertir a letras el importe
    try:
        importetmp = str(int(round(el_cbte.imp_total*100)))
    except (ValueError, TypeError):
        importetmp = "0000"
    try:
        montoiz = numero_a_letra.convertir(int(importetmp[:-2]))
        montoder = importetmp[-2:]
    except ValueError:
        montoiz = "cero"
        montoder = "00"
        
    obs += "Son %s %s con %s/100" % (el_cbte.moneda_id.ds, montoiz, montoder)

    if el_cbte.obs_comerciales is not None:
        obs += "\n" + el_cbte.obs_comerciales
    
    for ds in f.split_multicell(obs, 'item_description01'):
        li_items.append(dict(code=code, ds=ds, qty=qty, unit=unit, price=None, amount=None))

    # calculate pages:
    lines = len(li_items)
    max_lines_per_page = 24
    pages = lines / (max_lines_per_page - 1)
    if lines % (max_lines_per_page - 1): pages = pages + 1

    # completo campos y hojas
    for page in range(1, pages+1):
        f.add_page()
        f['page'] = u'Página %s de %s' % (page, pages)
        if pages>1 and page<pages:
            s = u'Continúa en la página %s' % (page+1)
        else:
            s = ''
        f['item_description%02d' % (max_lines_per_page+1)] = s

        try:
            if not las_variables.logo:
                logo = os.path.join(request.env.web2py_path,"applications",request.application,"static","images", "logo_fpdf.png")

            else:
                # path al logo
                logo = os.path.join(request.env.web2py_path,"applications",request.application,"uploads", las_variables.logo)

        except (AttributeError, ValueError, KeyError, TypeError):
            logo = os.path.join(request.env.web2py_path,"applications",request.application,"static","images", "logo_fpdf.png")

        f["company_name"] = utftolatin(las_variables.empresa)
        f["company_logo"] = logo
        f["company_header1"] = utftolatin(las_variables.domicilio)
        f["company_header2"] = "CUIT " + str(las_variables.cuit)
        f["company_footer1"] = utftolatin(el_cbte.tipocbte.ds)

        try:
            f["company_footer2"] = WSDESC[el_cbte.webservice]
        except KeyError:
            f["company_footer2"] = u"Factura electrónica"

        f['number'] = str(el_cbte.punto_vta).zfill(4) + "-" + str(el_cbte.cbte_nro).zfill(7)
        f['payment'] = utftolatin(el_cbte.forma_pago)
        f['document_type'] = el_cbte.tipocbte.ds[-1:]

        f['customer_address'] = utftolatin('Dirección')
        f['item_description'] = utftolatin('Descripción')

        try:
            cae = str(el_cbte.cae)
            if cae == "None": cae = "0000000000"
            elif "|" in cae: cae = cae.strip("|")
            f['barcode'] = cae
            f['barcode_readable'] = "CAE: " + cae
        except (TypeError, ValueError, KeyError, AttributeError):
            f['barcode'] = "0000000000"
            f['barcode_readable'] = u"CAE: no registrado"

        try:
            issue_date = el_cbte.fecha_cbte.strftime("%d-%m-%Y")
        except (TypeError, AttributeError):
            issue_date = ""

        try:
            due_date = el_cbte.fecha_vto.strftime("%d-%m-%Y")
        except (TypeError, AttributeError):
            due_date = ""

        f['issue_date'] = issue_date

        f['due_date'] = due_date

        f['customer_name'] = utftolatin(el_cbte.nombre_cliente)
        f['customer_address'] = utftolatin(el_cbte.domicilio_cliente)
        f['customer_vat'] = utftolatin(el_cbte.cp_cliente)
        f['customer_phone'] = utftolatin(el_cbte.telefono_cliente)
        f['customer_city'] = utftolatin(el_cbte.localidad_cliente)
        f['customer_taxid'] = utftolatin(el_cbte.nro_doc)

        # print line item...
        li = 0
        k = 0
        total = 0.00
        for it in li_items:
            k = k + 1
            if k > page * (max_lines_per_page - 1):
                break
            if it['amount']:
                total += float(it['amount'])
            if k > (page - 1) * (max_lines_per_page - 1):
                li += 1
                if it['qty'] is not None:
                    f['item_quantity%02d' % li] = it['qty']
                if it['code'] is not None:
                    f['item_code%02d' % li] = it['code']
                if it['unit'] is not None:
                    f['item_unit%02d' % li] = it['unit']
                f['item_description%02d' % li] = it['ds']
                if it['price'] is not None:
                    f['item_price%02d' % li] = "%0.2f" % float(it['price'])
                if it['amount'] is not None:
                    f['item_amount%02d' % li] = "%0.2f" % float(it['amount'])

        if pages == page:
            f['net'] = "%0.2f" % amountorzero(el_cbte.imp_neto)
            f['vat'] = "%0.2f" % amountorzero(el_cbte.impto_liq)
            f['total_label'] = 'Total:'
        else:
            f['total_label'] = 'SubTotal:'
        f['total'] = "%0.2f" % amountorzero(el_cbte.imp_total)

    return f.render('invoice.pdf', dest='S')
Пример #5
0
def crear_pdf(el_cbte):
    from gluon.contrib.pyfpdf import Template
    import os.path
    # generate sample invoice (according Argentina's regulations)
    los_detalles = db(db.detalle.comprobante == el_cbte.id).select()
    las_variables = db(db.variables).select().first()

    import random
    from decimal import Decimal

    # read elements from db
    template = db(
        db.pdftemplate.title == "Demo invoice pyfpdf").select().first()
    elements = db(db.pdfelement.pdftemplate == template.id).select(
        orderby=db.pdfelement.priority)

    f = Template(format="A4",
                 elements=elements,
                 title=utftolatin(el_cbte.nombre_cliente),
                 author=utftolatin(las_variables.empresa),
                 subject=utftolatin(db.tipocbte[el_cbte.tipocbte].ds),
                 keywords="Electronic TAX Invoice")

    if el_cbte.obs_comerciales:
        detail = el_cbte.obs_comerciales
    else:
        detail = ""

    items = []

    i = 0

    for detalle in los_detalles:
        i += 1
        ds = utftolatin(detalle.ds)
        qty = "%.3f" % float(detalle.qty)
        price = str(detalle.precio)
        code = str(detalle.codigo)
        items.append(
            dict(code=code,
                 unit=str(detalle.umed.ds[:1]),
                 qty=qty,
                 price=price,
                 amount=str(detalle.imp_total),
                 ds="%s: %s" % (i, ds)))

    # divide and count lines
    lines = 0
    li_items = []

    unit = qty = code = None

    for it in items:
        qty = it['qty']
        code = it['code']
        unit = it['unit']
        for ds in f.split_multicell(it['ds'], 'item_description01'):
            # add item description line (without price nor amount)
            li_items.append(
                dict(code=code,
                     ds=ds,
                     qty=qty,
                     unit=unit,
                     price=None,
                     amount=None))
            # clean qty and code (show only at first)
            unit = qty = code = None
        # set last item line price and amount
        li_items[-1].update(amount=it['amount'], price=it['price'])

    obs = "\n<U>Observaciones:</U>\n\n" + detail

    # convertir a letras el importe
    try:
        importetmp = str(int(round(el_cbte.imp_total * 100)))
    except (ValueError, TypeError):
        importetmp = "0000"
    try:
        montoiz = numero_a_letra.convertir(int(importetmp[:-2]))
        montoder = importetmp[-2:]
    except ValueError:
        montoiz = "cero"
        montoder = "00"

    obs += "Son %s %s con %s/100" % (el_cbte.moneda_id.ds, montoiz, montoder)

    if el_cbte.obs_comerciales is not None:
        obs += "\n" + el_cbte.obs_comerciales

    for ds in f.split_multicell(obs, 'item_description01'):
        li_items.append(
            dict(code=code, ds=ds, qty=qty, unit=unit, price=None,
                 amount=None))

    # calculate pages:
    lines = len(li_items)
    max_lines_per_page = 24
    pages = lines / (max_lines_per_page - 1)
    if lines % (max_lines_per_page - 1): pages = pages + 1

    # completo campos y hojas
    for page in range(1, pages + 1):
        f.add_page()
        f['page'] = u'Página %s de %s' % (page, pages)
        if pages > 1 and page < pages:
            s = u'Continúa en la página %s' % (page + 1)
        else:
            s = ''
        f['item_description%02d' % (max_lines_per_page + 1)] = s

        try:
            if not las_variables.logo:
                logo = os.path.join(request.env.web2py_path, "applications",
                                    request.application, "static", "images",
                                    "logo_fpdf.png")

            else:
                # path al logo
                logo = os.path.join(request.env.web2py_path, "applications",
                                    request.application, "uploads",
                                    las_variables.logo)

        except (AttributeError, ValueError, KeyError, TypeError):
            logo = os.path.join(request.env.web2py_path, "applications",
                                request.application, "static", "images",
                                "logo_fpdf.png")

        f["company_name"] = utftolatin(las_variables.empresa)
        f["company_logo"] = logo
        f["company_header1"] = utftolatin(las_variables.domicilio)
        f["company_header2"] = "CUIT " + str(las_variables.cuit)
        f["company_footer1"] = utftolatin(el_cbte.tipocbte.ds)

        try:
            f["company_footer2"] = WSDESC[el_cbte.webservice]
        except KeyError:
            f["company_footer2"] = u"Factura electrónica"

        f['number'] = str(el_cbte.punto_vta).zfill(4) + "-" + str(
            el_cbte.cbte_nro).zfill(7)
        f['payment'] = utftolatin(el_cbte.forma_pago)
        f['document_type'] = el_cbte.tipocbte.ds[-1:]

        f['customer_address'] = utftolatin('Dirección')
        f['item_description'] = utftolatin('Descripción')

        try:
            cae = str(el_cbte.cae)
            if cae == "None": cae = "0000000000"
            elif "|" in cae: cae = cae.strip("|")
            f['barcode'] = cae
            f['barcode_readable'] = "CAE: " + cae
        except (TypeError, ValueError, KeyError, AttributeError):
            f['barcode'] = "0000000000"
            f['barcode_readable'] = u"CAE: no registrado"

        try:
            issue_date = el_cbte.fecha_cbte.strftime("%d-%m-%Y")
        except (TypeError, AttributeError):
            issue_date = ""

        try:
            due_date = el_cbte.fecha_vto.strftime("%d-%m-%Y")
        except (TypeError, AttributeError):
            due_date = ""

        f['issue_date'] = issue_date

        f['due_date'] = due_date

        f['customer_name'] = utftolatin(el_cbte.nombre_cliente)
        f['customer_address'] = utftolatin(el_cbte.domicilio_cliente)
        f['customer_vat'] = utftolatin(el_cbte.cp_cliente)
        f['customer_phone'] = utftolatin(el_cbte.telefono_cliente)
        f['customer_city'] = utftolatin(el_cbte.localidad_cliente)
        f['customer_taxid'] = utftolatin(el_cbte.nro_doc)

        # print line item...
        li = 0
        k = 0
        total = 0.00
        for it in li_items:
            k = k + 1
            if k > page * (max_lines_per_page - 1):
                break
            if it['amount']:
                total += float(it['amount'])
            if k > (page - 1) * (max_lines_per_page - 1):
                li += 1
                if it['qty'] is not None:
                    f['item_quantity%02d' % li] = it['qty']
                if it['code'] is not None:
                    f['item_code%02d' % li] = it['code']
                if it['unit'] is not None:
                    f['item_unit%02d' % li] = it['unit']
                f['item_description%02d' % li] = it['ds']
                if it['price'] is not None:
                    f['item_price%02d' % li] = "%0.2f" % float(it['price'])
                if it['amount'] is not None:
                    f['item_amount%02d' % li] = "%0.2f" % float(it['amount'])

        if pages == page:
            f['net'] = "%0.2f" % amountorzero(el_cbte.imp_neto)
            f['vat'] = "%0.2f" % amountorzero(el_cbte.impto_liq)
            f['total_label'] = 'Total:'
        else:
            f['total_label'] = 'SubTotal:'
        f['total'] = "%0.2f" % amountorzero(el_cbte.imp_total)

    return f.render('invoice.pdf', dest='S')
def invoice():
    from gluon.contrib.pyfpdf import Template
    import os.path

    # generate sample invoice (according Argentina's regulations)

    import random
    from decimal import Decimal

    # read elements from db

    elements = db(db.pdf_element.pdf_template_id == 1).select(
        orderby=db.pdf_element.priority)

    f = Template(format="A4",
                 elements=elements,
                 title="Sample Invoice",
                 author="Sample Company",
                 subject="Sample Customer",
                 keywords="Electronic TAX Invoice")

    detail = "Lorem ipsum dolor sit amet, consectetur. " * 5
    items = []
    for i in range(1, 30):
        ds = "Sample product %s" % i
        qty = random.randint(1, 10)
        price = round(random.random() * 100, 3)
        code = "%s%s%02d" % (chr(random.randint(
            65, 90)), chr(random.randint(65, 90)), i)
        items.append(
            dict(code=code,
                 unit='u',
                 qty=qty,
                 price=price,
                 amount=qty * price,
                 ds="%s: %s" % (i, ds)))

    # divide and count lines
    lines = 0
    li_items = []
    for it in items:
        qty = it['qty']
        code = it['code']
        unit = it['unit']
        for ds in f.split_multicell(it['ds'], 'item_description01'):
            # add item description line (without price nor amount)
            li_items.append(
                dict(code=code,
                     ds=ds,
                     qty=qty,
                     unit=unit,
                     price=None,
                     amount=None))
            # clean qty and code (show only at first)
            unit = qty = code = None
        # set last item line price and amount
        li_items[-1].update(amount=it['amount'], price=it['price'])

    obs = "\n<U>Detail:</U>\n\n" + detail
    for ds in f.split_multicell(obs, 'item_description01'):
        li_items.append(
            dict(code=code, ds=ds, qty=qty, unit=unit, price=None,
                 amount=None))

    # calculate pages:
    lines = len(li_items)
    max_lines_per_page = 24
    pages = lines / (max_lines_per_page - 1)
    if lines % (max_lines_per_page - 1): pages = pages + 1

    # completo campos y hojas
    for page in range(1, pages + 1):
        f.add_page()
        f['page'] = 'Page %s of %s' % (page, pages)
        if pages > 1 and page < pages:
            s = 'Continues on page %s' % (page + 1)
        else:
            s = ''
        f['item_description%02d' % (max_lines_per_page + 1)] = s

        f["company_name"] = "Sample Company"
        f["company_logo"] = os.path.join(request.env.web2py_path,
                                         "applications", request.application,
                                         "private", "tutorial", "logo.png")
        f["company_header1"] = "Some Address - somewhere -"
        f["company_header2"] = "http://www.example.com"
        f["company_footer1"] = "Tax Code ..."
        f["company_footer2"] = "Tax/VAT ID ..."
        f['number'] = '0001-00001234'
        f['issue_date'] = '2010-09-10'
        f['due_date'] = '2099-09-10'
        f['customer_name'] = "Sample Client"
        f['customer_address'] = "Siempreviva 1234"

        # print line item...
        li = 0
        k = 0
        total = Decimal("0.00")
        for it in li_items:
            k = k + 1
            if k > page * (max_lines_per_page - 1):
                break
            if it['amount']:
                total += Decimal("%.6f" % it['amount'])
            if k > (page - 1) * (max_lines_per_page - 1):
                li += 1
                if it['qty'] is not None:
                    f['item_quantity%02d' % li] = it['qty']
                if it['code'] is not None:
                    f['item_code%02d' % li] = it['code']
                if it['unit'] is not None:
                    f['item_unit%02d' % li] = it['unit']
                f['item_description%02d' % li] = it['ds']
                if it['price'] is not None:
                    f['item_price%02d' % li] = "%0.3f" % it['price']
                if it['amount'] is not None:
                    f['item_amount%02d' % li] = "%0.2f" % it['amount']

        if pages == page:
            f['net'] = "%0.2f" % (total / Decimal("1.21"))
            f['vat'] = "%0.2f" % (total * (1 - 1 / Decimal("1.21")))
            f['total_label'] = 'Total:'
        else:
            f['total_label'] = 'SubTotal:'
        f['total'] = "%0.2f" % total

    response.headers['Content-Type'] = 'application/pdf'
    return f.render('invoice.pdf', dest='S')