5

我正在为一些包含图像的产品构建 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')
    )
)

我还尝试搜索 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'),
    ]
)

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

4

1 回答 1

3

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

于 2013-07-19T13:47:18.657 回答