'Align table justify and add img to docx
i generate a report and save it as a doc file, im having some troubles in the design part.
Its better to show you. You can see bellow what i have enter image description here
Here is what i need enter image description here
Can someone help?
Here is my code
from docx.enum.style import WD_STYLE_TYPE
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx.shared import Pt, Cm
from docx2pdf import convert
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import docx
best_drivers_pdf=['dd-33-44:::12:::A','dd-23-44:::10:::A','dd-33-45:::6:::D','dd-33-44:::9:::B']
docpath = "Reports/file.docx"
mydoc = docx.Document()
section_g = mydoc.sections
section_h = mydoc.sections[0]
header = section_h.header
header_para = header.paragraphs[0]
footer = section_h.footer
footer_para = footer.paragraphs[0]
mydoc.sections[0].header_distance = Cm(0)
mydoc.sections[0].footer_distance = Cm(0)
runhead = header_para.add_run()
runhead.add_picture(path_logo.strip(), width=docx.shared.Cm(21.7), height=docx.shared.Cm(4.2))
runfoot = footer_para.add_run()
runfoot.add_picture("client_report/report_img/bottom.png", width=docx.shared.Cm(21.7),height=docx.shared.Cm(2.5))
for section in section_g:
section.top_margin = Cm(0)
section.bottom_margin = Cm(0)
section.left_margin = Cm(0)
section.right_margin = Cm(0)
styles = mydoc.styles
style = styles.add_style('Tahoma', WD_STYLE_TYPE.PARAGRAPH)
style.font.name = 'Tahoma'
style.font.size = Pt(11)
shd = OxmlElement('w:background')
shd.set(qn('w:color'), '407294')
mydoc.element.insert(0, shd)
shd1 = OxmlElement('w:displayBackgroundShape')
mydoc.settings.element.insert(0, shd1)
mydoc.add_heading('Best Drivers', 1).alignment = 1
tablebest = mydoc.add_table(rows=1, cols=4)
tablebest.style = 'Colorful List'
row = tablebest.rows[0].cells
row[0].text = ''
row[1].text = 'vehicle'
row[2].text = 'Points'
row[3].text = 'Grade'
for x in best_drivers_pdf:
p, v, g = x.split(":::")
row = tablebest.add_row().cells
row[0].text = ''
#row[0].add_picture("report_img/green_car.png", width=docx.shared.Cm(2),height=docx.shared.Cm(2))
row[1].text = str(v)
row[2].text = str(p)
row[3].text = str(g)
tablebest.alignment = WD_TABLE_ALIGNMENT.CENTER
mydoc.save(docpath)
Can someone help me get the table justify to center and add img to the first row of each table? First row is left empty for that porpuse but i cant seem to do it :(
Solution 1:[1]
for x in range(0, 5):
for cell in tablebest.columns[x].cells:
if x==0 or x==4:
cell.width = Cm(3)
else:
cell.width = Cm(2)
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | bizric |
