• 技术文章 >后端开发 >Python教程

    如何使用Python自动化生成PDF报告?

    WBOYWBOY2023-04-23 11:25:15转载42

    因为工作需要经常需要生成很多的PDF报告给客户查看产品效果以及过程的讲解。

    每次都需要按照一定的格式的编写文档并生成PDF报告,这样重复性的工作实在太累。

    想着可以使用python生成一份给用户看的报告,里面需要插入图片、表格、文字说明等等。

    使用第三方的python非标准模块reportlab就能满足直接生成PDF报告的需要,由于是非标准库需要使用pip的方式安装一下该模块。

    使用pip安装reportlab模块,支持生成PDF文档。

    pip install reportlab -i https://pypi.tuna.tsinghua.edu.cn/simple

    若是在安装过程中出现缺失C++环境导致构建失败时,可以直接选择使用wheel文件的方式安装reportlab模块。

    Python自动化办公之怎么生成PDF报告

    .whl文件的下载地址如下:https://www.lfd.uci.edu/~gohlke/pythonlibs/

    下载完成之后存储到本地磁盘,按照存放的路径安装reportLab模块即可,安装方式可以参考下面的安装方式。

    pip install wheel -i https://pypi.tuna.tsinghua.edu.cn/simple
    
    pip install D:\downloads\reportlab-3.5.57-cp36-cp36m-win_amd64.whl

    提前将reportlab模块中需要使用到的python对象导入到当前的代码块中。

    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

    模块导入完成之后,第一步需要设置PDF文档中使用到的字体,字体可以根据自己的喜好自行设置。

    # Registering a font named 'simfang' with the file 'simfang.ttf'.
    pdfmetrics.registerFont(TTFont('simfang', 'simfang.ttf'))

    我这里选择的字体是simfang.ttf,关于windows系统中的默认字体可以下面的路径中查看。

    Python自动化办公之怎么生成PDF报告

    开发业务代码之前,我们可以将公共的部分提到最外面,这里使用getSampleStyleSheet函数将获取到所有的样式表后面在其他地方也可以使用。

    # Getting a list of styles that can be used in the document.
    style_list = getSampleStyleSheet()

    1、插入PDF标题

    大标题设置字体样式对象为Heading1,字体颜色为绿色,大小为18并且加粗。

    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_)

    Python自动化办公之怎么生成PDF报告

    2、插入PDF小标题

    小标题设置字体样式对象为Normal,字体颜色为红色,大小为15并且不加粗。

    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_)

    Python自动化办公之怎么生成PDF报告

    3、插入普通段落文本

    普通文本设置字体样式对象为Normal,字体颜色为默认,大小为12并且不加粗,开启自动换行模式。

    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_)

    Python自动化办公之怎么生成PDF报告

    4、插入PDF图片

    将图片插入到PDF文档对象中比较简单,只需要设置需要插入图片的本地路径即可。

    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

    Python自动化办公之怎么生成PDF报告

    5、插入PDF表格

    插入表格时,表格的格式可以根据自己的喜好设置表格的标题、字体样式、字体大小以及是否需要合并等参数来控制需要插入的表格对象。

    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

    Python自动化办公之怎么生成PDF报告

    上述就是PDF文档中常用的对象,最后通过添加对应的内容参数即可生成PDF文档并保存到本地磁盘当中。

    # 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_)

    Python自动化办公之怎么生成PDF报告

    以上就是如何使用Python自动化生成PDF报告?的详细内容,更多请关注php中文网其它相关文章!

    声明:本文转载于:亿速云,如有侵犯,请联系admin@php.cn删除
    专题推荐:Python PDF
    上一篇:如何解决Python中出现File "<stdin>", line 1非语法错误 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • Python运动检测编程实战演练• Python如何使用Requests请求网页• Python连接oracle的问题怎么解决• Python数据可视化的实现方法• Python中如何创建对象列表
    1/1

    PHP中文网