Ejemplo n.º 1
4
def dotest(outputname, nostamp):
    try:
        from bidi.algorithm import get_display
    except ImportError:
        from unittest import SkipTest
        raise SkipTest("Need python-bidi")
    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)

    pdf.compress = False
    pdf.add_page()
    pdf.add_font('DejaVu', '', \
        os.path.join(common.basepath, 'font/DejaVuSans.ttf'), uni=True)
    pdf.set_font('DejaVu', '', 14)
    # this will be displayed wrong as actually it is stored LTR:
    text= u"این یک متن پارسی است. This is a Persian text !!"
    pdf.write(8, text)
    pdf.ln(8)
    # Reverse the RLT using the Bidirectional Algorithm to be displayed correctly:
    # (http://unicode.org/reports/tr9/)
    rtl_text = get_display(text)
    pdf.write(8, rtl_text)

    pdf.output(outputname, 'F')
Ejemplo n.º 2
1
def dotest(outputname, nostamp):
    # filename - output filename
    # nostamp - do no use stamp in result file
    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)
    pdf.add_page()
    pdf.set_font('Arial', '', 16)
    pdf.write(8, "Test template")
    pdf.output(outputname, 'F')
Ejemplo n.º 3
0
def dotest(outputname, nostamp):
    fpdf.set_global('SYSTEM_TTFONTS', "c:\\WINDOWS\\Fonts")

    pdf = fpdf.FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)

    pdf.add_page()
    # Add a Windows System font (uses UTF-8)
    t0 = time.time()
    pdf.add_font('sysfont','','arial.ttf',uni=True)
    pdf.set_font('sysfont','',14)
    t1 = time.time()
    if not nostamp:
        common.log("ttf loading time", t1-t0)

    # Load a UTF-8 string from a file and print it
    with open(os.path.join(common.basepath, "HelloWorld.txt"), "rb") as file:
        txt = file.read().decode("UTF-8")
    pdf.multi_cell(25, 5, txt)

    pdf.text(100, 5, '1234')

    pdf.write(5,'To find out what\'s new in self tutorial, click ')
    pdf.set_font('','U')
    link=pdf.add_link()
    pdf.write(5,'here',link)

    # Select a standard font (uses windows-1252)
    pdf.set_font('Arial','',14)
    pdf.ln(10)
    pdf.write(5, 'The file size of this PDF is only 12 KB.')

    pdf.output(outputname, 'F')
Ejemplo n.º 4
0
def dotest(outputname, nostamp):
    pdf = FPDF(orientation = "L", format = "A5")
    pdf.compress = False
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)
    pdf.set_font('Arial', '', 14)
    for i in range(10):
        o = ["p", "L", "P", "l"][i % 4]
        page(pdf, "Page %d from 10\nOrientation: %s" % (i + 1, o), o)
    pdf.output(outputname, 'F')
Ejemplo n.º 5
0
def dotest(outputname, nostamp):
    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)

    pdf.add_page()

    pdf.dashed_line(10, 10, 110, 10)
    pdf.dashed_line(10, 20, 110, 20, 5, 5)
    pdf.dashed_line(10, 30, 110, 30, 1, 10)

    pdf.output(outputname, 'F')
Ejemplo n.º 6
0
def dotest(outputname, nostamp):
    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)

    pdf.add_page()

    for i in range(1,41):
        # for flow mode, do not pass x or y:
        pdf.image(os.path.join(common.basepath, '../tutorial/logo_pb.png'))

    pdf.output(outputname, 'F')
Ejemplo n.º 7
0
def dotest(outputname, nostamp):
    pdf = FPDF(orientation = "L", format = (100, 250))
    pdf.compress = False
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)
    pdf.set_font('Arial', '', 14)
    for i in range(16):
        o = ["p", "l"][i % 2]
        f = ["a3", "a4", "a5", "letter", "legal", "",
            (100, 250), (320, 240)][i % 8]
        page(pdf, "Page %d from 16\nFormat: %s\nOrientation: %s" % 
            (i + 1, f, o), o, f)
    pdf.output(outputname, 'F')
