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



每次运行代码时,我都希望在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中可能吗?或者我应该尝试其他库来做到这一点吗?如果可能的话,请告诉我怎么做,

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

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')

包含徽标和具有某种样式的页眉(此处为页眉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"

最新更新