How to drawImage a matplotlib figure in a reportlab canvas?

后端 未结 2 1516
攒了一身酷
攒了一身酷 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 23:01

    Solution for Python 3, and embedding matplotlib figure as a vector image (no rasterization). Reposting here as I searched for this quite some time.

    import matplotlib.pyplot as plt
    from io import BytesIO
    from reportlab.pdfgen import canvas
    from reportlab.graphics import renderPDF
    from svglib.svglib import svg2rlg
    
    fig = plt.figure(figsize=(4, 3))
    plt.plot([1,2,3,4])
    plt.ylabel('some numbers')
    
    imgdata = BytesIO()
    fig.savefig(imgdata, format='svg')
    imgdata.seek(0)  # rewind the data
    
    drawing=svg2rlg(imgdata)
    
    c = canvas.Canvas('test2.pdf')
    renderPDF.draw(drawing,c, 10, 40)
    c.drawString(10, 300, "So nice it works")
    c.showPage()
    c.save()
    

    svglib is available from conda-forge.

提交回复
热议问题