Ejemplo n.º 8
0
def dotest(outputname, nostamp):
    # Portrait, millimeter units, A4 page size     
    pdf = FPDF("P", "mm", "A4")
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)
    # Set font: Times, normal, size 10
    pdf.add_page()
    if not nostamp:
        # do not show picture in batch
        url = "http://upload.wikimedia.org/wikipedia/commons/thumb/0/0b/Code_3_of_9.svg/262px-Code_3_of_9.svg.png"
        pdf.image(url, 10, 10)

    pdf.code39("*wikipedia*", 12.75, 7, 1.49)

    pdf.output(outputname, 'F')
Ejemplo n.º 9
0
def dotest(outputname, nostamp):
    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)

    pdf.add_page()
    # Add a Unicode font (uses UTF-8)
    pdf.add_font("DejaVu", "", os.path.join(common.basepath, "font", "DejaVuSansCondensed.ttf"), uni=True)
    pdf.set_font("DejaVu", "", 14)

    # Load a UTF-8 string from a file and print it
    with open(os.path.join(common.basepath, "HelloWorld.txt"), "rb") as file:
        txt = file.read().decode("UTF-8")
    pdf.write(8, txt)

    pdf.output(outputname, "F")
Ejemplo n.º 10
0
def dotest(outputname, nostamp):
    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)

    pdf.add_page()
    pdf.set_font('Arial', '', 14)  
    pdf.ln(10)
    if nostamp:
        data = "TEST-TEST-TEST"
    else:
        data = sys.version

    #áéíóúüñ
    # This string converted with errors in py2.x 
    pdf.write(5, ('hello world %s áéíóúüñ' % data))

    pdf.output(outputname, 'F')
Ejemplo n.º 11
0
def dotest(outputname, nostamp):
    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)

    pdf.add_page()
    pdf.set_font('Arial', '', 14)  
    pdf.ln(10)
    if nostamp:
        data = "TEST-TEST-TEST"
    else:
        data = sys.version

    pdf.write(5, 'hello world %s' % data)
    pdf.image("../tutorial/logo.png", 50, 50)
    pdf.image("flower2.jpg", 100, 50)
    pdf.image("lena.gif", 50, 75)
    pdf.output(outputname, 'F')
Ejemplo n.º 12
0
def dotest(outputname, nostamp):
    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)

    pdf.add_page()
    pdf.set_font('Arial', '', 14)  

    pdf.text(10, 57, 'DeviceGray')
    pdf.image(os.path.join(common.basepath, "img_gray.jpg"), 55, 5)

    pdf.text(10, 157, 'DeviceRGB')
    pdf.image(os.path.join(common.basepath, "img_rgb.jpg"), 55, 105)

    pdf.text(10, 257, 'DeviceCMYK')
    pdf.image(os.path.join(common.basepath, "img_cmyk.jpg"), 55, 205)

    pdf.output(outputname, 'F')
Ejemplo n.º 13
0
def dotest(outputname, nostamp):
    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)

    pdf.add_page()
    # Add a Unicode font (uses UTF-8)
    pdf.add_font('DejaVu', '', \
        os.path.join(common.basepath, "font", 'DejaVuSansCondensed.ttf'), \
        uni = True)
    pdf.set_font('DejaVu','',14)

    # Load a UTF-8 string from a file and print it
    txt = open(os.path.join(common.basepath, "HelloWorld.txt"), "rb").\
        read().decode("UTF-8")
    pdf.write(8, txt)


    pdf.output(outputname, 'F')
Ejemplo n.º 14
0
def dotest(outputname, nostamp):
    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)

    pdf.add_page()
    pdf.set_font('Arial', '', 14)  
    pdf.ln(10)
    if nostamp:
        data = "TEST-TEST-TEST"
    else:
        data = sys.version

    pdf.write(5, 'hello world %s' % data)
    path = os.path.join(common.basepath, os.pardir, "tutorial", "logo.png")
    pdf.image(path, 50, 50)
    pdf.image(os.path.join(common.basepath, "flower2.jpg"), 100, 50)
    pdf.image(os.path.join(common.basepath, "lena.gif"), 50, 75)
    pdf.output(outputname, 'F')
