Home > OS >  Reportlab - inverted image
Reportlab - inverted image

Time:08-30

I am trying to display some png pictures in my ReportLab canvas with the functions drawImage() but it is displaying the picture as inverted.

Original image : enter image description here

Image in the report : enter image description here

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter, landscape, A4
from reportlab.lib.utils import ImageReader

fig = plt.figure()
#fig.patch.set_facecolor('#0c1c33')
#fig.patch.set_alpha(1)
data = [10,30,25,15,10]
plt.pie(data, labels = ['A', 'B', 'C', 'D', 'E'])
circle = plt.Circle( (0,0), 0.7, color='#0c1c33')
p = plt.gcf()
p.gca().add_artist(circle)
plt.savefig('test_donut.png')
plt.show()

my_canvas = canvas.Canvas("Test_Rapport.pdf",pagesize=(landscape(A4)),bottomup=0)
my_canvas.drawImage(ImageReader('test_donut.png'), 300, 150, width=200, height=150)
my_canvas.save()

Do you have an idea of how I could solve this problem ? Thanks in advance for your help and your time

CodePudding user response:

It is to do with the canvas coordinate system. Sometimes you would need to use bottomup=1 for drawImage() to work as desired, but if you already designed coordinates for the other elements on bottomup=0, then the text and everything else will not be where it should be if you change bottomup to be 1.

This is a fix you can try (scaling the canvas this way forces the image to flip back to how it should be, but the y-value then needs to be a negative value to make the image visible on the A4 page):

my_canvas = canvas.Canvas("Test_Rapport.pdf",pagesize=(landscape(A4)),bottomup=0)

my_canvas.saveState()
my_canvas.scale(1,-1)
x_val = 300
y_val = -150
my_canvas.drawImage(ImageReader('test_donut.png'), x_val, y_val, width=200, height=150)
my_canvas.restoreState()

my_canvas.save()
  • Related