3
votes

I want a logo file to be attached everytime in the word document, when I run the code,

Ideally the code should look like :

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

is this possible in the python-docx or should i try some other library to do this? if possible please tell me how,

2
A "header" in Word is a block of text in the top-margin area of each page, generally appearing the same on every page. A "heading" is often a "section heading" and is a title paragraph, generally bold and bigger than the body text, used to introduce a new section. Which do you want? - scanny

2 Answers

4
votes

with the following code, you can create a table with two columns the first element is the logo, the second element is the text part of the header

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

A simpler way to include logo and a header with some style (Heading 2 Char here):

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"