Reportlab pdf example
Toggle navigation Code Maven. Python Python Listing a directory using Python How to insert a dictionary in another dictionary in Python How to merge two dictionaries range vs.
Skeleton: A minimal example generating HTML with Python Jinja Simple logging in Python Logging in Python Python argparse to process command line arguments Using the Open Weather Map API with Python Python: seek - move around in a file and tell the current location Python: Capture standard output, standard error, and the exit code of a subprocess Python: Iterate over list of tuples Print version number of Python module Python: Repeat the same random numbers using seed Python: split command line into pieces as the shell does - shlex.
Prev Next. Install the reportlab module using: pip install reportlab. We have more content, but the appearance is still not ideal. Let's see how we can use a page template to arrange our content. Go back to templates and take note of each part:. By default, the PDF rendering engine uses the first template until it is told otherwise, so in this case, 'blank' has been used on all pages.
Notice that a nice PDF background has been used on which the products list is printed. That can also be used to include full static pages. Let's use pre-made PDFs to replace the blank first page and insert a standard end page. Your story should look like this:. Ideally, we would be able to keep the descriptions from breaking across pages, so that all the information about a product stayed together.
Your stylesheet should now look like this:. Finally, let's get our colors and fonts correct. We can register a new font and a new color in the docinit section; edit yours to look like this:.
And there you have it, a professionally finished document created on the fly from an XML file. There is plenty more to learn to control the flow for more complex documents - see the RML users guide. Now let's turn our attention to how we passed the data into the template in the first place.
For now, lets focus on lines , where we see the main loop over the XML to build product objects:. ModelNumber prod. ModelName prod. Summary prod. Description if prod. UnitCost [0:len str prodTag. UnitCost -2] if prod. Remember how the checklist has been failing to generate?
This is because the PDF engine has been complaining that the Prep file is trying to access an attribute img of the products which does not exist. Let's try giving our product objects an attribute based on this:. Description prod. ImageUrl [-1]. Now try building the document again. Let's tidy up this issue when there is no set price and the 'request a quote' text does not fit into the small box. Let's put a conditional statement in our template which uses a different size box when the quote gets big.
Let's take a look:. Drawing a line in ReportLab is actually quite easy. Once you get used to it, you can actually create very complex drawings in your documents, especially when you combine it with some of ReportLab's other features.
The method to draw a straight line is simply line. Then you set the line's width via the setLineWidth method. Finally, you create a single line. The line method accepts four arguments: x1, y1, x2, y2. These are the beginning x and y coordinates as well as the ending x and y coordinates. You add another 10 lines by using a for loop. The canvas supports several other drawing operations. For example, you can also draw rectangles, wedges and circles.
Here's a simple demo:. Let's take a few moments to go over the various arguments that each of these polygon methods accepts. The rect's code signature looks like this:. Then you set its width and height. The fill parameter tells ReportLab to fill the interior of the polygon that I drew with a color. This one is very similar to the rect. According to method's docstring, the x1, y1, x2, y2 parameters are the corner points of the enclosing rectangle.
The stroke and fill parameters operate the same way as the rect's. Just for fun, you went ahead and set the ellipse's fill to 1. The x1,y1, x2,y2 parameters for the wedge actually correspond to the coordinates of an invisible enclosing rectangle that goes around a full degree circle version of the wedge.
So you will need to imagine that the full circle with a rectangle around it to help you position a wedge correctly. It also has a starting angle parameter startAng and the extent parameter, which basically tells the wedge how far out to arc to.
The other parameters have already been explained. The circle's arguments are probably the most self-explanatory of all of the polygons you have looked at. The r argument is the radius. The stroke and fill arguments are pretty obvious. It accepts Red, Green, Blue values for its parameters.
There are corresponding fill color setters too i. You can use the functions by passing in the correct name or tuple to the appropriate function. One of the first things you will want to know how to do when creating PDFs with ReportLab is how to add a page break so you can have multipage PDF documents.
The canvas object allows you to do this via the showPage method. Note however that for complex documents, you will almost certainly use ReportLab's flowables, which are special classes specifically for "flowing" your documents across multiple pages. Flowables are kind of mind-bending in their own right, but they are also a lot nicer to use than trying to keep track of which page you are on and where your cursor position is at all times. ReportLab defaults its page orientation to Portrait, which is what all word processors do as well.
But sometimes you will want to use a page in landscape instead. There are at least two ways to tell Reportlab to use a landscape:. Sometimes it's nice to see how you can take what you've learned and see if applied.
So let's take some of the methods you've learned about here and create a simple application that creates a form:. Then you paint everything in the desired locations and save the file. When you run this, you will see the following:. You learned a lot about ReportLab's canvas and its many methods in this tutorial. While all the canvas methods weren't covered, you now know how to do the following:. Give ReportLab a try. You will find it is very useful and soon you will be creating amazing PDF reports of your very own!
Want to learn more about what you can do with ReportLab and Python? We use it to create form letters for people who have overdue parking tickets. The following example is based on some code I wrote for that application, although the letter is quite a bit different.
Note that the code below will not run without the Python Imaging Library. Well, that's a lot more code than our previous examples contained. We'll need to look over it slowly to understand everything that's going on. When you're ready, just continue reading. There are a number of other constants we could import that would allow us to right or left justify our text and do other fun things.
It contains lots of modules, but probably the most important of them are the flowables, such as Paragraph. A flowable typically has the following abilities: wrap , draw and sometimes split. They are used to make writing paragraphs, tables and other constructs over multiple pages easier to do. The SimpleDocTemplate class allows us to set up margins, page size, filename and a bunch of other settings for our document all in one place.
A Spacer is good for adding a line of blank space, like a paragraph break. ParagraphStyle is used to set our paragraph's text alignment in this example, but it can do much more than that see page 67 of the user guide.
Finally, the inch is a unit of measurement to help in positioning items on your PDF. This means that the logo will be two inches from the top and two inches from the left. I don't recall the reason why Reportlab's examples use a Story list, but that's how we'll do it here as well. Basically you create a line of text, a table, and image or whatever and append it to the Story list. You'll see that throughout the entire example. The first time we use it is when we add the image. Before we look at the next instance, we'll need to look at how we add a style to our styles object:.
The reason this is important is because you can use the style list to apply various paragraph alignment settings and more to text in your document. In the code above, we create a ParagraphStyle called "Justify".
0コメント