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

Tay*_*sir 4 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
Run Code Online (Sandbox Code Playgroud)

这在 python-docx 中可能吗?还是我应该尝试其他库来做到这一点?如果可能的话请告诉我怎么做

小智 5

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

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')
Run Code Online (Sandbox Code Playgroud)


bha*_*avi 5

包含徽标和具有某种样式的标题的更简单方法(此处为标题 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"
Run Code Online (Sandbox Code Playgroud)