使用python-docx在Word文档的页眉中添加徽标

时间:2018-11-26 06:18:36

标签: python-3.x python-docx

当我运行代码时,我希望徽标文件每次都附加在word文档中,

理想情况下,代码应如下所示:

from docx import Document
document = Document()
logo = open('logo.eps', 'r')                  #the logo path that is to be attached
document.add_heading('Underground Heating Oil Tank Search Report', 0) #simple heading that will come bellow the logo in the header.
document.save('report for xyz.docx')              #saving the file

这在python-docx中是否可行,还是我应该尝试其他一些库来做到这一点?可能的话,请告诉我如何,

2 个答案:

答案 0 :(得分:0)

使用以下代码,您可以创建一个具有两列的表,第一个元素是徽标,第二个元素是标题的文本部分

from docx import Document
from docx.shared import Inches, Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
document = Document()
header = document.sections[0].header
htable=header.add_table(1, 2, Inches(6))
htab_cells=htable.rows[0].cells
ht0=htab_cells[0].add_paragraph()
kh=ht0.add_run()
kh.add_picture('logo.png', width=Inches(1))
ht1=htab_cells[1].add_paragraph('put your header text here')
ht1.alignment = WD_ALIGN_PARAGRAPH.RIGHT
document.save('yourdoc.docx')

答案 1 :(得分:0)

包含徽标和具有某种样式的标题的更简单方法(此处为标题2个字符):

from docx import Document from docx.shared import Inches, Pt
doc = Document()

header = doc.sections[0].header
paragraph = header.paragraphs[0]

logo_run = paragraph.add_run()
logo_run.add_picture("logo.png", width=Inches(1))

text_run = paragraph.add_run()
text_run.text = '\t' + "My Awesome Header" # For center align of text
text_run.style = "Heading 2 Char"