Giter Club home page Giter Club logo

pyfpdf's Introduction

pyfpdf: FPDF for Python

PyFPDF is a library for PDF document generation under Python, ported from PHP (see FPDF: "Free"-PDF, a well-known PDFlib-extension replacement with many examples, scripts and derivatives).

Compared with other PDF libraries, PyFPDF is simple, small and versatile, with advanced capabilities, and is easy to learn, extend and maintain.

Features:

  • Python 2.5 to 3.4 support
  • Unicode (UTF-8) TrueType font subset embedding
  • Barcode I2of5 and code39, QR code coming soon ...
  • PNG, GIF and JPG support (including transparency and alpha channel)
  • Templates with a visual designer & basic html2pdf
  • Exceptions support, other minor fixes, improvements and PEP8 code cleanups

Installation Instructions:

To get the latest development version you can download the source code running:

   git clone https://github.com/reingart/pyfpdf.git
   cd pyfpdf
   python setup.py install

You can also install PyFPDF from PyPI, with easyinstall or from Windows installers. For example, using pip:

   pip install fpdf

Note: the Python Imaging Library (PIL) is needed for GIF support. PNG and JPG support is built-in and doesn't require any external dependency. For Python 3, Pillow - The friendly PIL fork is supported.

Documentation:

Documentation Status

For further information, see the project site: https://github.com/reingart/pyfpdf or the old Google Code project page https://code.google.com/p/pyfpdf/.

pyfpdf's People

Contributors

craigahobbs avatar eocasio avatar googlecodeexporter avatar jredrejo avatar kalbermattenm avatar larivact avatar leoleozhu avatar leonelcamara avatar marcelotduarte avatar niphlod avatar reingart avatar romankharin avatar yanone avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyfpdf's Issues

write_html doesn't allow base64 inlined images

If you have a base64 inline image in html the write_html method doesn't work as it doesn't know how to extract the data from the src string:

<p><img alt="Embedded Image" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAOwCAYAAADRJ6o6AAA..." /></p>

failed to add certain PNG

My code is something like:

from fpdf import FPDF

pdf = FPDF(unit='pt',format=[1058, 1497])
pdf.add_page()
pdf.image('tmpB8jsgj.png')
pdf.output('test.pdf', 'F')

Here is the corresponding image.

