是否可以在 ReportLab 中为图像添加边框?

mis*_*ely 5 html python xml reportlab

我正在为一些包含图像的产品构建 PDF。很多这些图像都有白色背景,所以我真的很想在它们周围添加边框。我在创建 PDF 时得到了一个图像 url,我可以直接将其传递给 reportlab 的 Image(),它会显示得很好。它周围有一个边界,这是棘手的部分。

查看ReportLab 的用户指南后, Image() 没有直接应用边框的能力。所以有一些技巧我想我会尝试看看我是否可以模拟图像周围的边框。

起初,我认为为每个图像创建框架不仅会很痛苦,而且框架的边框只是用于调试的黑色实线,无法以任何方式自定义。我希望能够更改边框的厚度和颜色,因此该选项没有希望。

然后我注意到 Paragraph() 能够采用 ParagraphStyle() ,它可以应用某些样式,包括边框。Image() 没有 ParagraphStyle() 等价物,所以我想也许我可以使用 Paragraph() 来代替创建一个包含 XML 'img' 标签的字符串和我拥有的图像 url,然后将 ParagraphStyle() 应用到它带有边框。这种方法成功地显示了图像,但仍然没有边框:(下面的简单示例代码:

from reportlab.platypus import Paragraph
from reportlab.lib.styles import Paragraph Style

Paragraph(
    text='<img src="http://placehold.it/150x150.jpg" width="150" height="150" />',
    style=ParagraphStyle(
        name='Image',
        borderWidth=3,
        borderColor=HexColor('#000000')
    )
)
Run Code Online (Sandbox Code Playgroud)

我还尝试搜索 XML 是否有办法为边框内联样式,但没有找到任何东西。

任何建议表示赞赏!谢谢 :) 如果是这种情况,请告诉我是否甚至不可能!

解决方案:

凭借G Gordon Worley III的想法,我能够编写出有效的解决方案!下面是一个例子:

from reportlab.platypus import Table

img_width = 150
img_height = 150
img = Image(filename='url_of_img_here', width=img_width, height=img_height)
img_table = Table(
    data=[[img]],
    colWidths=img_width,
    rowHeights=img_height,
    style=[
        # The two (0, 0) in each attribute represent the range of table cells that the style applies to. Since there's only one cell at (0, 0), it's used for both start and end of the range
        ('ALIGN', (0, 0), (0, 0), 'CENTER'),
        ('BOX', (0, 0), (0, 0), 2, HexColor('#000000')), # The fourth argument to this style attribute is the border width
        ('VALIGN', (0, 0), (0, 0), 'MIDDLE'),
    ]
)
Run Code Online (Sandbox Code Playgroud)

然后只需添加img_table到您的流动列表中:)

G G*_*III 4

我认为你应该采取的方法是将图像放在表格中。表格样式非常适合您想要做的事情,并提供很大的灵活性。您只需要一个 1 x 1 的表格,其中图像显示在表格中唯一的单元格内。