reportlab中旋转图片的简单方法

A simple method for rotate images in reportlab

我们如何使用 reportlab 轻松旋转图像?我寻找但没有找到简单的方法。找到的唯一方法来自 http://dods.ipsl.jussieu.fr/orchidee/SANORCHIDEE/TEMP/TEMP_LOCAL/cdat_portable/lib_new_wrong_gcc/python2.4/site-packages/reportlab/test/test_graphics_images.py 使用例如:

>>> from reportlab.graphics.shapes import Image, Drawing
>>> from reportlab.platypus import SimpleDocTemplate
>>> from reportlab.lib.pagesizes import A4, portrait
>>> from reportlab.lib.units import mm
>>> img = Image(-202/25.4, -125/25.4, 210/25.4, 138/25.4, 'uneBelleImage.png') # (x, y [from lower left corner], width, height, path, **kw)
>>> d = Drawing(0, 0) # (width, height, *nodes, **keywords)
>>> d.add(img)
>>> d.scale(100,100) #(%width, %height)
>>> d.rotate(90)
>>> report=[]
>>> report.append(d)
>>> page = SimpleDocTemplate('toto.pdf', pagesize = portrait(A4), rightMargin=20*mm, leftMargin=20*mm, topMargin=10*mm, bottomMargin = 10*mm)
>>> page.build(report)

这是可行的,但是就像用大锤敲螺母一样? 是否有更直接的方法,例如使用经典的 reportlab.platypus.Image ? 提前致谢!

要修改现有的可流动对象,您应该创建派生的 class 并覆盖您需要更改的方法以获得所需的行为。 因此,要创建旋转图像,您需要覆盖现有图像的包裹和绘制方法 class,如下所示:

from reportlab.platypus.flowables import Image

class RotatedImage(Image):

    def wrap(self,availWidth,availHeight):
        h, w = Image.wrap(self,availHeight,availWidth)
        return w, h
    def draw(self):
        self.canv.rotate(90)
        Image.draw(self)

I = RotatedImage('../images/somelogo.gif')

另一种方法是使用 img.transpose (https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.transpose) 在 PIL 中执行转换并添加转换后的图像。

对我来说效果更好:

from dataclasses import dataclass
from pathlib import Path

from PIL import Iamge
from reportlab.lib.utils import ImageReader
from reportlab.pdfgen.canvas import Canvas


@dataclass
class Position:
    """Information for a position"""

    x: float
    y: float
    width: float
    height: float


def write_image(canvas: Canvas, img: Path, pos: Position) -> None:
    """Put an image at a given position"""
    # As the canvas might be upside down, we need to flip the image vertically
    # The easiest way seems to be using PIL (Flowable seems a bit complicated)
    im = Image.open(img).transpose(Image.FLIP_TOP_BOTTOM)

    y = canvas._pagesize[1] - pos.y if canvas.bottomup else pos.y
    canvas.drawImage(ImageReader(im), pos.x, y, width=pos.width, height=pos.height)


c = Canvas("my_report.pdf", bottomup=0)
pos = Position(100, 100, 20, 30)
write_image(c, Path("my_image.png"), pos)
c.save()