搜尋
首頁後端開發Python教學如何使用Python自動化產生PDF報告?

因為工作需要經常需要產生很多的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陣列上可以執行哪些常見操作?在Python陣列上可以執行哪些常見操作?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

在哪些類型的應用程序中,Numpy數組常用?在哪些類型的應用程序中,Numpy數組常用?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

您什麼時候選擇在Python中的列表上使用數組?您什麼時候選擇在Python中的列表上使用數組?Apr 26, 2025 am 12:12 AM

useanArray.ArarayoveralistinpythonwhendeAlingwithHomoGeneData,performance-Caliticalcode,orinterfacingwithccode.1)同質性data:arraysSaveMemorywithTypedElements.2)績效code-performance-calitialcode-calliginal-clitical-clitical-calligation-Critical-Code:Arraysofferferbetterperbetterperperformanceformanceformancefornallancefornalumericalical.3)

所有列表操作是否由數組支持,反之亦然?為什麼或為什麼不呢?所有列表操作是否由數組支持,反之亦然?為什麼或為什麼不呢?Apr 26, 2025 am 12:05 AM

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactsperformance.2)listssdonotguaranteeconecontanttanttanttanttanttanttanttanttanttimecomplecomecomplecomecomecomecomecomecomplecomectacccesslectaccesslecrectaccesslerikearraysodo。

您如何在python列表中訪問元素?您如何在python列表中訪問元素?Apr 26, 2025 am 12:03 AM

toAccesselementsInapythonlist,useIndIndexing,負索引,切片,口頭化。 1)indexingStartSat0.2)否定indexingAccessesessessessesfomtheend.3)slicingextractsportions.4)iterationerationUsistorationUsisturessoreTionsforloopsoreNumeratorseforeporloopsorenumerate.alwaysCheckListListListListlentePtotoVoidToavoIndexIndexIndexIndexIndexIndExerror。

Python的科學計算中如何使用陣列?Python的科學計算中如何使用陣列?Apr 25, 2025 am 12:28 AM

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

您如何處理同一系統上的不同Python版本?您如何處理同一系統上的不同Python版本?Apr 25, 2025 am 12:24 AM

你可以通過使用pyenv、venv和Anaconda來管理不同的Python版本。 1)使用pyenv管理多個Python版本:安裝pyenv,設置全局和本地版本。 2)使用venv創建虛擬環境以隔離項目依賴。 3)使用Anaconda管理數據科學項目中的Python版本。 4)保留系統Python用於系統級任務。通過這些工具和策略,你可以有效地管理不同版本的Python,確保項目順利運行。

與標準Python陣列相比,使用Numpy數組的一些優點是什麼?與標準Python陣列相比,使用Numpy數組的一些優點是什麼?Apr 25, 2025 am 12:21 AM

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基於基於duetoc的iMplation,2)2)他們的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函數函數函數函數構成和穩定性構成和穩定性的操作,製造

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具