How to drawImage a matplotlib figure in a reportlab canvas?

后端 未结 2 1525
攒了一身酷
攒了一身酷 2021-01-01 22:31

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.

<
2条回答
  •  情深已故
    2021-01-01 22:46

    The problem is that drawImage expects either an ImageReader object or a filepath, not a file handle.

    The following should work:

    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()
    

提交回复
热议问题