Python Self-Learning Manual
When making reports or writing proposals, have you ever encountered this situation? Using a PDF editor to manually draw flowcharts and annotate shapes is not only time-consuming but also difficult to align. Every modification requires readjustment — actually, with Python, you can automate the drawing of lines, rectangles, circles, and various shapes with just a few lines of code, generating a PDF that is both standardized and aesthetically pleasing.
Today, I will guide you through using the reportlab library to master PDF graphic drawing techniques from scratch. All code is directly copyable and executable, whether for generating annotated reports or creating flowcharts, you can easily accomplish it!
1. Preparation: 3 minutes to set up the environment
The core library we will use this time is reportlab, which is a Python library specifically designed for generating PDFs, supporting various functions such as graphic drawing and text typesetting. It is easy to install and highly compatible, allowing beginners to quickly get started.
1.1 Install the core library
Open the command prompt on your computer (Windows: press Win+R, type cmd; Mac: open the terminal), enter the following command, and wait for about 10 seconds to complete the installation:
|
pip install reportlab # If prompted with a permission issue, add the –user parameter:pip install reportlab –user |
1.2 Core tool explanation
We mainly use the canvas class from reportlab, which acts like an “electronic canvas”, where all graphics are drawn. Understanding these 3 core concepts in advance will make the subsequent code easy to understand:
|
Core Concept |
Description |
Key Points |
|
Canvas object |
Creates a PDF file, serving as the drawing “canvas” |
Must specify the save path and page size during initialization (default A4) |
|
Coordinate System |
Locates the position of graphics, with the bottom left corner of the page as the origin(0,0) |
The A4 paper size is 21cm×29.7cm, it is recommended to use cm for a more intuitive unit |
|
Drawing Methods |
For example, line() draws a line, rect() draws a rectangle, called as needed |
Each method requires passing coordinates or size parameters, pay attention to the order of parameters |
|
Important Note: The origin of the coordinates in reportlab is at the bottom left of the page, which is different from our daily habit of “top to bottom”, so be careful when calculating y axis coordinates! |
2. Practical Application: 5 types of shape drawing code (copy and use)
We will explain the drawing methods for lines, rectangles, circles/ellipses, and polygons from basic to complex. Each example includes “scene+code+parameter explanation+effect preview“, helping you quickly understand and reuse.
All code follows the logic of “create canvas → set style → draw graphics → save file”, first unifying the initialization of the canvas (the following examples can directly reuse this part of the code):
|
pythonfrom reportlab.pdfgen import canvasfrom reportlab.lib.pagesizes import A4 # A4 paper sizefrom reportlab.lib.units import cm # Import centimeter unit (more in line with daily habits)# 1. Create canvas: specify save path, page size as A4pdf_canvas = canvas.Canvas(“PDF Graphic Drawing Example.pdf”, pagesize=A4)# 2. Optional: set page titlepdf_canvas.setTitle(“Python PDF Graphic Drawing Tutorial”) |
2.1 Draw Lines: Essential for Annotations and Dividers
Applicable scenarios: PDF page dividers, table borders, graphic auxiliary lines, etc. The core method is line(x1, y1, x2, y2), passing in the starting and ending coordinates.
|
python# ————— Draw Line —————# 1. Draw a default style line (black, thin): from (1cm,28cm) to (20cm,28cm)pdf_canvas.line(1*cm, 28*cm, 20*cm, 28*cm)# 2. Draw a red line: set color first, then drawpdf_canvas.setStrokeColorRGB(1, 0, 0) # RGB color: redpdf_canvas.line(1*cm, 27*cm, 20*cm, 27*cm)# 3. Draw a thick line: set line width to 2ptpdf_canvas.setLineWidth(2) # Line width, unit ptpdf_canvas.line(1*cm, 26*cm, 20*cm, 26*cm)# 4. Reset style (to avoid affecting subsequent graphics)pdf_canvas.setStrokeColorRGB(0, 0, 0) # Restore blackpdf_canvas.setLineWidth(1) # Restore default width |
|
Effect Preview: At the top of the page, there will be 3 lines, which are default black thin line, red thin line, and black thick line, clearly distinguishing different styles, which can be directly used as page title dividers. |
2.2 Draw Rectangles: The Ultimate Tool for Selection and Area Division
Applicable scenarios: text box borders, data area division, decision boxes in flowcharts, etc. Supports ordinary rectangles, filled color rectangles, and rounded rectangles, with core methods being rect() and roundRect() methods.
|
python# ————— Draw Rectangle —————# 1. Ordinary rectangle: top left corner (x1,y1), width width, height heightpdf_canvas.rect(2*cm, 23*cm, 5*cm, 3*cm) # Top left corner (2,23), width 5cm, height 3cm# 2. Filled gray rectangle: fill=1 indicates fillingpdf_canvas.setFillColorRGB(0.8, 0.8, 0.8) # Light graypdf_canvas.rect(9*cm, 23*cm, 5*cm, 3*cm, fill=1)# 3. Rounded rectangle: the last parameter is the corner radiuspdf_canvas.setFillColorRGB(1, 1, 1) # Restore white fillpdf_canvas.roundRect(16*cm, 23*cm, 5*cm, 3*cm, 0.5*cm, fill=1) |
Parameter explanation:rect(x, y, width, height, fill=0), where (x,y) is the top left corner coordinate, fill=1 represents filled color, fill=0 only draws the border; the last parameter of the rounded rectangle is the radius of the corner, the larger the value, the more pronounced the rounded corner.
2.3 Draw Circles and Ellipses: Data Annotations and Decorative Elements
Applicable scenarios: highlighting key data (such as circular highlights), pie chart basics in graphs, decorative elements, etc. Use circle() for circles and ellipse() for ellipses.
|
python# ————— Draw Circles and Ellipses —————# 1. Ordinary circle: center (x,y), radius rpdf_canvas.circle(5*cm, 18*cm, 2*cm) # Center (5,18), radius 2cm# 2. Blue filled circlepdf_canvas.setFillColorRGB(0, 0, 1) # Bluepdf_canvas.circle(11*cm, 18*cm, 2*cm, fill=1)# 3. Ordinary ellipse: top left corner (x1,y1), bottom right corner (x2,y2)pdf_canvas.setFillColorRGB(1, 1, 1) # Whitepdf_canvas.ellipse(15*cm, 16*cm, 19*cm, 18*cm) # Top left (15,16), bottom right (19,18)# 4. Orange filled ellipsepdf_canvas.setFillColorRGB(1, 0.5, 0) # Orangepdf_canvas.ellipse(15*cm, 13*cm, 19*cm, 15*cm, fill=1)# Reset fill color to whitepdf_canvas.setFillColorRGB(1, 1, 1) |
2.4 Draw Polygons: Custom Shapes and Flowchart Basics
Applicable scenarios: arrows in flowcharts, triangular annotations, custom shapes (like pentagons), etc. The core method is polygon(), passing in the coordinates of multiple vertices.
|
python# ————— Draw Polygon —————# 1. Ordinary triangle: pass in 3 vertex coordinates [(x1,y1), (x2,y2), (x3,y3)]pdf_canvas.polygon([(2*cm, 10*cm), (7*cm, 10*cm), (4.5*cm, 14*cm)])# 2. Green filled trianglepdf_canvas.setFillColorRGB(0, 1, 0) # Greenpdf_canvas.polygon([(9*cm, 10*cm), (14*cm, 10*cm), (11.5*cm, 14*cm)], fill=1)# 3. Pentagon: pass in 5 vertex coordinatespdf_canvas.setFillColorRGB(1, 1, 1) # Whitepdf_canvas.polygon([(16*cm, 10*cm), (19*cm, 11*cm), (18*cm, 14*cm), (14*cm, 14*cm), (13*cm, 11*cm)]) |
|
Tip: When drawing polygons, arrange the vertex coordinates in “clockwise or “counterclockwise order to avoid crossing or confusion; if you want to draw arrows, you can combine triangles and lines. |
3. Advanced: Combining Text and Graphics (Practical Scenarios)
In actual work, graphics often need to be accompanied by text explanations for clarity. Below, I will teach you how to add annotations to graphics and create text boxes with borders, making the PDF content more complete.
|
python# ————— Combine Text and Graphics —————# 1. Set font: font name, font size (unit pt)pdf_canvas.setFont(“Helvetica”, 12)# 2. Add explanatory text next to the graphicspdf_canvas.drawString(2*cm, 22*cm, “Ordinary Rectangle”)pdf_canvas.drawString(9*cm, 22*cm, “Filled Gray Rectangle”)pdf_canvas.drawString(2*cm, 9*cm, “Triangle Example”)pdf_canvas.drawString(15*cm, 15*cm, “Ellipse Example”)# 3. Create a text box with a border# First draw the rectangle borderpdf_canvas.rect(1*cm, 2*cm, 19*cm, 5*cm)# Then add text (use drawString with different y coordinates for line breaks)pdf_canvas.setFont(“Helvetica”, 14) # Title font sizepdf_canvas.drawString(2*cm, 6*cm, “Python PDF Graphic Drawing Summary”)pdf_canvas.setFont(“Helvetica”, 12) # Body font sizepdf_canvas.drawString(2*cm, 5*cm, “1. Use line() to draw lines, setStrokeColorRGB() to change color”)pdf_canvas.drawString(2*cm, 4*cm, “2. Use rect()/roundRect() to draw rectangles, supporting rounded corners and filling”)pdf_canvas.drawString(2*cm, 3*cm, “3. Use polygon() for complex shapes, just pass in vertex coordinates”)# Save PDF (must call save() to generate the file)pdf_canvas.save()print(“PDF file has been generated! Path: Current folder/PDF Graphic Drawing Example.pdf”) |
4. Practical Case: Generate a Workflow Diagram
Combining the knowledge above, let’s create a high-frequency practical scenario — generating a “Data Processing Flowchart”, using this template directly to quickly create various business flowcharts.
|
pythonfrom reportlab.pdfgen import canvasfrom reportlab.lib.pagesizes import A4from reportlab.lib.units import cm# Create a new canvasflow_canvas = canvas.Canvas(“Data Processing Flowchart.pdf”, pagesize=A4)flow_canvas.setTitle(“Data Processing Flowchart”)# 1. Draw flow boxes (rounded rectangles)flow_canvas.setFillColorRGB(0.95, 0.95, 0.95) # Light gray fillflow_canvas.roundRect(5*cm, 25*cm, 10*cm, 2*cm, 0.3*cm, fill=1) # Start boxflow_canvas.roundRect(5*cm, 21*cm, 10*cm, 2*cm, 0.3*cm, fill=1) # Data input boxflow_canvas.roundRect(5*cm, 17*cm, 10*cm, 2*cm, 0.3*cm, fill=1) # Processing boxflow_canvas.roundRect(5*cm, 13*cm, 10*cm, 2*cm, 0.3*cm, fill=1) # Output boxflow_canvas.roundRect(5*cm, 9*cm, 10*cm, 2*cm, 0.3*cm, fill=1) # End box# 2. Draw arrows (line + triangle)def draw_arrow(canvas, x1, y1, x2, y2): “””Draw an arrow: from (x1,y1) to (x2,y2)””” # Draw line canvas.line(x1, y1, x2, y2) # Draw arrowhead (triangle) canvas.polygon([(x2, y2), (x2-0.3*cm, y2+0.2*cm), (x2-0.3*cm, y2-0.2*cm)])# Call arrow functiondraw_arrow(flow_canvas, 10*cm, 25*cm, 10*cm, 23*cm) # Start → Inputdraw_arrow(flow_canvas, 10*cm, 21*cm, 10*cm, 19*cm) # Input → Processingdraw_arrow(flow_canvas, 10*cm, 17*cm, 10*cm, 15*cm) # Processing → Outputdraw_arrow(flow_canvas, 10*cm, 13*cm, 10*cm, 11*cm) # Output → End# 3. Add flow textflow_canvas.setFont(“Helvetica”, 12)flow_canvas.drawCentredString(10*cm, 26*cm, “Start”)flow_canvas.drawCentredString(10*cm, 22*cm, “Input Raw Data”)flow_canvas.drawCentredString(10*cm, 18*cm, “Python Cleans/Analyzes Data”)flow_canvas.drawCentredString(10*cm, 14*cm, “Generate PDF Report”)flow_canvas.drawCentredString(10*cm, 10*cm, “End”)# Save fileflow_canvas.save()print(“Flowchart PDF has been generated!”) |
In this case, we encapsulated the draw_arrow() function to achieve arrow reuse. When modifying the flow later, you only need to adjust the coordinates and text of the flow boxes, greatly improving efficiency.
5. Common Problems and Solutions
•Problem1: Running the code reports an error “Cannot find reportlab library”?Solution: Re-execute the installation command. If using the Anaconda environment, it must be installed in the Anaconda Prompt; if prompted that “pip” is not an internal command, you need to configure the Python environment variable.
•Problem2: The generated PDF displays garbled Chinese characters?Solution: reportlab does not support Chinese fonts by default, you need to manually specify the Chinese font, the code is as follows:from reportlab.pdfbase import pdfmetricsfrom reportlab.pdfbase.ttfonts import TTFontpdfmetrics.registerFont(TTFont(‘SimHei’, ‘SimHei.ttf’)) # Register SimHeipdf_canvas.setFont(‘SimHei’, 12) # Use SimHei(ensure that the computer has the SimHei.ttf font file)
•Problem3: The graphic positions are always misaligned?Solution: Using cm (centimeters) as the unit is more intuitive than pt; you can first mark the graphic positions on paper, then convert them into coordinates; the effective drawing area of A4 paper is recommended to be controlled within 1-20cm (x axis), 2-28cm (y axis), to avoid content being cut off.
6. Summary and Interaction
Today, we used the reportlab library to achieve the drawing of 5 types of graphics, from basic lines and rectangles to practical flowcharts. The core is to “master the coordinate rules + call the corresponding methods”. These skills can help you completely get rid of the hassle of manually drawing PDF graphics, whether for generating reports, creating tutorials, or automating office tasks, they can be very useful.
Have you encountered any difficulties in handling PDF in your work? For example, batch adding graphic annotations to PDFs, generating PDFs with charts, etc., feel free to leave a message in the comments, and next time we will explain it specifically!
If you find it useful, remember to like + watch + share, follow me, and unlock more Python office automation skills in the future~