用 Python 将 matplotlib 图表集成到 PDF 中,


Python中文社区(ID:python-china)

介绍

PDF 格式是与平台无关,它独立于底层操作系统和渲染引擎。事实上,PDF 是基于一种脚本语言——PostScript,它是第一个独立于设备的页面描述语言。

在本指南中,我们将使用 borb —— 一个专门用于阅读、操作和生成 PDF 文档的 Python 库。它提供了一个低级模型(允许您访问精确的坐标和布局)和一个高级模型(您可以将边距、位置等精确计算委托给布局管理器) .

matplotlib 是一个数据可视化库,也是许多其他流行库(如 Seaborn)背后的引擎。

基于用于创建报告(通常包括图形)的常见 PDF 文档,我们将看看如何使用 borb 将 Matplotlib 图表集成到 PDF 文档中。

安装 borb和 matplotlib

borb 可以从 GitHub 上的源代码下载,或通过 pip 安装:

  1. $ pip install borb 

matplotlib 也可以通过 pip 安装:

  1. $ pip install matplotlib

用 Borb 在 PDF 文档中集成 Matplotlib 图表

在创建饼图等图表之前,我们将编写一个小的效用函数,该函数生成 N 种颜色,均匀分布在颜色光谱中。

每当我们需要创建绘图并为每个部分着色时,这将对我们有所帮助:

  1. from borb.pdf.canvas.color.color import HSVColor, HexColor  
  2. from decimal import Decimal  
  3. import typing  
  4. def create_n_colors(n: int) -> typing.List[str]:  
  5.   # The base color is borb-blue  
  6.   base_hsv_color: HSVColorHSVColor = HSVColor.from_rgb(HexColor("56cbf9"))  
  7.   # This array comprehension creates n HSVColor objects, transforms then to RGB, and then returns their hex string  
  8.   return [HSVColor(base_hsv_color.hue + Decimal(x / 360), Decimal(1), Decimal(1)).to_rgb().to_hex_string() for x in range(0, 360, int(360/n))] 

HSL 和 HSV/HSB 是由计算机图形学研究人员在 1970 年代设计的,目的是更接近人类视觉感知色彩属性的方式。在这些模型中,每种色调的颜色都排列在一个径向切片中,围绕中性色的中心轴,范围从底部的黑色到顶部的白色:

用它表示颜色的优点是我们可以轻松地将颜色光谱分成相等的部分。

现在我们可以定义一个 create_pie_chart() 函数(或其他类型图的函数):

  1. # New import(s)  
  2. import matplotlib.pyplot as plt  
  3. from borb.pdf.canvas.layout.image.chart import Chart  
  4. from borb.pdf.canvas.layout.layout_element import Alignment  
  5. def create_piechart(labels: typing.List[str], data: typing.List[float]):  
  6.   # Symetric figure to ensure equal aspect ratio  
  7.   fig1, ax1 = plt.subplots(figsize=(4, 4))  
  8.   ax1.pie(  
  9.     data,  
  10.     explode=[0 for _ in range(0, len(labels))],  
  11.     labelslabels=labels,  
  12.     autopct="%1.1f%%",  
  13.     shadow=True,  
  14.     startangle=90,  
  15.     colors=create_n_colors(len(labels)),  
  16.   )  
  17.   ax1.axis("equal")  # Equal aspect ratio ensures that pie is drawn as a circle.  
  18.   return Chart(  
  19.     plt.gcf(),  
  20.     width=Decimal(200),  
  21.     height=Decimal(200),  
  22.     horizontal_alignment=Alignment.CENTERED,  
  23.   ) 

在这里,我们使用 Matplotlib 通过 pie() 函数创建饼图。

PyPlot 实例的 gcf() 函数返回当前图形。该图可以嵌入到 PDF 文档中,方法是将其注入到 Chart 构造函数中,并与您的自定义参数(例如width, height 和 horizontal_alignment)一起插入。

您只需向Chart构造函数提供一个 Matplotlib 图。

将 Matplotlib 图表添加到 PDF 文档

