2013-07-18 44 views
2

我正在爲包含圖像的某些產品構建PDF。很多這些圖像都有白色背景,所以我真的很想在它們周圍添加邊框。在創建PDF時我給出了一個圖像URL,我可以直接將它傳遞給reportlab的Image(),它會顯示它很好。這是一個棘手的部分。是否可以在ReportLab中爲圖像添加邊框?

通過瀏覽ReportLab's userguide後,Image()無法直接應用邊框。所以有一些技巧我以爲我會試圖看看我是否可以模擬圖像邊框。

起初,我認爲爲每個圖像創建幀不僅是一種痛苦,而且幀的邊界只是用於調試的純黑線,並且不能以任何方式定製。我希望能夠改變邊框的厚度和顏色,這樣這個選項就沒有前途。

然後我注意到段落()能夠採用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有辦法內聯的邊框風格,但沒有找到任何東西

任何建議表示讚賞!謝謝:)讓我知道,如果這是不可能的,如果是這樣的話!

SOLUTION:

隨着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到您的可流動的名單:)

回答

2

我想你應該採取的方法是把圖像的表內。表格樣式適用於您想要做的事情並提供很大的靈活性。您只需要一個1乘1的表格,圖像顯示在表格中唯一的單元格內。

+0

這是一個好主意!我採取了這種方法,並想出瞭如何將圖像放入1x1表格中並對其進行設計:)正是我需要的,謝謝! – missmely

相關問題