source : impression python
reportlab yes Python A library of standards , You can draw pictures. 、 Draw a chart 、 Edit text , Finally, you can output PDF Format . Its logic and editing a word Document or PPT It's like . There are two ways :
1) Create a blank document , Then write on it 、 Drawing, etc ;
2) Create a blank list, Insert various text boxes in the form of a filled table 、 Pictures, etc , The last generation PDF file .
Because you need to generate a report for users to see , You need to insert pictures inside 、 Forms, etc , So the second method is adopted .
reportlab Input Python Third party library , It needs to be installed before use :pip install reportlab
Import relevant content in advance , And register fonts .( Before registering fonts, you need to prepare font files )
from reportlab.pdfbase import pdfmetrics # Register Fonts
from reportlab.pdfbase.ttfonts import TTFont # Font class
from reportlab.platypus import Table, SimpleDocTemplate, Paragraph, Image # Report content related classes
from reportlab.lib.pagesizes import letter # Logo size of the page (8.5*inch, 11*inch)
from reportlab.lib.styles import getSampleStyleSheet # Text style
from reportlab.lib import colors # Color module
from reportlab.graphics.charts.barcharts import VerticalBarChart # Chart class
from reportlab.graphics.charts.legends import Legend # Legend class
from reportlab.graphics.shapes import Drawing # Drawing tools
from reportlab.lib.units import cm # Company :cm
# Register Fonts ( Prepare the font file in advance , If the same file needs multiple fonts, you can register multiple fonts )
pdfmetrics.registerFont(TTFont('SimSun', 'SimSun.ttf'))
Create a Graphs class , Provide different report contents through different static methods , Include : title 、 Ordinary paragraphs 、 picture 、 Tables and charts . At present, most of the relevant data in the function are fixed values , It can be set to relevant parameters according to the situation .
class Graphs:
# Draw the title
@staticmethod
def draw_title(title: str):
# Get all stylesheets
style = getSampleStyleSheet()
# Get the title style
ct = style['Heading1']
# Set style related properties separately
ct.fontName = 'SimSun' # Font name
ct.fontSize = 18 # font size
ct.leading = 50 # Row spacing
ct.textColor = colors.green # The font color
ct.alignment = 1 # In the middle
ct.bold = True
# Create a paragraph corresponding to the title , And back to
return Paragraph(title, ct)
# Draw subtitles
@staticmethod
def draw_little_title(title: str):
# Get all stylesheets
style = getSampleStyleSheet()
# Get the title style
ct = style['Normal']
# Set style related properties separately
ct.fontName = 'SimSun' # Font name
ct.fontSize = 15 # font size
ct.leading = 30 # Row spacing
ct.textColor = colors.red # The font color
# Create a paragraph corresponding to the title , And back to
return Paragraph(title, ct)
# Draw normal paragraph content
@staticmethod
def draw_text(text: str):
# Get all stylesheets
style = getSampleStyleSheet()
# Get normal styles
ct = style['Normal']
ct.fontName = 'SimSun'
ct.fontSize = 12
ct.wordWrap = 'CJK' # Set auto wrap
ct.alignment = 0 # Align left
ct.firstLineIndent = 32 # Space at the beginning of the first line
ct.leading = 25
return Paragraph(text, ct)
# Draw table
@staticmethod
def draw_table(*args):
# Column width
col_width = 120
style = [
('FONTNAME', (0, 0), (-1, -1), 'SimSun'), # typeface
('FONTSIZE', (0, 0), (-1, 0), 12), # The font size of the first line
('FONTSIZE', (0, 1), (-1, -1), 10), # Font size from the second line to the last line
('BACKGROUND', (0, 0), (-1, 0), '#d5dae6'), # Set the background color of the first line
('ALIGN', (0, 0), (-1, -1), 'CENTER'), # The first line is horizontally centered
('ALIGN', (0, 1), (-1, -1), 'LEFT'), # Align the second line to the last line left and right
('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), # All tables are centered up and down
('TEXTCOLOR', (0, 0), (-1, -1), colors.darkslategray), # Set the text color in the table
('GRID', (0, 0), (-1, -1), 0.5, colors.grey), # Set the table border to grey color , The line width is 0.5
# ('SPAN', (0, 1), (0, 2)), # Merge the first column, two or three rows
# ('SPAN', (0, 3), (0, 4)), # Merge the first column, three or four rows
# ('SPAN', (0, 5), (0, 6)), # Merge five or six rows in the first column
# ('SPAN', (0, 7), (0, 8)), # Merge five or six rows in the first column
]
table = Table(args, colWidths=col_width, style=style)
return table
# Create a chart
@staticmethod
def draw_bar(bar_data: list, ax: list, items: list):
drawing = Drawing(500, 250)
bc = VerticalBarChart()
bc.x = 45 # Of the whole chart x coordinate
bc.y = 45 # Of the whole chart y coordinate
bc.height = 200 # Height of chart
bc.width = 350 # Width of chart
bc.data = bar_data
bc.strokeColor = colors.black # Color of the top and right axes
bc.valueAxis.valueMin = 5000 # Set up y The minimum of the coordinates
bc.valueAxis.valueMax = 26000 # Set up y Maximum of coordinates
bc.valueAxis.valueStep = 2000 # Set up y Step size of coordinates
bc.categoryAxis.labels.dx = 2
bc.categoryAxis.labels.dy = -8
bc.categoryAxis.labels.angle = 20
bc.categoryAxis.categoryNames = ax
# Icon
leg = Legend()
leg.fontName = 'SimSun'
leg.alignment = 'right'
leg.boxAnchor = 'ne'
leg.x = 475 # Legend of the x coordinate
leg.y = 240
leg.dxTextSpace = 10
leg.columnMaximum = 3
leg.colorNamePairs = items
drawing.add(leg)
drawing.add(bc)
return drawing
# Drawing pictures
@staticmethod
def draw_img(path):
img = Image(path) # Read the picture under the specified path
img.drawWidth = 5*cm # Set the width of the picture
img.drawHeight = 8*cm # Set the height of the picture
return img
if __name__ == '__main__':
# Create an empty list corresponding to the content
content = list()
# Add the title
content.append(Graphs.draw_title(' Data analysis employment salary '))
# Add images
content.append(Graphs.draw_img(' The fight against the epidemic will win .png'))
# Add paragraph text
content.append(Graphs.draw_text(' as everyone knows , The position of big data analyst is a sweet pastry , In recent years, data analysis has swept the entire Internet industry , Job recruitment related to data analysis 、 Training is endless . Many people go one after another , Want to participate in this wave of dividends . So what about the employment prospects of data analysts ?'))
# Add a subtitle
content.append(Graphs.draw_title(''))
content.append(Graphs.draw_little_title(' Average salary at different levels '))
# Add table
data = [
(' Job title ', ' Average salary ', ' Year on year growth rate '),
(' Data Analyst ', '18.5K', '25%'),
(' Senior Data Analyst ', '25.5K', '14%'),
(' Senior Data Analyst ', '29.3K', '10%')
]
content.append(Graphs.draw_table(*data))
# Generate charts
content.append(Graphs.draw_title(''))
content.append(Graphs.draw_little_title(' Employment in popular cities '))
b_data = [(25400, 12900, 20100, 20300, 20300, 17400), (15800, 9700, 12982, 9283, 13900, 7623)]
ax_data = ['BeiJing', 'ChengDu', 'ShenZhen', 'ShangHai', 'HangZhou', 'NanJing']
leg_items = [(colors.red, ' Average salary '), (colors.green, ' Recruitment volume ')]
content.append(Graphs.draw_bar(b_data, ax_data, leg_items))
# Generate pdf file
doc = SimpleDocTemplate('report.pdf', pagesize=letter)
doc.build(content)
The results of the report generation are as follows :
Recommended reading :
introduction : The most complete zero Foundation Python The problem of | Zero Basics 8 Months Python | Actual project | learn Python That's the shortcut
dried food : A short comment on crawling Douban , The movie 《 The rest of us 》 | 38 year NBA Best player analysis | From people's expectation to public praise ! Tang Dynasty detective 3 disappointing | Laugh at the story of the new Yitian dragon slaying | Riddle answer King | use Python Make a massive sketch of my little sister | Mission impossible is so hot , I use machine learning to make a mini recommendation system movie
Interest : Pinball game | squared paper for practicing calligraphy | Beautiful flowers | Two hundred lines Python《 Cool run every day 》 game !
AI: A robot that can write poetry | Color the picture | Forecast revenue | Mission impossible is so hot , I use machine learning to make a mini recommendation system movie
Gadget : Pdf turn Word, Easily handle forms and watermarks ! | One touch html Save the page as pdf!| bye PDF Withdrawal charges ! | use 90 Lines of code create the strongest PDF converter ,word、PPT、excel、markdown、html One click conversion | Make a nail low-cost ticket reminder ! |60 Line of code to do a voice wallpaper switcher, look at my little sister every day !|