Ejemplo n.º 15
0
def dotest(outputname, nostamp):
    plane = genbar()
    palette = (0,0,0, 255,255,255) + (128,128,128)*254
    try:    
        img = Image.frombytes("P", plane.size, plane.tobytes())
    except AttributeError:
        # note: https://github.com/python-pillow/Pillow/issues/63
        img = Image.fromstring("P", plane.size, plane.tostring())
    img.putpalette(palette)

    with tempfile.NamedTemporaryFile(delete = False, suffix = ".gif") as f:
        gif1 = f.name
    with tempfile.NamedTemporaryFile(delete = False, suffix = ".gif") as f:
        gif2 = f.name

    img.save(gif1, "GIF", optimize = 0)
    img.save(gif2, "GIF", transparency = 1, optimize = 0)

    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)
    pdf.add_page()
    pdf.set_font('Arial', '', 16)
    pdf.write(8, "Transparency")
    pdf.ln()
    pdf.write(8, "    Transparency")
    pdf.ln()
    pdf.write(8, "        Transparency")
    pdf.ln()
    pdf.image(gif1, x = 15, y = 15)

    pdf.write(8, "Transparency")
    pdf.ln()
    pdf.write(8, "    Transparency")
    pdf.ln()
    pdf.write(8, "        Transparency")
    pdf.ln()
    pdf.image(gif2, x = 15, y = 39)

    pdf.output(outputname, 'F')

    os.unlink(gif1)
    os.unlink(gif2)
Ejemplo n.º 16
0
def dotest(outputname, nostamp):
    plane = genbar()
    palette = (0,0,0, 255,255,255) + (128,128,128)*254
    img = Image.fromstring("P", plane.size, plane.tostring())
    img.putpalette(palette)

    f = tempfile.NamedTemporaryFile(delete = False, suffix = ".gif")
    gif1 = f.name
    f.close()
    f = tempfile.NamedTemporaryFile(delete = False, suffix = ".gif")
    gif2 = f.name
    f.close()

    img.save(gif1, "GIF")
    img.save(gif2, "GIF", transparency = 1)


    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)
    pdf.add_page()
    pdf.set_font('Arial', '', 16)
    pdf.write(8, "Transparency")
    pdf.ln()
    pdf.write(8, "    Transparency")
    pdf.ln()
    pdf.write(8, "        Transparency")
    pdf.ln()
    pdf.image(gif1, x = 15, y = 15)

    pdf.write(8, "Transparency")
    pdf.ln()
    pdf.write(8, "    Transparency")
    pdf.ln()
    pdf.write(8, "        Transparency")
    pdf.ln()
    pdf.image(gif2, x = 15, y = 39)

    pdf.output(outputname, 'F')

    os.unlink(gif1)
    os.unlink(gif2)
Ejemplo n.º 17
0
def dotest(outputname, nostamp):
    fpdf.set_global("FPDF_CACHE_MODE", 1)
    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)

    pdf.add_page()
    # Add a Unicode font (uses UTF-8)
    pdf.add_font('DejaVu', '', \
        os.path.join(common.basepath, "font", 'DejaVuSans.ttf'), \
        uni = True)
    pdf.set_font('DejaVu', '', 14)
    with open(os.path.join(common.basepath, "HelloWorld.txt"), "rb") as file:
        txt = file.read().decode("UTF-8")

    if not nostamp:
        text(pdf, txt, 100, nostamp)
    text(pdf, txt, 75, nostamp)
    text(pdf, txt, 125, nostamp)

    pdf.output(outputname, 'F')
Ejemplo n.º 18
0
def dotest(outputname, nostamp):
    pdf = FPDF(orientation = "L", unit = "in")
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)

    pdf.add_page()

    img_path = os.path.join(common.basepath, '../tutorial/logo.png')
    img = Image.open(img_path)
    w, h = img.size
    width = 8
    height = width * (h // w)
    with tempfile.NamedTemporaryFile(delete = False, suffix = ".png") as f:
        img_new = f.name
    # convert to RGBA
    img2 = img.convert(mode = "RGBA")
    img2.save(img_new)
    # create pdf
    pdf.image(img_new, x = 1, y = 1, w = width, h = height)

    pdf.output(outputname, 'F')
Ejemplo n.º 19
0
def dotest(outputname, nostamp):
    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)

    pdf.add_page()
    pdf.set_font('Arial', '', 14)  

    for i in range(0, 270, 5):
        pdf.text(i % 40 + 20, i + 20, "Image masking " * 4)
    mask = pdf.image(os.path.join(common.basepath, "masking.png"), 
        is_mask = True)
    pdf.image(os.path.join(common.basepath, "lena.gif"), 
        40.0, 20.0, w = 120, mask_image = mask)

    pdf.image(os.path.join(common.basepath, "img_gray.jpg"), 
        20.0, 200.0, w = 50, mask_image = mask)
    pdf.image(os.path.join(common.basepath, "img_rgb.jpg"), 
        80.0, 200.0, w = 50, mask_image = mask)
    pdf.image(os.path.join(common.basepath, "img_cmyk.jpg"), 
        140.0, 200.0, w = 50, mask_image = mask)

    pdf.output(outputname, 'F')
