使用python-docx在Word文档头部添加标志。

3

当我运行代码时,我希望每次将logo文件附加在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中可行,或者我应该尝试其他库来完成这个任务?如果可能,请告诉我如何做。


“Header”在Word中是每个页面顶部边距区域的一块文本块,通常在每个页面上都相同。而“heading”通常是“section heading”,是一个标题段落,通常比正文文本粗体和大号,用于引入新的章节。您需要哪一个? - scanny
2个回答

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

4
一个更简单的方法来包含logo和带一些样式的头部(这里是二级标题文本):
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"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接