我想使用drawImage方法将使用matplotlib生成的图形添加到reportlab画布中,而不必先将图形保存到硬盘驱动器中.
我的问题与:
Is there a matplotlib flowable for ReportLab?,很好地解决了.
但是,我不想使用DocTemplates,Stories,Flowables等.如上所述,我想使用drawImage将它放在画布中的某个位置.
我尝试使用以下方法将matplotlib图转换为PIL图像:
2)http://matplotlib.org/faq/howto_faq.html#matplotlib-in-a-web-application-server
例如,一些无法工作的代码是:
import Image
import matplotlib.pyplot as plt
import cStringIO
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch, cm
fig = plt.figure(figsize=(4, 3))
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
imgdata = cStringIO.StringIO()
fig.savefig(imgdata, format='png')
imgdata.seek(0) # rewind the data
im = Image.open(imgdata)
c = canvas.Canvas('test.pdf')
#c.drawImage(imgdata, cm, cm, inch, inch)
c.drawImage(im, cm, cm, inch, inch)
c.save()
尝试绘制imgdata会导致错误:
AttributeError: 'cStringIO.StringO' object has no attribute 'rfind'
绘制即时通讯给出:
AttributeError: rfind
现在有人如何解决这个问题?
任何帮助将不胜感激.
解决方法:
问题是drawImage需要ImageReader对象或文件路径,而不是文件句柄.
以下应该有效:
import Image
import matplotlib.pyplot as plt
import cStringIO
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch, cm
from reportlab.lib.utils import ImageReader
fig = plt.figure(figsize=(4, 3))
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
imgdata = cStringIO.StringIO()
fig.savefig(imgdata, format='png')
imgdata.seek(0) # rewind the data
Image = ImageReader(imgdata)
c = canvas.Canvas('test.pdf')
c.drawImage(Image, cm, cm, inch, inch)
c.save()