2016-01-01 95 views
0

有沒有辦法將框架周圍的內嵌圖片與python docx框架周圍的內嵌圖片

我有類似:

from docx import Document 
from docx.shared import Mm 

document = Document() 
table = document.add_table(rows=1, cols=3) 
pic_cells = table.rows[0].cells 
paragraph = pic_cells[0].paragraphs[0] 
run = paragraph.add_run() 
run.add_picture('testQR.png', width=Mm(15), height=Mm(15)) 
document.save('demo.docx') 

我需要把一幀圖像周圍,以紀念這個圖像的邊框(應該是與圖像尺寸相同)。

如何使用python docx package對此進行格式化?

回答

0

看來docx目前不支持這種功能。 由於您使用的表,你也許可以做的是以下幾點:

  1. 創建新的Word模板
  2. 定義自定義表樣式與邊框的單元中,你要去的地方你的圖像
  3. 使用模板的Python腳本docx這樣的:document = Document('template.docx')
  4. 應用剛剛創建

請重新表格樣式廣告this thread瞭解更多詳情。

另一種方法可能不太優雅,但100%的工作。在docx中使用它之前,您只需在圖像周圍創建邊框。 您可以使用PIL(用於python2)或Pillow(用於pyhton3)模塊進行圖像處理。

from PIL import Image 
from PIL import ImageOps 
img = Image.open('img.png') 
img_with_border = ImageOps.expand(img, border=1, fill='black') 
img_with_border.save('img-with-border.png') 

此代碼將您img.png文件,並創建一個1px的黑色邊框勾勒出新img-with-border.png。那麼只需在你的run.add_picture聲明中使用img-with-border.png即可。

+0

感謝您提供整潔的「枕頭」主意。這真正解決了圖片的問題 - 但不適用於文本。我將深入探討爲單元格模板樣式的可能性。 – Stefan

+0

@Stefan如果你對預先定義的表格樣式不錯,那麼只需應用[此列表]中的一個(https://python-docx.readthedocs.org/en/latest/user/styles-understanding.html#table-styles -in默認模板)。但是,如果您需要自定義樣式(如爲特定單個單元格創建邊框),那麼您別無選擇,只能創建自己的模板,正如我在答案中所述。 – vrs