现在是时候创建我们的 PDF 文档并向其中添加内容了。

  1. # New import(s)  
  2. from borb.pdf.document import Document  
  3. from borb.pdf.page.page import Page  
  4. from borb.pdf.pdf import PDF  
  5. from borb.pdf.canvas.layout.page_layout.multi_column_layout import MultiColumnLayout  
  6. from borb.pdf.canvas.layout.page_layout.page_layout import PageLayout  
  7. from borb.pdf.canvas.layout.text.paragraph import Paragraph  
  8. # Create empty Document  
  9. pdf = Document()  
  10. # Create empty Page  
  11. page = Page()  
  12. # Add Page to Document  
  13. pdf.append_page(page)  
  14. # Create PageLayout  
  15. layout: PageLayout = MultiColumnLayout(page) 
  16. # Write title  
  17. layout.add(Paragraph("About Lorem Ipsum",   
  18.                      font_size=Decimal(20),   
  19.                      font="Helvetica-Bold")) 

我们将在此 PDF 中使用连字符,以确保文本的布局更加流畅。borb 中的连字符非常简单:

  1. # New import(s)  
  2. from borb.pdf.canvas.layout.hyphenation.hyphenation import Hyphenation  
  3. # Create hyphenation algorithm  
  4. hyphenation_algorithm: HyphenationHyphenation = Hyphenation("en-gb")  
  5. # Write paragraph  
  6. layout.add(Paragraph(  
  7.     """  
  8.     Lorem Ipsum is simply dummy text of the printing and typesetting industry.   
  9.     Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,  
  10.     when an unknown printer took a galley of type and scrambled it to make a type specimen book.   
  11.     It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.   
  12.     It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,   
  13.     and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.  
  14.     """, text_alignment=Alignment.JUSTIFIED, hyphenation=hyphenation_algorithm)) 

现在我们可以使用我们之前声明的函数添加饼图;

  1. # Write graph  
  2. layout.add(create_piechart(["Loren", "Ipsum", "Dolor"],   
  3.                            [0.6, 0.3, 0.1])) 

接下来我们将编写另外三个 Paragraph对象。其中一个将不仅仅表示引用(侧面边框,不同字体等)。

  1. # Write paragraph  
  2. layout.add(Paragraph(  
  3.     """  
  4.     Contrary to popular belief, Lorem Ipsum is not simply random text.   
  5.     It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.   
  6.     Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words,   
  7.     consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature,   
  8.     discovered the undoubtable source.  
  9.     """, text_alignment=Alignment.JUSTIFIED, hyphenation=hyphenation_algorithm))  
  10. # Write paragraph  
  11. layout.add(Paragraph(  
  12.     """  
  13.     Lorem Ipsum is simply dummy text of the printing and typesetting industry.   
  14.     """,   
  15.     font="Courier-Bold",  
  16.     text_alignment=Alignment.JUSTIFIED,   
  17.     hyphenation=hyphenation_algorithm,  
  18.     border_color=HexColor("56cbf9"), 
  19.     border_width=Decimal(3),  
  20.     border_left=True,  
  21.     padding_left=Decimal(5),  
  22.     padding_bottom=Decimal(5),  
  23. ))  
  24. # Write paragraph  
  25. layout.add(Paragraph(  
  26.     """  
  27.     Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum"  
  28.     (The Extremes of Good and Evil) by Cicero, written in 45 BC.   
  29.     This book is a treatise on the theory of ethics, very popular during the Renaissance.  
  30.     """, text_alignment=Alignment.JUSTIFIED, hyphenation=hyphenation_algorithm)) 

让我们添加另一个绘图。

  1. # Write graph  
  2. layout.add(create_piechart(["Loren", "Ipsum", "Dolor", "Sit", "Amet"],   
  3.                            [600, 30, 89, 100, 203])) 

还有一段内容(Paragraph):

  1. # Write paragraph  
  2. layout.add(Paragraph(  
  3.     """  
  4.     It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.  
  5.     The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here',   
  6.     making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text,   
  7.     and a search for 'lorem ipsum' will uncover many web sites still in their infancy.   
  8.     Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).  
  9.     """, text_alignment=Alignment.JUSTIFIED, hyphenation=hyphenation_algorithm)) 

最后,我们可以存储文档(Document):

  1. # Write to disk  
  2. with open("output.pdf", "wb") as pdf_file_handle:  
  3.   PDF.dumps(pdf_file_handle, pdf) 

运行此代码会生成如下所示的 PDF 文档:

在本文中,您学习了如何使用 borb 将 Matplotlib 图表集成到 PDF 。

鸿蒙官方战略合作共建——HarmonyOS技术社区

评论关闭