Ejemplo n.º 20
0
def dotest(outputname, nostamp=True):
    pdf = FPDF(unit="pt")
    pdf._putinfo = lambda: common.test_putinfo(pdf)
    pdf.add_page()
    pdf.set_font("Times", size=12)
    pdf.cell(0, 12, "Dummy content")
    
    # Get the PDF data the usual way via a real file
    pdf.output(outputname)
    with open(outputname, "rb") as file:
        data = file.read(1000)
        assert len(data) == 966, "Unexpected PDF file size"
    
    try:  # Python < 3 (Python 2.5 does not have the "io" module)
        from cStringIO import StringIO
        capture = StringIO()
        detach = lambda: capture
    except ImportError:  # Python >= 3.1
        from io import TextIOWrapper, BytesIO
        # Ensure that no text encoding is actually done
        capture = TextIOWrapper(BytesIO(), "undefined")
        detach = lambda: capture.detach()
    
    # Compare data when output() writes to stdout
    original_stdout = sys.stdout
    try:
        sys.stdout = capture
        pdf.output()
        capture = detach()
    finally:
        sys.stdout = original_stdout
    assert capture.getvalue() == data, "Unexpected stdout data"
    
    # Compare data when output() returns a byte string
    returned = pdf.output(dest="S")
    assert isinstance(returned, bytes), "output() should return bytes"
    assert returned == data, "Unexpected PDF data returned"
Ejemplo n.º 21
0
def dotest(outputname, nostamp):
    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)
    pdf.add_page()
    pdf.add_font('DejaVu', '', os.path.join(common.basepath, 
        'font/DejaVuSansCondensed.ttf'), uni = True)
    pdf.set_font('DejaVu', '', 14)

    # Note: this line cause syntax error in Python 3.0-3.2
    text = u"""
Veľké písmená
A   Á   Ä   B   C   Č   D   Ď   DZ  DŽ  E   É   F   G   H   CH  I   Í   J   K   L   Ĺ   Ľ
Malé písmená
a   á   ä   b   c   č   d   ď   dz  dž  e   é   f   g   h   ch  i   í   j   k   l   ĺ   ľ
Veľké písmená
M   N   Ň   O   Ó   Ô   P   Q   R   Ŕ   S   Š   T   Ť   U   Ú   V   W   X   Y   Ý   Z   Ž
Malé písmená
m   n   ň   o   ó   ô   p   q   r   ŕ   s   š   t   ť   u   ú   v   w   x   y   ý   z   ž
"""

    pdf.write(8, text)
    pdf.ln(8)
    pdf.output(outputname, 'F')
Ejemplo n.º 22
0
def dotest(outputname, nostamp):
    pdf = fpdf.FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)

    fpdf.set_global("FPDF_CACHE_MODE", 1)
    # set default alias: {nb} that will be replaced with total page count
    pdf.alias_nb_pages()

    # Add a Unicode font (uses UTF-8)
    pdf.add_font('DejaVu', '', \
        os.path.join(common.basepath, "font", 'DejaVuSansCondensed.ttf'), \
        uni = True)
    pdf.set_font('DejaVu', '', 14)

    for i in range(5):
        pdf.add_page()
        pdf.set_font('Arial','B',16)
        pdf.cell(40,10,'Hello World! Page %d from {nb}' % (i + 1))
        pdf.set_font('DejaVu','',14)
        pdf.cell(40,30,'Hello World! unicode {nb}')


    pdf.output(outputname, 'F')
