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

时间:2013-07-18 19:13:47

标签: python html xml reportlab

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

查看ReportLab's userguide后,Image()无法直接应用边框。所以有一些技巧我认为我会试图看看是否可以模拟图像周围的边框。

起初,我认为为每个图像创建帧不仅会让人感到痛苦,而且帧的边框只是用于调试的纯黑线,无法以任何方式进行自定义。我希望能够改变边框的厚度和颜色,这样选项就没有用了。

然后我注意到Paragraph()能够采用ParagraphStyle(),它可以应用某些样式,包括边框。 Image()没有ParagraphStyle()等价物,所以我想也许我可以使用Paragraph()而不是创建一个包含XML'img'标签的字符串,其中包含我拥有的图像网址,然后应用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添加到您的flowables列表中:)

1 个答案:

答案 0 :(得分:2)

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

相关问题