Is it possible to get a Flowable's coordinate position once it's rendered using ReportLab.platypus?

风格不统一 提交于 2019-11-30 14:19:13

After working on this all day today, I finally figured out a nice way to do this! Here's how I did it for anyone else who would like this feature of hyperlinked Image flowables in their PDFs.

Basically, reportlab.platypus.flowables has a class called Flowable that Image inherits from. Flowable has a method called drawOn(self, canvas, x, y, _sW=0) that I override in a new class I created called HyperlinkedImage.

from reportlab.platypus import Image

class HyperlinkedImage(Image, object):

    # The only variable I added to __init__() is hyperlink. I default it to None for the if statement I use later.
    def __init__(self, filename, hyperlink=None, width=None, height=None, kind='direct', mask='auto', lazy=1):
        super(HyperlinkedImage, self).__init__(filename, width, height, kind, mask, lazy)
        self.hyperlink = hyperlink

    def drawOn(self, canvas, x, y, _sW=0):
        if self.hyperlink: # If a hyperlink is given, create a canvas.linkURL()
            x1 = self.hAlignAdjust(x, _sW) # This is basically adjusting the x coordinate according to the alignment given to the flowable (RIGHT, LEFT, CENTER)
            y1 = y
            x2 = x1 + self._width
            y2 = y1 + self._height
            canvas.linkURL(url=self.hyperlink, rect=(x1, y1, x2, y2), thickness=0, relative=1)
        super(HyperlinkedImage, self).drawOn(canvas, x, y, _sW)

Now instead of creating a reportlab.platypus.Image as your image flowable, use the new HyperlinkedImage instead :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!