我正在制作一份包含图片的产品PDF。其中许多图片都有白色背景,因此我希望在它们周围添加边框。在创建PDF时,我会得到一个图片URL,可以直接传递给reportlab的Image()方法,并且可以正常显示。但是添加边框就比较麻烦了。
在查看ReportLab用户指南后,发现Image()方法没有直接应用边框的功能。因此,我考虑尝试一些技巧来模拟图片周围的边框。
起初,我认为为每个图像创建框架不仅很麻烦,而且框架的边框只是用于调试的纯黑色线条,无法以任何方式自定义。我想要能够更改边框的厚度和颜色,所以这个选项并不可行。
然后只需将
在查看ReportLab用户指南后,发现Image()方法没有直接应用边框的功能。因此,我考虑尝试一些技巧来模拟图片周围的边框。
起初,我认为为每个图像创建框架不仅很麻烦,而且框架的边框只是用于调试的纯黑色线条,无法以任何方式自定义。我想要能够更改边框的厚度和颜色,所以这个选项并不可行。
然后我发现Paragraph()可以使用ParagraphStyle(),它可以应用某些样式,包括边框。Image()没有等效的ParagraphStyle(),所以我想也许我可以使用Paragraph()来创建一个包含图像url的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
添加到您的可流动对象列表中即可 :)