After running the code, I get an error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/site-packages/fpdf/fpdf.py", line 150, in wrapper
    return fn(self, *args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/fpdf/fpdf.py", line 971, in image
    info=self._parsepng(name)
  File "/usr/local/lib/python2.7/site-packages/fpdf/fpdf.py", line 1844, in _parsepng
    f.read(n+4)
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

Images showing as black

When I try to put an image in a pdf, it turns out black. I've tried jpeg, png and gif with the same result. I'm using python 3.4. The code I'm using is:

pdf = FPDF('P', 'mm', 'A4')
pdf.compress = False
pdf.set_margins(28, 19, 27)
pdf.set_font('Times', '', 11)
pdf.add_page()
pdf.cell(151, 4.5, "", 0, 1, 'L')
pdf.image(thumbnail, 30, 23, 0, 35.63)

Result of running tests:

3.4.0: total - 24, ok - 22, skip - 2

fpdf 1.7.2
Ubuntu 14.04
Pillow 2.8.1
Django 1.8
Python 3.4.0

PyPI version up (1.7.1)

It seems that 1.7.1 already stable, but not yet on PyPI. Could you make a release? Thanks!

PDF files generated cannot be read by Adobe Reader or Preview on Mac

Attached is an output pdf generated by doing a series of add_page() and image() calls. I cannot open the PDF successfully in programs like Adobe Reader or Preview on MacOS, but can open them with evince in Linux and the PDF viewer in Google Chrome. Does any one know what might be causing this issue?

Here is the code I am using, in which I am passing a list of *.png files

def makePdf(out_path, listImages, dir = ''):
    """
    Arguments
    ---------
    out_path: str, i.e. 'path/to/output.pdf'
    listImages: list of str, i.e. ['road_user_type_counts.png', 'speed_cdf.png']
    dir: str, path where images located, and pdf will be outputted
    """

    pdf = FPDF(orientation='L', unit = "in", format = 'Letter')

    # Save an image per page
    for page in listImages:
        pdf.add_page()

        img_path = os.path.join(dir,str(page))
        img = Image.open(img_path)
        w, h = img.size
        
        # all images default 8 inch width
        width = 8

        # height in inches, relative to aspect ratio
        height = width * (h // w)

        pdf.image(img_path, x=1, y=1, w=width, h=height)

    pdf.output(out_path, "F")

santosreport.pdf

Insert images from memory, rather than from the filesystem

First of all I need to say, thanks so much for providing and maintaining a Python pdf generation library with a sane API and good documentation.

I'm first using Pillow to generate an image, and then inserting the image into a pdf using FPDF.

Currently I have to

  • create the image using Pillow
  • save the image to disk
  • create a pdf with FPDF
  • insert the image into the pdf using image('path/to/file', ...) which calls _parsepng(filename) which calls load_resource(filename) which finally calls open(filename, "rb")
  • delete the image from disk

Since I have the image already loaded in memory, if I could pass those bytes to the image function then I could avoid touching the disk altogether.

{nb} not working

on the tutorial page the following code

this.cell(0,10,'Page '+str(this.page_no())+'/{nb}',0,0,'C')

should generate a pagination info where nb the total of the pages on the PDF, right? But the {nb} tag is not being replaced. Any tips on that?

unicode support

i try to create pdf from django utf8 model , the language of fields is persian
this is the code for pdf

string  = item.questionid.question.encode('utf-8').strip()
pdf.cell(0,10, string,0,1)

but the output is some random characters like it's not encoded correctly

HTML Link in cell

I'm trying to write a cell which includes an external HTML link. I can write a HTML link but this is not within my layout cells.

The following does not work:

    pdf.cell(0,0,pdf.write_html('<a href="www.google.com">my link</a>', image_map=None),0,0)

Any pointers as to how I can write? My anticipated outcome is a link to our website followed by text for the name, price, etc...

Support Python’s “unittest” framework

Recently I pushed some changes to allow using the existing test suite with Python’s “unittest” framework. This issue is to allow the changes to be discussed and reviewed better.

Comparison of the changes: 25af257...dd64bb1

The tests may now be run on Python 2.7 and 3.2+ with a command like

python -m unittest discover -s tests/cover/

The main advantages for using “unittest” for me are:

  • Familiarity, e.g. I know how to specify different interpreters, enable warnings, etc
  • Better exception reporting when a test fails

The original “runtest.py” script that runs all the tests on different Python interpreters should continue to work as before. Also, individual test files can still be run as before. So nothing is lost. The advantages for these methods:

  • “runtest.py” automatically uses various Python interpreters
  • Better support for older Python versions

In the standard “unittest” library that comes with Python 2.5 and 2.6, the automatic test discovery mode is not supported, so it may not be so useful in those Python versions. There might be a separate package that could be installed, but this would need more investigation.

.

.

Image breaks PDF

Since im using version 1.7.2 installed from github the pdf.image method breaks the PDF without throwing an exception or any other traceable error. All I get is:

Couldn’t open PDF
Something’s keeping this PDF from opening.

when i attemb to open the PDF.

This was working with version 1.7.2 installed via PIP, which doesn't provide an add_page method with format parameter, what is the reason why i have to use the github installation.

help ?
best regards

Apostrophe and Ampersand causing new column.

Hi
Am facing an issue with pyfpdf.
&, \x26, &, ', Apostrophe and Ampersand causing a new column.
any string having "&", breaks into a new column.
e.g "Hello & world" is creating 3 cells.
How to fix this issue?

Raise ValueError if txt argument passed to cell method is a dict

Because Python is a dynamically typed programming language it is important that libraries provide user-friendly error messages if you provided an argument of a wrong type.

I changed something in my application so that a dict with keys got unknowingly passed to the cell method. I then got a cryptic KeyError: 0 exception. It would be nice if pyfpdf would catch this and return something like txt can't be a dict.

from fpdf import FPDF

pdf = FPDF()
pdf.add_page()
pdf.set_font('Arial', 'B', 16)
pdf.cell(40, 10, {'name':'test'}, align='C')
pdf.output('tuto1.pdf', 'S')

write_html() containing image inside table row return weird

I got this following minimum example showing the weird result:

import fpdf
class MyPDF(fpdf.FPDF, fpdf.HTMLMixin):
    pass

html = '<table align="center" border="0" width="100%"><thead><tr><th width="40%">image1</th><th width="10%">date</th><th width="10%">time</th><th width="40%">image2</th></tr></thead><tbody><tr><td align="center"><img height="100" src="https://assets-cdn.github.com/images/modules/logos_page/GitHub-Mark.png" width="100" /></td><td align="center" height="100" width="8%">Text 1</td><td align="center" height="100" width="8%">Text 2</td><td align="center"><img height="100" src="https://assets-cdn.github.com/images/modules/logos_page/GitHub-Mark.png" width="100" /></td></tr></tbody></table>'
pdf = MyPDF()
pdf.write_html(html)
pdf.output('xxx.pdf')

The html alone is:

image1datetimeimage2
Text 1Text 2

However the rendered pdf got it's images in random places. (see attached)
screen shot 2016-06-07 at 7 08 51 pm

Am I missing something?

PyPI doesn't have up to date version of pyfpdf

pip install fpdf

there is a syntax error in the html.py for the version of fpdf thats installed via pip. On line 220,
NameError: global name 'color' is not defined

however on version 1.7.2 in the github repo it seems like the error is fixed.

Imprimir 2 hojas A5 en una A4

Estimados, estoy trabajando en un proyecto que imprimie docuemtos en A5. El papel que voy a usar es A4 y en la mitad esta troquelado para que el usuario final lo pueda cortar. Como mi aplicacion imprimite en A5 en duplicado, busco que emita dos paginas A5 en una hoja A4. Es posible? me puedan dar un orientacion?

Desde ya muchas gracias.

3 columns with multi_cell

i tried with

pdf.multi_cell(40,10,'column 1',1,0,'C')
pdf.multi_cell(40,10,'column 1',1,0,'C')
pdf.multi_cell(70,10,'column 1',1,0,'C')

but the cells appeared one below the other

How can i make three columns (side-by-side) with multi_cell?

create a text block area

I've trying to print a table which can support multiple lines over the heads or the content itself. The problem is that the multi_cell function only accept the height of the cells, so we cannot adjust the height size equally to all the multi_cells side by side. Like this example:

+---------------+---------------+----------------+
|               | one line text |                |
| Two line      +---------------+ Two line       |
| Text          |               | text           |
|               |               |                |
+---------------+               +----------------+

So we manage the columns (multi_cell) to have the same height per cell, but not the same area height which makes the usage of full border "incorrect". It can be used only the left and right border and then draw manually the top and bottom lines but the alignment of the text will be a problem. the one line of text will not be vertically aligned.

Basically the multi_cell cannot be used as a text box area. So i think the library is missing this: a text box area. I know this is not easy to implement, but i don't see any topic around here related to tries. So there is any plan to build this type of "widget", or it's just another of "shut up and find out other library"?

Well this project by far is the best i have found. It's pretty complete and easy to use. But has the same problem from the other: missing a text box area. If can get this the translation of html table, and the creation of table by template will be easy and less buggy.

add_page

I'm using the version 1.72 on Python. 2.7.
My add _page method lets me only specify the orientation, the other 2 parameters described in your documentation do not work.

TypeError: "...got an unexpected keyword argument..."

Any Ideas or alternatives?

Thanks a lot!! :)

different page margins in odd and even page

Hi
I´m using python 2.7 and pyfpdf 1.7.1
I would like to know how could I print odd and even pages with different margins like a book.
I try this code:

class PDF(FPDF):
def header(self):
if self.page_no()%2==0:
#print "even - par"
pdf.set_left_margin(10.0)
pdf.set_right_margin(20.0)
else:
#print "odd - impar"
pdf.set_left_margin(20.0)
pdf.set_right_margin(10.0)

It partially works but because I'm printing a document from a .csv file with a loop "like for row in reader:" the first line of each page continue with the previous margin adjustment.

please see the example attached.

could you please tell me if there is any solution?

regards

libro_2017-01-18.pdf

basic and promising table code?

So it's been a while i want to write down something that will help me out to draw a table. Last night a rushed some code and this is the result for now.

class BaseFPDF(FPDF, HTMLMixin):

    def draw_table(self,width,cell_line_height,rows,columns,table):

        max_x = self.get_x() + width

        column_width = width / columns

        base_x = [ self.get_x() + ( column_width * i ) for i in range(1,columns) ]

        base_x = [0] + base_x

        hline = lambda : self.line(self.get_x(),self.get_y(),max_x,self.get_y())

        bgn_y = self.get_y()

        print('Drawing table -> table width {} ({} to {}) , column width {}'.format(width,self.get_x(),max_x,column_width))
        print(base_x)

        for row in range(rows) :

            print('printing row {}'.format(row))
            # find out what is the great line height
            max_cell_height = (int(max([ self.get_string_width(cell) / column_width for cell in table[row] ])) + 1) * cell_line_height

            print('max cell height -> ' , max_cell_height)

            #self.line(self.get_x(),self.get_y(),max_x,self.get_y())
            hline()
            self.ln(1)
            base_y = self.get_y()

            for cell in table[row] :

                self.set_x(base_x[table[row].index(cell)]+self.get_x())

                self.multi_cell(column_width,cell_line_height,cell)

                self.set_y(base_y)

                print(self.get_x())

            #self.multi_cell(column_width,)

            self.ln(max_cell_height + 1) # jump to another row

        hline()

        for c in base_x :

            x = self.get_x() + c

            self.line( x , self.get_y() , x , bgn_y )

        self.line( max_x , self.get_y() , max_x , bgn_y )

    def get_max_page_width(self):

        if self.def_orientation == 'P' :

            return self.w - (self.l_margin + self.r_margin)

        else :

            return self.get_max_page_height()

    def get_max_page_height(self):

        if self.def_orientation == 'P' :

            return self.h - (self.b_margin + self.t_margin)

        else :

            self.get_max_page_width()

usage

pdf = BasePDF(...)
table = [
    ['1,1','1,2','1,3','1,4'],
    ['2,1','2,2','2,3','2,4'],
    ['3,1','3,2','3,3','3,4'],
    ['4,1','4,2','4,3','4,4'],
]

pdf.set_font('Arial','B',10)
pdf.cell(0,4,'Aplicações')

pdf.ln(4)

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

pdf.draw_table(self.get_max_page_width(),4,4,4,table)

The goal is to make it available by a fork, but i can only do this next week. Until there i want some opinions!

draw on the previous page

I need to draw a document with two column. The problem is that the content of both column are independent of each other. So the perfect scenario is the possibility to draw all the first column content, and the get back to the top of first page and draw the other column, because the the two columns have "dynamic" heights: some time the column 1 need 3 pages and column 2 just one.

I've searched over the API and didn't found a function to select the page we want to draw on, but there is anyway to that with the other functions available? (I could not understand would be possible)

thanks

table border=1 only show outer border and inner border on thead

with the above configuration i can get a full border painting over the thead tag, and around the table, but the row don't show a black line divider

<table border="1" cellpadding="5" cellspacing="5" width="100%">

    <thead>
        <tr>
            <th align="left" width="60%">Title 1</th>
            <th align="left" width="40%">Title 2</th>
        </tr>
    </thead>

    <tbody>
    <tr>
        <td>some text</td>
        <td>some text</td>
    </tr>

    </tbody>

</table>

Like this

+------------------------------------------------+
|  title 1               |  title 2              |
|                        |                       |
+------------------------------------------------+
|  some text             |  some text            |
|                        |                       |
|                        |                       |
|                        |                       |
|                        |                       |
|                        |                       |
|                        |                       |
|                        |                       |
+------------------------------------------------+

How can i make every row show a bottom line divider? .-.

PIL import issue, hash collision

Hello,

We have a project where we use PIL in multiple files. Installing pyfpdf through easy-install, we ran into the following error when loading the project through a webframework:

AccessInit: hash collision: 3 for both 1 and 1

I have googled a bit around and found http://jaredforsyth.com/blog/2010/apr/28/accessinit-hash-collision-3-both-1-and-1/ (look into the "docs_util patch" link).

I solved my problem by making the following modifications:
sitn@99da694

Is that of any interest ? (I'll be happy to submit a PR if yes...)

get_string_width results are far away from the correct value

Hi,

i tried to use the get_string_width to fit a text on a sheet. But the sizes returned does not fit to the printed result.

Maybe iam doing something wrong but it looks get_string_width is not working properly.

Here is my code i used:

import fpdf as pc

class InfoLabel():   

    def __init__(self):
        self.fontsize = 20
        self.format = (101.6, 152.4)
        self.margin = 5
        self.pdf = pc.FPDF(orientation='L', unit="mm", format=self.format)
        self.pdf.set_margins(self.margin, self.margin, self.margin)
        self.pdf.add_page()
        self.pdf.set_font('Arial', '', self.fontsize)
        self.pdf.compress = False # not supportet yet for python3


    def get_max_fontsize(self, text = ("Dies", "ist", "ein", "Test.")):
        print(text)
        fontsize = self.fontsize
        while not self.check_textlines_length(text, fontsize):
            fontsize -= 1
        return fontsize


    def check_textlines_length(self, text, fontsize):
        max_width = self.format[0] - (self.margin * 2)
        self.pdf.set_font_size(fontsize)
        for line in text:
            if line != "":
                string_width = self.pdf.get_string_width(line)
                print(fontsize, max_width, string_width, line)
                if string_width > max_width:
                    return(False)
        return(True)


    def print_text(self, text):
        #self.pdf.set_font_size(self.fontsize)
        self.pdf.write(10, text)


    def write_pdf(self):
        self.pdf.output('tuto1.pdf','F')


def main():
    text = """Es_ist_ein_paradiesmatisches_Land,
in_dem_einem_gebratene_Satzteile_in_den_Mund_fliegen.
Nicht_einmal_von_der_allmächtigen_Interpunktion_werden_die_Blindtexte_beherrscht
_ein_geradezu_unorthographisches_Leben.
"""

    label = InfoLabel()    
    max_fontsize = label.get_max_fontsize(text=text.split("\n"))
    label.print_text(text)
    label.write_pdf()


if __name__ == "__main__":
    main()

Auto page break margin - html table borders.

Two questions:

  1. I can't adjust the bottom margin with pdf.set_auto_page_break(auto: bool, margin = 0.0). It crashes the script, what is the proper syntax?
  2. The html table has a line at top and bottom, I do not want any borders. How do I eliminate the top and bottom lines?

Thanks.

cannot generate pdf with non-ascii characters inside

#-*-coding:latin-1 -*- 
pdf = FPDF(format='letter')
pdf.add_page()
pdf.set_font("Arial", size=12)
pdf.cell(200, 10, txt=u"呵呵", ln=1, align="C")
pdf.output("tutorial.pdf")

I have tried decoding and encoding in many ways when assigning the string to txt, none of them works.
Hope somebody tell me how to fix it, thx!
My environment is OS X, python 2.7.

Font color Fails in THEAD.

I'm trying to create a report from a HTML doc, but I have an issue with the html parser.

Rows of 'thead' section are not coloring well. That's my sample code:

from fpdf import FPDF, HTMLMixin
html = """
<H2 align="center">INFORME CAPACIDAD</H2>
<h3 align="center">AAAA</h3>
<center>
</center>

<table border="1" align="center" width="52%">
<thead><tr>
<th width="34%" bgcolor="#008000"><font color="#ffffff">Empresa</font></th>
<th width="34%" bgcolor="#008000"><font color="#ffffff">Numero Usuarios</font></th>
<th width="32%" bgcolor="#008000"><font color="#ffffff">Ratio Semanal</font></th></tr></thead>
<tbody><tr><td><font color='#FF0000'>empresa</font></td><td><font color='#00FF00'>aaaa</font></td><td>&nbsp;a</td></tr>
</tbody>
</table>
"""
class MyFPDF(FPDF, HTMLMixin):
    pass

pdf=MyFPDF()
pdf.add_page()
pdf.write_html(html)
pdf.output('test.pdf')

And the result shows as follow:

image

As you can see, THEAD must be black but appear in red. I hope you can help me with this issue.

TypeError while adding image

I get a strange error while trying to add a PNG to my PDF. The relevant traceback:

  File "/home/bas/projects/awesomeit/2016/awesomeit/pdf/gen.py", line 20, in gen_ticket_pdf
    pdf.image(qr_path)
  File "/home/bas/projects/awesomeit/2016/venv/lib/python3.4/site-packages/fpdf/fpdf.py", line 167, in wrapper
    return fn(self, *args, **kwargs)
  File "/home/bas/projects/awesomeit/2016/venv/lib/python3.4/site-packages/fpdf/fpdf.py", line 1004, in image
    info=self._parsepng(name)
  File "/home/bas/projects/awesomeit/2016/venv/lib/python3.4/site-packages/fpdf/fpdf.py", line 1903, in _parsepng
    f.read(n+4)
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

I have attached the PNG.
d76c0157410bd50af94731dc4f040821

p tag with align justify makes text overflow to right

I was using a p tag to holdup my text and decide to justify then setting up the align attribute

<p align="justify"></p>

The problem is that when i render the PDF without the align it generates a normal text with 8 lines, and when i put the align it generates a 2 line text. What's is missing is the automatic line break afaik.

So i'm missing something else here to get a justified text or it's just a "bug"?

PyFPDF GAE Support

When you add a font file in pyfpdf use the module to create a Pickle pkl file GAE has enhanced the functionality so that you can use to add information to the NDB font files have been created prohibited.

Branch Name: gae_support

RuntimeError "Table column/cell width not specified, unable to continue"

I was trying to render a html template (with django)

class MyFPDF(FPDF, HTMLMixin):
    pass
(...)
html = get_template('api/historico_easypdf.html').render(Context( context ))
print('done rendering')
pdf=MyFPDF()
pdf.add_page()
pdf.write_html(html)

which contains some tables (with this format)

<table border="1" cellpadding="5px">
    <tr>
        <td>
        <span>
            <b>(text ...)</b>
            <u>(text ...)</u>
        </span>&nbsp

        <span>
            <b>(text ...)</b>
            <u>(text ...)</u>
        </span>&nbsp
        </td>
    </tr>
</table>

this error was raised

ERROR 2015-04-02 17:26:02,810 base 72308 140735311446784 Internal Server Error: /api/pdf/historico/pre/1
Traceback (most recent call last):
  File "/Users/vyscond/Tartarus/myproj/.venv/lib/python3.4/site-packages/fpdf/html.py", line 72, in handle_data
    l = [self.table_col_width[self.table_col_index]]
IndexError: list index out of range

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/vyscond/Tartarus/myproj/.venv/lib/python3.4/site-packages/django/core/handlers/base.py", line 111, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/vyscond/Tartarus/myproj/.venv/lib/python3.4/site-packages/django/views/decorators/csrf.py", line 57, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/vyscond/Tartarus/myproj/.venv/lib/python3.4/site-packages/django/views/decorators/http.py", line 41, in inner
    return func(request, *args, **kwargs)
  File "/Users/vyscond/Tartarus/myproj/api/genpdf.py", line 78, in historico_preliminar
    pdf.write_html(html)
  File "/Users/vyscond/Tartarus/myproj/.venv/lib/python3.4/site-packages/fpdf/html.py", line 401, in write_html
    h2p.feed(text)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/html/parser.py", line 165, in feed
    self.goahead(0)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/html/parser.py", line 216, in goahead
    self.handle_data(rawdata[i:j])
  File "/Users/vyscond/Tartarus/myproj/.venv/lib/python3.4/site-packages/fpdf/html.py", line 74, in handle_data
    raise RuntimeError("Table column/cell width not specified, unable to continue")
RuntimeError: Table column/cell width not specified, unable to continue
Internal Server Error: /api/pdf/historico/pre/1
Traceback (most recent call last):
  File "/Users/vyscond/Tartarus/myproj/.venv/lib/python3.4/site-packages/fpdf/html.py", line 72, in handle_data
    l = [self.table_col_width[self.table_col_index]]
IndexError: list index out of range

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/vyscond/Tartarus/myproj/.venv/lib/python3.4/site-packages/django/core/handlers/base.py", line 111, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/vyscond/Tartarus/myproj/.venv/lib/python3.4/site-packages/django/views/decorators/csrf.py", line 57, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/vyscond/Tartarus/myproj/.venv/lib/python3.4/site-packages/django/views/decorators/http.py", line 41, in inner
    return func(request, *args, **kwargs)
  File "/Users/vyscond/Tartarus/myproj/api/genpdf.py", line 78, in historico_preliminar
    pdf.write_html(html)
  File "/Users/vyscond/Tartarus/myproj/.venv/lib/python3.4/site-packages/fpdf/html.py", line 401, in write_html
    h2p.feed(text)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/html/parser.py", line 165, in feed
    self.goahead(0)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/html/parser.py", line 216, in goahead
    self.handle_data(rawdata[i:j])
  File "/Users/vyscond/Tartarus/myproj/.venv/lib/python3.4/site-packages/fpdf/html.py", line 74, in handle_data
    raise RuntimeError("Table column/cell width not specified, unable to continue")
RuntimeError: Table column/cell width not specified, unable to continue

So i am missing some configuration over the object MyPDF or on html? .-.

Setting a default font

Any reason there is not a default font selected when creating a FPDF instance? Currently if we do not use set_font before writing a cell, the module gives a object has no attribute 'unifontsubset' error message.

I noticed the HTMLMixin does selects a default font. Will the project be interested in a patch to enable this?

Storage for project artifacts (fonts, images, etc)

Currently we use some data on external server and not in repository:

  • fpdf_unicode_font_pack.zip - 15.7Mb, fonts used by tests, tutorials, examples
  • tuto*.pdf - approximately 100Kb, PDF samples
  • perhaps something other

This files server from googlecode, which will be closed for changing. Github doesn't provide space for binary storage.

Any proposes?

Generating a BytesIO with FPDF.output

I've tried all the options over the FPDF.output to produce an valid output to send as a web response using Django's HttpResponse object.

With the String (S) option i can generate a blank PDF and with all the other options the browser just render a grey background and the message of "Loading" (using chrome for testing).

So i was thinking if it's possible to have another type of dest over the output function to generate an BytesIO object. With this format it's (simple to embed)[https://docs.djangoproject.com/en/1.7/howto/outputting-pdf/#complex-pdfs] it to the response on Django.

Strong and Em tag support in HTMLMixin

I am using the HTMLMixin to write a simple rich text field into a PDF report. It works fine, but strong and em tags are not supported. Looking at html.py, they have been added in for closing tags, but not opening tags. Copy pasting the strong to b tag, and em to i tag conversion from handle_endtag at line 296 to handle_starttag in html.py at line 172 fixes it for me.

I have added a string replacement to my code to handle this bug and it all formats perfectly, but it would just be nice to finish the half implemented functionality in the html.py file.

Thanks

UserWarning: cmap value too big/small: -33395

I try to test pyfpdf with outputting Chinese pdf on my Fedora21. Here are the codes:

pdf = FPDF()
pdf.add_page()
pdf.add_font('fireflysung', '', '/usr/share/fonts/fireflysung/fireflysung.ttf', uni=True)
pdf.set_font('fireflysung', '', 16)
pdf.write(10, u'edony\n糯米517吃货节\n')
pdf.ln(10)
pdf.output('test.pdf', 'F')

But the warning comes and the test.pdf seems perfect.

pyfpdf/fpdf/ttfonts.py:671: UserWarning: cmap value too big/small: -33395
  warnings.warn("cmap value too big/small: %s" % cm)
pyfpdf/fpdf/ttfonts.py:671: UserWarning: cmap value too big/small: -36119
  warnings.warn("cmap value too big/small: %s" % cm)

Personally, this is fireflysung font's problem. I don't know why! What should I do to solve it?
I download the font from http://www.study-area.org/apt/firefly-font/fireflysung-1.3.0.tar.gz.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.