使用Reportlab

时间:2018-05-02 13:35:24

标签: python-3.x pdf reportlab

我正在尝试将一个旋转的图像居中在Reportlab上,但是我在使用正确的位置计算时遇到了问题。

这是当前的代码:

from reportlab.pdfgen import canvas
from reportlab.lib.utils import ImageReader
from PIL import Image as PILImage

import requests
import math


def main(rotation):
    # create a new PDF with Reportlab
    a4 = (595.275590551181, 841.8897637795275)
    c = canvas.Canvas('output.pdf', pagesize=a4)
    c.saveState()

    # loading the image:
    img = requests.get('https://i.stack.imgur.com/dI5Rj.png', stream=True)

    img = PILImage.open(img.raw)
    width, height = img.size

    # We calculate the bouding box of a rotated rectangle
    angle_radians = rotation * (math.pi / 180)
    bounding_height = abs(width * math.sin(angle_radians)) + abs(height * math.cos(angle_radians))
    bounding_width = abs(width * math.cos(angle_radians)) + abs(height * math.sin(angle_radians))

    a4_pixels = [x * (100 / 75) for x in a4]

    offset_x = (a4_pixels[0] / 2) - (bounding_width / 2)
    offset_y = (a4_pixels[1] / 2) - (bounding_height / 2)
    c.translate(offset_x, offset_y)

    c.rotate(rotation)
    c.drawImage(ImageReader(img), 0, 0, width, height, 'auto')

    c.restoreState()
    c.save()


if __name__ == '__main__':
    main(45)

到目前为止,这就是我所做的:

  1. 计算旋转矩形的边界(因为它会更大)
  2. 使用这些来计算图像中心的位置(尺寸/ 2 - 图像/ 2)的宽度和高度。
  3. 出现了两个我无法解释的问题:

    1. “a4”变量以磅为单位,其他所有内容均以像素为单位。如果我将它们更改为像素以计算位置(这是合乎逻辑的,使用a4_pixels = [x * (100 / 75) for x in a4])。旋转0度时放置不正确。如果我把a4保持在分数上,那就有效......?
    2. 如果我改变旋转,它会更加突破。
    3. 所以我的最后一个问题是:我如何计算offset_xoffset_y值,以确保它始终居中,无论轮换如何?

      谢谢! :)

1 个答案:

答案 0 :(得分:1)

翻译画布时,您实际上是移动原点(0,0)点,所有绘制操作都是相对于此。

因此,在下面的代码中,我将原点移动到页面的中间位置。 然后我旋转了“页面”并在“页面”上绘制了图像。由于画布轴已旋转,因此无需旋转图像。

from reportlab.pdfgen import canvas
from reportlab.lib.utils import ImageReader
from reportlab.lib.pagesizes import A4
from PIL import Image as PILImage
import requests

def main(rotation):
    c = canvas.Canvas('output.pdf', pagesize=A4)
    c.saveState()

    # loading the image:
    img = requests.get('https://i.stack.imgur.com/dI5Rj.png', stream=True)
    img = PILImage.open(img.raw)
    # The image dimensions in cm
    width, height = img.size

    # now move the canvas origin to the middle of the page
    c.translate(A4[0] / 2, A4[1] / 2)
    # and rotate it
    c.rotate(rotation)
    # now draw the image relative to the origin
    c.drawImage(ImageReader(img), -width/2, -height/2, width, height, 'auto')

    c.restoreState()
    c.save()

if __name__ == '__main__':
    main(45)