将matplotlib图形写入缓冲区,然后作为文件读取,以便在PDF中嵌入图像

2024-04-19 19:56:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将几个matplotlib图形保存到用FPDF创建的PDF中的特定位置。我不想把这些数字丢到文件里然后再把它们放回去。更好的解决方案似乎是将它们写入缓冲区,然后再读回,但我不确定这是否可行。在

简化代码:

import pandas as pd
import matplotlib.pyplot as plt
from fpdf import FPDF
from io import BytesIO
import base64

# create figure
fig = plt.figure()

# add plot
ax = pd.Series( [1,3,2] ).plot()

# create bytesio object
bio = BytesIO()        

# save figure to bytesio
fig.savefig(bio, format="png", bbox_inches='tight')

# this works to save the figure to a file
with open("myfile.png", "wb") as file:
    file.write(bio.getvalue())

# create a PDF and set some attributes    
pdf = FPDF(orientation="L", unit="in", format="letter")
pdf.set_font('Arial', 'B', 14)
pdf.add_page()

# try to read the bytesio object as though it's a file
# pdf.image() expects a file name or a URL: https://pyfpdf.readthedocs.io/en/latest/reference/image/index.html
# trying to create a data url with the base64-encoded data inside it

pdf.image( name='data://image/png;base64,' + base64.b64encode(bio.getvalue()).decode() , x=1, y=1, w=3.5, type='png')

# save pdf
pdf.output("mypdf.pdf")

完整堆栈跟踪:

^{pr2}$

因为pdf.image文件()可以使用URL,我希望构造一个不实际尝试打开文件的数据URL。这就像在HTML页面中嵌入一个图像。那种想法。我尝试了getvalue()和encode()以及decode()的多次迭代,但没有得到正确的组合。在

在本例中,我成功地写入了一个文件,以确保我的BytesIO对象中包含正确的数据,但将其转储到pdf.image文件()不工作。在


Tags: 文件toimageimportpdfpngascreate