Python中文社区(ID:python-china)介绍,PDF格式是平台无关的,独立于底层操作系统和渲染引擎。事实上,PDF是基于一种脚本语言——PostScript,它是第一个与设备无关的页面描述语言。在本指南中,我们将使用borb——一个专门用于读取、操作和生成PDF文档的Python库。它提供了一个低级模型(让你可以访问精确的坐标和布局)和一个高级模型(你可以委托精确计算边距、位置等。(像Seaborn)是它背后的引擎。基于常见的PDF用于创建报告的文档(通常包括图表),我们将看看如何使用borb将Matplotlib图表集成到PDF文档中。安装borb和matplotlibborb可以从GitHub上的源代码下载,也可以通过pip安装:$pipinstallborbmatplotlib也可以通过pip安装:$pipinstallmatplotlib用Borb集成PDF文档中的Matplotlib图表在创建饼图等图表之前,我们会编写一个小的实用函数,它生成在色谱中均匀分布的N种颜色。每当我们需要创建绘图并为每个部分着色时,这将对我们有所帮助:HSVColor.from_rgb(HexColor("56cbf9"))#这个数组理解创建了n个HSVColor对象,转化为RGB,然后返回它们的hex字符串return[HSVColor(base_hsv_color.hue+Decimal(x/Decimal_r1),Decimal(bto.g(1),Decimal(1)),Decimal().to_hex_string()forxinrange(0,360,int(360/n))]HSL和HSV/HSB是计算机图形学研究人员在1970年代为了更接近humanvisualperception方式。在这些模型中,每个色调的颜色都围绕中性色的中心轴排列成径向切片,范围从底部的黑色到顶部的白色:以这种方式表示颜色的优点是这样我们就可以很容易地将光谱分成相等的部分。现在我们可以定义一个create_pie_chart()函数(或其他类型图表的函数):List[str],data:typing.List[float]):#Symetricfiguretoensureequalspectratiofig1,ax1=plt.subplots(figsize=(4,4))ax1.pie(数据,explode=[0for_inrange(0,len(labels)))],labelslabels=labels,autopct="%1.1f%%",shadow=True,startangle=90,colors=create_n_colors(len(labels)),)ax1.axis("equal")#Equalaspectratioensuresthatpieisdrawnasacircle.returnChart(plt.gcf(),width=Decimal(200),height=Decimal(200),horizo??ntal_alignment=Alignment.CENTERED,)这里我们使用Matplotlib通过pie()函数创建饼图。PyPlot实例的gcf()函数返回当前图形。通过将图表连同您的自定义参数(例如宽度、高度和水平对齐方式)一起注入到图表构造函数中,可以将图表嵌入到PDF文档中。您只需向图表构造函数提供一个Matplotlib图。将Matplotlib图表添加到PDF文档现在是时候创建我们的PDF文档并向其中添加内容了。#Newimport(s)fromborb.pdf.documentimportDocumentfromborb.pdf.page.pageimportPagefromborb.pdf.pdfimportPDFfromborb.pdf.canvas.layout.page_layout.multi_column_layoutimportMultiColumnLayoutfromborb.pdf.canvas.layout.page_layout.page_layoutimportPageLayoutfromborb.pdf.canvas.layout.text.paragraphimportParagraph#CreateemptyDocumentpdf=Document()#CreateemptyPagepage=Page()#AddPagetoDocumentpdf.append_page(page)#CreatePageLayoutlayout:PageLayout=MultiColumnLayout(page)#Writetitlelayout.add(段落("AboutLoremIpsum",font_size=Decimal(20),font="Helvet-Bold"))我们将在此PDF中使用连字符,以确保文本布局更流畅。borb中的连字符非常简单:#Newimport(s)fromborb.pdf.canvas.layout.hyphenation.hyphenationimportHyphenation#Createhyphenationalgorithmhyphenation_algorithm:HyphenationHyphenation=Hyphenation("en-gb")#Writeparagraphlayout.add(Paragraph("""LoremIpsumissimplydummytextoftheprintingandtypesettingindustry.LoremIpsumhasbeentheindustry'sstandarddummytexteversincethe1500s,whenanunknownprintertookagalleyoftypeandscrambledittomakeatypespecimenbook.Ithassurvivednotonlyfivecenturies,butalsotheleapintoelectronictypesetting,remainingessentiallyunchanged.Itwaspopularisedinthe1960swiththereleaseofLetrasetsheetscontainingLoremIpsumpassages,andmorerecentlywithdesktoppublishingsoftwarelikeAldusPageMakerincludingversionsofLoremIpsum.""",text_alignment=Alignment.JUSTIFIED,hyphenation=hyphenation_algorithm))现在我们可以使用我们之前声明的函数添加饼图;#Writegraphlayout.add(create_piechart(["Loren","Ipsum","Dolor"],[0.6,0.3,0.1]))Nextwe将写入另外三个Paragraph对象,其中一个将不仅仅表示引用(侧边框、不同的字体等)。#Writeparagraphlayout.add(Paragraph("""Contrarytopopularbelief,LoremIpsumisnotsimplyrandomtext.IthasrootsinapieceofclassicalLatinliteraturefrom45BC,makingitover2000yearsold.RichardMcClintock,aLatinprofessoratHampden-SydneyCollegeinVirginia,lookeduponeofthemoreobscureLatinwords,consectetur,fromaLoremIpsumpassage,andgoingthroughthecitesofthewordinclassicalliterature,discoveredtheundoubtablesource.""",text_alignment=Alignment.JUSTIFIED,hyphenation=hyphenation_algorithm))#Writeparagraphlayout.add(Paragraph("""LoremIpsumissimplydummytextoftheprintingandtypesettingindustry.""",font="Courier-Bold",text_alignment=Alignment.JUSTIFIED,hyphenation=hyphenation_algorithm,border_color=HexColor("56cbf9"),border_width=Decimal(3),border_left=True,padding_left=Decimal(5),padding_bottom=Decimal(5),))#Writeparagraphlayout.add(Paragraph("""LoremIpsumcomesfromsections1.10.32西塞罗的“deFinibusBonorumetMalorum”(善恶的极端)的1.10.33,写于公元前45年。这本书讲的是伦理学理论,文艺复兴时期很流行。#Writegraphlayout.add(create_piechart(["Loren","Ipsum","Dolor","Sit","Amet"],[600,30,89,100,203]))还有一个段落(Paragraph):#Writeparagraphlayout。add(Paragraph("""Itisalongestablishedfactthatareaderwillbedistractedbythereadablecontentofapagewhenlookingatitslayout.ThepointofusingLoremIpsumisthatithasamore-or-lessnormaldistributionofletters,asopposedtousing'Contenthere,contenthere',makingitlooklikereadableEnglish.ManydesktoppublishingpackagesandwebpageeditorsnowuseLoremIpsumastheirdefaultmodeltext,andasearchfor'loremipsum'willuncovermanywebsitesstillintheirinfancy.Variousversionshaveevolvedovertheyears,sometimesbyaccident,sometimesonpurpose(injectedhumourandthelike).""",text_alignment=Alignment.JUSTIFIED,hyphenation=hyphenation_algorithm))最后我们可以存储文档(Document):#Writetodiskwithopen("output.pdf","wb")aspdf_file_handle:PDF.dumps(pdf_file_handle,pdf)运行这段代码会生成如下的PDF文档:在本文中,您学习了如何使用borb将Matplotlib图表集成到PDF中
