Insert PNG Image to Reportlab PDF using Python

61 views Asked by At

I have tried and gone through multiple topic on a similar questions, I am not able to export image to pdf, is there any way to debug to understand what's going on. When i use below function for simpler example it works fine, however, I can't share other image for which it doesn't work, I would like to know how can i debug and understand why it doesn't work.

from reportlab.platypus import Image
from reportlab.lib.units import inch
import matplotlib.pyplot as plt
from io import BytesIO

def fig2image(f):
    buf = io.BytesIO()
    f.savefig(buf, format='png', dpi=300)
    buf.seek(0)
    x,y = f.get_size_inches()
    return Image(buf, x * inch, y * inch)
 
#Worked Example:
abc, ax = plt.subplots(dpi=400,figsize=(4,4))
plt.plot([1,2,3,4])
plt.savefig('abc.png')

fig2image(abc)
1

There are 1 answers

1
Cam On

You can use the format parameter with savefig to save to pdf. Make sure the files extension is also .pdf

import matplotlib.pyplot as plt
import numpy as np

# create data
values=np.cumsum(np.random.randn(1000,1))

# use the plot function
plt.plot(values)
plt.savefig('abc.pdf', format='pdf')

output

enter image description here