Because of work requirements, I often need to generate a lot of PDF reports for customers to check the product effects and explain the process.
Every time you need to write documents in a certain format and generate PDF reports, this repetitive work is really tiring.
I am thinking that I can use python to generate a report for users, which needs to insert pictures, tables, text descriptions, etc.
Using the third-party python non-standard module reportlab can meet the need to directly generate PDF reports. Since it is a non-standard library, you need to use pip to install the module.
Use pip to install the reportlab module, which supports generating PDF documents.
pip install reportlab -i https://pypi.tuna.tsinghua.edu.cn/simple
If the C environment is missing during the installation process and the build fails, you can directly choose to use the wheel file to install the reportlab module.
The download address of the .whl file is as follows: https://www.lfd.uci.edu/~gohlke/pythonlibs/
Store after downloading is complete Go to the local disk and install the reportLab module according to the storage path. For the installation method, please refer to the installation method below.
pip install wheel -i https://pypi.tuna.tsinghua.edu.cn/simple pip install D:\downloads\reportlab-3.5.57-cp36-cp36m-win_amd64.whl
Import the python objects that need to be used in the reportlab module into the current code block in advance.
from reportlab.pdfbase import pdfmetrics # 注册字体 from reportlab.pdfbase.ttfonts import TTFont # 字体类 from reportlab.platypus import Table, SimpleDocTemplate, Paragraph, Image # 报告内容相关类 from reportlab.lib.pagesizes import letter # 页面的标志尺寸(8.5*inch, 11*inch) from reportlab.lib.styles import getSampleStyleSheet # 文本样式 from reportlab.lib import colors # 颜色模块 from reportlab.lib.units import cm # 单位:cm
After the module is imported, the first step is to set the fonts used in the PDF document. The fonts can be set according to your own preferences.
# Registering a font named 'simfang' with the file 'simfang.ttf'. pdfmetrics.registerFont(TTFont('simfang', 'simfang.ttf'))
The font I chose here is simfang.ttf. You can view the default font in the Windows system in the path below.
Before developing business code, we can bring the public part to the outside. Here, using the getSampleStyleSheet function, all the style sheets will be obtained and can be used in other places.
# Getting a list of styles that can be used in the document. style_list = getSampleStyleSheet()
Set the font style object of the large title to Heading1, the font color to green, the size to 18 and bold.
def insert_full_title(title_name=None): """ This function takes in a title name and returns the full title name. :param title_name: The name of the title you want to insert """ font_ = style_list['Heading1'] font_.fontName = 'simfang' font_.fontSize = 18 font_.leading = 50 font_.textColor = colors.green font_.alignment = 1 font_.bold = True return Paragraph(title_name, font_)
Set the font style object of the subtitle to Normal, the font color to red, the size to 15 and not bold.
def insert_lettle_title(lettle_name=None): """ :param lettle_name: The name of the lettle you want to insert """ font_ = style_list['Normal'] font_.fontName = 'simfang' font_.fontSize = 15 font_.leading = 30 font_.textColor = colors.red return Paragraph(lettle_name, font_)
For ordinary text, set the font style object to Normal, the font color to default, the size to 12 and not bold. Turn on automatic line wrapping mode.
def insert_text(text=None): """ > This function inserts text into the current document :param text: The text to insert """ font_ = style_list['Normal'] font_.fontName = 'simfang' font_.fontSize = 12 font_.wordWrap = 'CJK' font_.alignment = 0 font_.firstLineIndent = 32 font_.leading = 25 return Paragraph(text, font_)
Inserting pictures into PDF document objects is relatively simple. You only need to set the local path where the pictures need to be inserted.
def insert_image(image_path=None): """ > This function inserts an image into the notebook :param image_path: The path to the image you want to insert """ img = Image(image_path) img.drawWidth = 5 * cm img.drawHeight = 8 * cm return img
When inserting a table, the format of the table can be set according to your own preferences. The title, font style, font size and Whether merging and other parameters are needed to control the table objects that need to be inserted.
def insert_table(*args): """ It inserts a table into the database. """ col_width = 120 style = [ ('FONTNAME', (0, 0), (-1, -1), 'simfang'), # 字体 ('FONTSIZE', (0, 0), (-1, 0), 12), # 第一行的字体大小 ('FONTSIZE', (0, 1), (-1, -1), 10), # 第二行到最后一行的字体大小 ('BACKGROUND', (0, 0), (-1, 0), '#d5dae6'), # 设置第一行背景颜色 ('ALIGN', (0, 0), (-1, -1), 'CENTER'), # 第一行水平居中 ('ALIGN', (0, 1), (-1, -1), 'LEFT'), # 第二行到最后一行左右左对齐 ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), # 所有表格上下居中对齐 ('TEXTCOLOR', (0, 0), (-1, -1), colors.darkslategray), # 设置表格内文字颜色 ('GRID', (0, 0), (-1, -1), 0.5, colors.grey), # 设置表格框线为grey色,线宽为0.5 ] table = Table(args, colWidths=col_width, style=style) return table
The above are the commonly used objects in PDF documents. Finally, by adding the corresponding content parameters, the PDF document can be generated and saved to the local disk.
# A special variable in Python that evaluates to `True` if the module is being run as the main program. if __name__ == '__main__': pdf_ = list() pdf_.append(insert_full_title('数据测试报告')) pdf_.append(insert_text( 'Python 是一门编程语言。 您可以在服务器上使用 Python 来创建 Web 应用程序。通过实例学习 我们的 TIY 编辑器使学习 Python 变得简单,它能够同时显示代码和结果。 ')) pdf_.append(insert_image('./excle源数据.png')) pdf_.append(insert_lettle_title('数据内容展示:')) data = [ ('职位名称', '平均薪资', '较上年增长率'), ('数据分析师', '18.5K', '25%'), ('高级数据分析师', '25.5K', '14%'), ('资深数据分析师', '29.3K', '10%') ] pdf_.append(insert_table(*data)) doc = SimpleDocTemplate('测试报告.pdf', pagesize=letter) doc.build(pdf_)
The above is the detailed content of How to automatically generate PDF reports using Python?. For more information, please follow other related articles on the PHP Chinese website!