Ejemplo n.º 23
0
def dotest(outputname, nostamp):

    # generate sample invoice (according Argentina's regulations)   
    from decimal import Decimal

    f = Template(format="A4",
             title="Sample Invoice", author="Sample Company",
             subject="Sample Customer", keywords="Electronic TAX Invoice")
    if nostamp:
        f.pdf._putinfo = lambda: common.test_putinfo(f.pdf)
        random = randomfake()
    else:
        import random

    csvpath = os.path.join(common.basepath, "invoice.csv")
    f.parse_csv(infile=csvpath, delimiter=";", decimal_sep=",")
    
    detail = "Lorem ipsum dolor sit amet, consectetur. " * 30
    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 = int(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, int(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(common.basepath, "../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
            
    f.render(outputname)
Ejemplo n.º 24
0
def dotest(outputname, nostamp):
    pdf = MyPDF()
    pdf.p_hdr1 = "Latin Character Set and WinAnsiEncoding (1252)"
    pdf.p_hdr2 = "PDF 1.7, annex D.1, pages 997-1000"
    pdf.alias_nb_pages()
    pdf.compress = False
    use_exfont = False
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)
    else:
        # This font used if:
        # 1. It exists
        # 2. In user mode
        fp = os.path.join(common.basepath, 'font/DejaVuSans.ttf')
        if os.path.exists(fp):
            use_exfont = True
            pdf.add_font('DejaVu', '', fp, uni = True)
    pdf.set_fill_color(150)
    pdf.add_page()

    def tabletop():
        pdf.set_font('Arial', 'B', 8)
        if use_exfont:
            pdf.cell(12, 8, txt = "DejaVu", border = 1, align = "C")
        pdf.cell(12, 8, txt = "Type 1", border = 1, align = "C")
        pdf.cell(12, 8, txt = "Code", border = 1, align = "C")
        pdf.cell(12, 8, txt = "1252", border = 1, align = "C")
        pdf.cell(35, 8, txt = "Name", border = 1, align = "C")
        pdf.cell(20, 8, txt = "WinAnsi", border = 1, align = "C")
        pdf.cell(20, 8, txt = "Unicode", border = 1, align = "C")
        pdf.ln()
    
    pdf.table_cnt = 0
    def print_char(char, name, code):
        if pdf.table_cnt > 28:
            pdf.add_page()
            pdf.table_cnt = 0
        if pdf.table_cnt == 0:
            tabletop()
        pdf.table_cnt += 1

        # transform char for displaying
        if len(char) != 1:
            if len(char) == 2 and char[:1] == u" ":
                ocode = ord(char[1])
                if code is not None:
                    pchar = unichr(code)
                else:
                    pchar = "O" + char[1:]
            else:
                raise Exception("bad charter for \"" + name + "\" " + repr(char))
        else:
            ocode = ord(char)
            pchar = char
        

        # external
        if use_exfont:
            pdf.set_font('DejaVu', '', 14)
            pdf.cell(12, 8, txt = pchar, border = 1, align = "R")

        pdf.set_font('Arial', '', 14)

        # as latin-1 charter
        bg = False
        txt = pchar
        try:
            pchar.encode("latin1")
        except UnicodeEncodeError:
            txt = ""
            bg = True
        pdf.cell(12, 8, txt = txt, border = 1, align = "R", fill = bg)

        # as winansi code
        if code is not None:
            txt = chr(code)
        else:
            txt = ""
        pdf.cell(12, 8, txt = txt, border = 1, align = "R")

        # as 1252
        bg = False
        try:
            txt = pchar.encode("windows-1252").decode("latin-1")
        except:
            txt = ""
            bg = True
        pdf.cell(12, 8, txt = txt, border = 1, align = "R", fill = bg)

        # char name
        pdf.cell(35, 8, txt = name, border = 1, align = "L")
        # hex codes
        hcode = ""
        alt = ""
        if code is not None:
            hcode = "0x%02X" % code
            if ocode != code:
                alt = "0x%02X" % ocode
        else:
            alt = "0x%02X" % ocode
        pdf.cell(20, 8, txt = hcode, border = 1, align = "L")
        pdf.cell(20, 8, txt = alt, border = 1, align = "L")

        pdf.ln()


    used = {}
    for char, name, code in SYMBOLS:
        print_char(char, name, code)
        used[code] = (char, name)

    for i in range(32, 256):
        if i not in used:
            print_char(unichr(i), "Code 0x%02X" % i, i)

    # wiki-like table
    pdf.p_hdr1 = "Windows-1252"
    pdf.p_hdr2 = "https://en.wikipedia.org/wiki/Windows-1252"
    pdf.add_page()
    # without this setting we should use 
    #  txt.encode("windows-1252").decode("latin-1") for every output
    pdf.set_doc_option("core_fonts_encoding", "windows-1252")
    cc = {}
    codec = {}
    for x in range(256):
        bgr, bgg, bgb = (0xFF, 0xFF, 0xFF)
        pdf.set_font('Arial', '', 14)
        if x in used:
            txt = used[x][0]
            if len(txt) > 1:
                code = ord(used[x][0][1])
            else:
                code = ord(used[x][0])
            if code < 256:
                code = "%02X" % code
            else:
                code = "U+%04X" % code
        else:
            txt = ""
            code = ""
        if x in CTRL:
            # control
            txt = CTRL[x]
            pdf.set_font('Arial', '', 10)
        # colors
        if (x <= 0x1F) or (x == 0x7F):
            bgr, bgg, bgb = (0xFF, 0xFF, 0xEF)
        elif (x >= 0x20 and x <= 0x2F) or \
             (x >= 0x3A and x <= 0x40) or \
             (x >= 0x5B and x <= 0x60) or \
             (x >= 0x7B and x <= 0x7E):
            bgr, bgg, bgb = (0xDF, 0xF7, 0xFF)
            # punctuation
        elif (x >= 0x30 and x <= 0x39) or (x in [0xB2, 0xB3, 0xB9]):
            # numeric digit
            bgr, bgg, bgb = (0xF7, 0xE7, 0xFF)
        elif x >= 0x41 and x <= 0x7A:
            # alphabetic
            bgr, bgg, bgb = (0xE7, 0xFF, 0xE7)
        elif x in [0x81, 0x8D, 0x8F, 0x90, 0x9D]:
            # unused
            bgr, bgg, bgb = (0xD0, 0xD0, 0xD0)
        elif (x in [0x83, 0x8A, 0x8C, 0x8E, 0x9A, 0x9C, 0x9E, 0x9F,
            0xAA, 0xBA]) or (x >= 0xC0 and x <= 0xD6) or \
            (x >= 0xD8 and x <= 0xF6) or (x >= 0xF8 and x <= 0xFF):
            # international
            bgr, bgg, bgb = (0xFF, 0xEF, 0xDF)
        else:
            # extended punctuation
            bgr, bgg, bgb = (0xDF, 0xDF, 0xE7)

        pdf.set_fill_color(bgr, bgg, bgb)
        cc[x % 16] = (bgr, bgg, bgb)
        codec[x % 16] = code
        pdf.cell(12, 8, txt = txt, border = "LRT", align = "C", fill = True)
        if x % 16 == 15:
            pdf.ln()
            pdf.set_font('Arial', '', 6)
            for i in range(16):
                pdf.set_fill_color(*cc[i])
                pdf.cell(12, 3, txt = codec[i],
                    border = "LR", align = "C", fill = True)
            pdf.ln()
            pdf.set_font('Arial', '', 6)
            for i in range(16):
                pdf.set_fill_color(*cc[i])
                pdf.cell(12, 3, txt = "0x%02X" % (x - 15 + i),
                    border = "LRB", align = "C", fill = True)
            pdf.ln()

    pdf.output(outputname, 'F')
Ejemplo n.º 25
0
def dotest(outputname, nostamp):
    pdf = FPDF()
    pdf.unifontsubset = False
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)
    pdf.add_page()
    pdf.set_font('Arial', 'I', 8)

    # 1. Test:
    # with txt = txt.encode('latin1') in function normalize_text of module fpdf.py
    # and using
    #
    # txt = all_pdf_chars
    #
    # you will get
    #       "UnicodeEncodeError: 'latin-1' codec can't encode character"
    # for each of the chars in chars_not_in_latin_1
    
    # 2. Test:
    # with txt = txt.encode('windows-2') in function normalize_text of module fpdf.py
    # and using
    #
    # txt = all_pdf_chars
    #
    # you will get
    #       "UnicodeEncodeError: 'windows-1252' codec can't encode character"
    # for each of the chars in chars_not_in_windows_1252
    
    # 3. Test
    # with txt = txt.encode('latin1') in function normalize_text of module fpdf.py
    # and using
    #
    # txt = latin_1_chars
    #
    # you don't get these errors

    # 4. Test
    # with txt = txt.encode('windows-1252') in function normalize_text of module fpdf.py
    # and using

    txt = windows_1252_chars
    
    # you either don't get these errors


    # to summarize
    # all_pdf_chars = windows_1252_chars + chars_not_in_windows_1252
    # all_pdf_chars = latin_1_chars + chars_not_in_latin_1
    
    def nrOfChars(var):
        if var in [all_pdf_chars,windows_1252_chars,latin_1_chars]:
            return len(var.split('\n'))-2-6
        elif var == chars_not_in_windows_1252:
            return len(var.split('\n'))-2
        elif var == chars_not_in_latin_1:
            return len(var.split('\n'))-2-1

    chartexts = {'all':all_pdf_chars,
                 'windows-1252':windows_1252_chars,
                 'latin1':latin_1_chars,
                 'not_in_windows_1252':chars_not_in_windows_1252,
                 'not_in_latin_1':chars_not_in_latin_1}
    for k in chartexts.keys():
        print(k,nrOfChars(chartexts[k]))

    # Output:
    #('all', 229)
    #('windows-1252', 215)
    #('latin1', 188)
    #('not_in_windows_1252', 14)
    #('not_in_latin_1', 41)
    # 
    # => not_in_latin_1 - not_in_windows_1252 = 27
    
    pdf.write(8, txt)

    pdf.output(outputname, 'F')
Ejemplo n.º 26
0
def dotest(outputname, nostamp):

    # generate sample invoice (according Argentina's regulations)   
    from decimal import Decimal

    f = Template(format="A4",
             title="Sample Invoice", author="Sample Company",
             subject="Sample Customer", keywords="Electronic TAX Invoice")
    if nostamp:
        f.pdf._putinfo = lambda: common.test_putinfo(f.pdf)
        random = randomfake()
    else:
        import random

    csvpath = os.path.join(common.basepath, "invoice.csv")
    f.parse_csv(infile=csvpath, delimiter=";", decimal_sep=",")
    
    detail = "Lorem ipsum dolor sit amet, consectetur. " * 30
    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 = int(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, int(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(common.basepath, "../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
            
    f.render(outputname)
Ejemplo n.º 27
0
def dotest(outputname, nostamp):
    pdf = MyPDF()
    pdf.p_hdr1 = "Latin Character Set and WinAnsiEncoding (1252)"
    pdf.p_hdr2 = "PDF 1.7, annex D.1, pages 997-1000"
    pdf.alias_nb_pages()
    pdf.compress = False
    use_exfont = False
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)
    else:
        # This font used if:
        # 1. It exists
        # 2. In user mode
        fp = os.path.join(common.basepath, 'font/DejaVuSans.ttf')
        if os.path.exists(fp):
            use_exfont = True
            pdf.add_font('DejaVu', '', fp, uni=True)
    pdf.set_fill_color(150)
    pdf.add_page()

    def tabletop():
        pdf.set_font('Arial', 'B', 8)
        if use_exfont:
            pdf.cell(12, 8, txt="DejaVu", border=1, align="C")
        pdf.cell(12, 8, txt="Type 1", border=1, align="C")
        pdf.cell(12, 8, txt="Code", border=1, align="C")
        pdf.cell(12, 8, txt="1252", border=1, align="C")
        pdf.cell(35, 8, txt="Name", border=1, align="C")
        pdf.cell(20, 8, txt="WinAnsi", border=1, align="C")
        pdf.cell(20, 8, txt="Unicode", border=1, align="C")
        pdf.ln()

    pdf.table_cnt = 0

    def print_char(char, name, code):
        if pdf.table_cnt > 28:
            pdf.add_page()
            pdf.table_cnt = 0
        if pdf.table_cnt == 0:
            tabletop()
        pdf.table_cnt += 1

        # transform char for displaying
        if len(char) != 1:
            if len(char) == 2 and char[:1] == u" ":
                ocode = ord(char[1])
                if code is not None:
                    pchar = unichr(code)
                else:
                    pchar = "O" + char[1:]
            else:
                raise Exception("bad charter for \"" + name + "\" " +
                                repr(char))
        else:
            ocode = ord(char)
            pchar = char

        # external
        if use_exfont:
            pdf.set_font('DejaVu', '', 14)
            pdf.cell(12, 8, txt=pchar, border=1, align="R")

        pdf.set_font('Arial', '', 14)

        # as latin-1 charter
        bg = False
        txt = pchar
        try:
            pchar.encode("latin1")
        except UnicodeEncodeError:
            txt = ""
            bg = True
        pdf.cell(12, 8, txt=txt, border=1, align="R", fill=bg)

        # as winansi code
        if code is not None:
            txt = chr(code)
        else:
            txt = ""
        pdf.cell(12, 8, txt=txt, border=1, align="R")

        # as 1252
        bg = False
        try:
            txt = pchar.encode("windows-1252").decode("latin-1")
        except:
            txt = ""
            bg = True
        pdf.cell(12, 8, txt=txt, border=1, align="R", fill=bg)

        # char name
        pdf.cell(35, 8, txt=name, border=1, align="L")
        # hex codes
        hcode = ""
        alt = ""
        if code is not None:
            hcode = "0x%02X" % code
            if ocode != code:
                alt = "0x%02X" % ocode
        else:
            alt = "0x%02X" % ocode
        pdf.cell(20, 8, txt=hcode, border=1, align="L")
        pdf.cell(20, 8, txt=alt, border=1, align="L")

        pdf.ln()

    used = {}
    for char, name, code in SYMBOLS:
        print_char(char, name, code)
        used[code] = (char, name)

    for i in range(32, 256):
        if i not in used:
            print_char(unichr(i), "Code 0x%02X" % i, i)

    # wiki-like table
    pdf.p_hdr1 = "Windows-1252"
    pdf.p_hdr2 = "https://en.wikipedia.org/wiki/Windows-1252"
    pdf.add_page()
    # without this setting we should use
    #  txt.encode("windows-1252").decode("latin-1") for every output
    pdf.set_doc_option("core_fonts_encoding", "windows-1252")
    cc = {}
    codec = {}
    for x in range(256):
        bgr, bgg, bgb = (0xFF, 0xFF, 0xFF)
        pdf.set_font('Arial', '', 14)
        if x in used:
            txt = used[x][0]
            if len(txt) > 1:
                code = ord(used[x][0][1])
            else:
                code = ord(used[x][0])
            if code < 256:
                code = "%02X" % code
            else:
                code = "U+%04X" % code
        else:
            txt = ""
            code = ""
        if x in CTRL:
            # control
            txt = CTRL[x]
            pdf.set_font('Arial', '', 10)
        # colors
        if (x <= 0x1F) or (x == 0x7F):
            bgr, bgg, bgb = (0xFF, 0xFF, 0xEF)
        elif (x >= 0x20 and x <= 0x2F) or \
             (x >= 0x3A and x <= 0x40) or \
             (x >= 0x5B and x <= 0x60) or \
             (x >= 0x7B and x <= 0x7E):
            bgr, bgg, bgb = (0xDF, 0xF7, 0xFF)
            # punctuation
        elif (x >= 0x30 and x <= 0x39) or (x in [0xB2, 0xB3, 0xB9]):
            # numeric digit
            bgr, bgg, bgb = (0xF7, 0xE7, 0xFF)
        elif x >= 0x41 and x <= 0x7A:
            # alphabetic
            bgr, bgg, bgb = (0xE7, 0xFF, 0xE7)
        elif x in [0x81, 0x8D, 0x8F, 0x90, 0x9D]:
            # unused
            bgr, bgg, bgb = (0xD0, 0xD0, 0xD0)
        elif (x in [0x83, 0x8A, 0x8C, 0x8E, 0x9A, 0x9C, 0x9E, 0x9F,
            0xAA, 0xBA]) or (x >= 0xC0 and x <= 0xD6) or \
            (x >= 0xD8 and x <= 0xF6) or (x >= 0xF8 and x <= 0xFF):
            # international
            bgr, bgg, bgb = (0xFF, 0xEF, 0xDF)
        else:
            # extended punctuation
            bgr, bgg, bgb = (0xDF, 0xDF, 0xE7)

        pdf.set_fill_color(bgr, bgg, bgb)
        cc[x % 16] = (bgr, bgg, bgb)
        codec[x % 16] = code
        pdf.cell(12, 8, txt=txt, border="LRT", align="C", fill=True)
        if x % 16 == 15:
            pdf.ln()
            pdf.set_font('Arial', '', 6)
            for i in range(16):
                pdf.set_fill_color(*cc[i])
                pdf.cell(12,
                         3,
                         txt=codec[i],
                         border="LR",
                         align="C",
                         fill=True)
            pdf.ln()
            pdf.set_font('Arial', '', 6)
            for i in range(16):
                pdf.set_fill_color(*cc[i])
                pdf.cell(12,
                         3,
                         txt="0x%02X" % (x - 15 + i),
                         border="LRB",
                         align="C",
                         fill=True)
            pdf.ln()

    pdf.output(outputname, 'F')