3
有沒有辦法在ReportLab中添加一個href /鏈接到Platypus Image對象?我知道如何在段落中的文字上添加鏈接,但似乎無法找到任何有關爲圖片添加鏈接的信息。ReportLab Image Link
有沒有辦法在ReportLab中添加一個href /鏈接到Platypus Image對象?我知道如何在段落中的文字上添加鏈接,但似乎無法找到任何有關爲圖片添加鏈接的信息。ReportLab Image Link
這可以通過missmely提出的HyperlinkedImage class可以輕鬆實現:
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)
這裏是一個小更新,使@ Meilo最偉大的回答工作,ReportLab的3.3.0。它修復方法名稱並添加hAlign
kwarg:
from reportlab.platypus import Image
class HyperlinkedImage(Image, object):
"""Image with a hyperlink, adopted from http://stackoverflow.com/a/26294527/304209."""
def __init__(self, filename, hyperlink=None, width=None, height=None, kind='direct',
mask='auto', lazy=1, hAlign='CENTER'):
"""The only variable added to __init__() is hyperlink.
It defaults to None for the if statement used later.
"""
super(HyperlinkedImage, self).__init__(filename, width, height, kind, mask, lazy,
hAlign=hAlign)
self.hyperlink = hyperlink
def drawOn(self, canvas, x, y, _sW=0):
if self.hyperlink: # If a hyperlink is given, create a canvas.linkURL()
# This is basically adjusting the x coordinate according to the alignment
# given to the flowable (RIGHT, LEFT, CENTER)
x1 = self._hAlignAdjust(x, _sW)
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)