title: How to drawImage a matplotlib figure in a reportlab canvas?
body: <p>I would like to add a figure generated with matplotlib to a reportlab canvas using the method drawImage and without having to save the figure to the hard drive first.</p>
  
  <p>My question is related to:
  <a href="https://stackoverflow.com/questions/4690585/is-there-a-matplotlib-flowable-for-reportlab">Is there a matplotlib flowable for ReportLab?</a>, which was nicely solved.
  However, I do not wish to use DocTemplates, Stories, Flowables, etc. As said, I would like put it at a certain position in the canvas using drawImage.</p>
  
  <p>I have tried to convert the matplotlib figure to a PIL image using the following methods:</p>
  
  <p>1) <a href="http://www.icare.univ-lille1.fr/wiki/index.php/How_to_convert_a_matplotlib_figure_to_a_numpy_array_or_a_PIL_image" rel="noreferrer">http://www.icare.univ-lille1.fr/wiki/index.php/How_to_convert_a_matplotlib_figure_to_a_numpy_array_or_a_PIL_image</a></p>
  
  <p>2) <a href="http://matplotlib.org/faq/howto_faq.html#matplotlib-in-a-web-application-server" rel="noreferrer">http://matplotlib.org/faq/howto_faq.html#matplotlib-in-a-web-application-server</a></p>
  
  <p>For example, some code that fails to work is:</p>
  
  <pre><code>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()
  </code></pre>
  
  <p>Trying to draw <code>imgdata</code> results in the error:</p>
  
  <pre><code>AttributeError: 'cStringIO.StringO' object has no attribute 'rfind'
  </code></pre>
  
  <p>While drawing <code>im</code> gives:</p>
  
  <pre><code>AttributeError: rfind
  </code></pre>
  
  <p>Does somebody now how to solve this issue?
  Any help would be greatly appreciated.</p>