Request Quote

Create .docx file in python(Odoo): python-docx

In this tutorial, I will discuss how to create the .docx file using python. In python one of the ways to create the .docx file is using the pythondocx library. Recently I was working on a project in Odoo where I needed to create a .docx file using python. I faced some challenges that I am sharing here.  I will show how to add the images, header, footer, etc in the .docx file.

In order to start with the python-docx, you have to install the library, you can install the library using any of the following ways.
1) You can install it using pip as:

pip install python-docx

2)You can install it using easy_install as:

easy_install python-docx

3) You can also install it by manually downloading from PyPI, unpack it and then simply run setup.py

tar xvzf python-docx-{version}.tar.gz
cd python-docx-{version}
python setup.py install

After the library is installed you can create a .docx file. I will create a “Test_word.docx” file and I will explain the meaning of some words also.

from docx import Document   #Import the Document
from docx.shared import Inches   #Import Inches, used to set width, height etc
from docx.shared import Pt   #Import Pt, used to font etc
document = Document()  
logo_path = 'logo.png'    # Path of the image file
section = document.sections[0]   # Create a section
sec_header = section.header   # Create header 
header_tp = sec_header.add_paragraph()  # Add a paragraph in the header, you can add any anything in the paragraph
header_run = header_tp.add_run()   # Add a run in the paragraph. In the run you can set the values 
header_run.add_picture(logo_path, width=Inches(2.0))  # Add a picture and set width.
rml_header = "\t\t This is the header message"
header_run.add_text(rml_header)
header_run.add_text("\n________________________________________________________________________________________________")
header_run.font.size =  Pt(8)
text = "Second Floor\nA 20 Sector 1\n Lajpat Nagar \nNew Delhi 201301\n______________"
table_main = document.add_table(rows=1, cols=2)

table_main.allow_autofit = True
tx_cells = table_main.rows[0].cells

tb_cell_run = tx_cells[0].add_paragraph().add_run()
tb_cell_run.add_text(text)
tb_cell_run.font.size =  Pt(8)
tx_cells[0].width = Inches(5)

pic_cells = table_main.rows[0].cells
pic_cell = pic_cells[1]

run = pic_cell.add_paragraph().add_run()
run.add_picture("user_image.jpg", width=Inches(0.8))

user_address = document.add_paragraph()
user_address_run = user_address.add_run()
user_address_run.text = "First Floor\nA 50 Sector 1\n Noida \n U.P 201301\n______________"
user_address_run.font.size =  Pt(8)
table = document.add_table(rows=1, cols=4)  #Create a table with and set the rows and columns
table.style = "Table Grid"   # Define the table style.  You can set any style defined in the styles files of the library
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Image'
hdr_cells[1].text = 'Product'
hdr_cells[2].text = 'Quantity'
hdr_cells[3].text = 'Unit Price'

records = [{'image':"1.jpeg", "product":"Product 1",'quantity':1, 'price':100}, {'image':"2.png", "product":"Product 2",'quantity':2, 'price':200}]
for record in records:
    row_cells = table.add_row().cells
    image_cell = row_cells[0].add_paragraph('')
    image_cell.add_run().add_picture(record.get('image'), width=Inches(0.5))
    row_cells[1].text = str(record.get('product'))
    row_cells[2].text = str(record.get('quantity')) 
    row_cells[3].text = str(record.get('price'))
section = document.sections[0]
default_footer = section.footer   # Add a footer
footer_p = default_footer.add_paragraph()
text = "Phone: 1256252352565  .  Email:test@gmail.com   .   Website: http://www.example.com"
footer_r = footer_p.add_run()
footer_r.add_text(text)
footer_r.font.size = Pt(8)

document.add_page_break()
document.save("Test_word.docx")  # Save the file

This is the screenshot of the file that has been created after compilation.

You can customize your file according to your requirement using the style, fonts, width, alignment, etc. You can check the features from the GitHub.
https://github.com/python-openxml/python-docx

If you are using Odoo then you can also save this file in the attachment and then can download it from there whenever required.

Attachment = self.env['ir.attachment'].sudo().create({
				'datas': base64Data,
				'type': 'binary',
				'res_model': 'modal.modal',
				'res_id': int(quote_id),
				'db_datas': 'Test_Docx.docx',
				'datas_fname':'Test_Docx.docx',
				'name':'Test_Docx.docx',
				}
				)

That is it.!!!
If you liked this post, I would be very grateful if you write your opinions, comments and suggestions to keep the post updated and interesting.
Thank you!

Current Product Version - 1.0.0

. . .

Comments (4)

Add Your Comment

  • Divyansh Tripathi
    Hey, thanks for the article but I was wondering if there any way to add the z-index to the image in python docx because I want to add the picture background in the word document. Any help is appreciated
    • Jahangir Naik
      Hi, I haven’t worked much on the images using python .docx yet, maybe Document.style will be used(but not sure). If you have some queries still you can raise a ticket at support@webkul.com and we will assist you there.
      • Divyansh
        No, it’s alright I figured a workaround and besides, there’s no way to add z-index to an image in python docx right now.
        Thanks for your efforts, anyway.
      • Megha Joshi
        Hello Divyansh,

        Thanks for the confirmation, for any further assistance kindly drop us a mail at – support@webkul.com

        Regards,
        Megha
        Webkul

  • css.php
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just recieved your project brief and our expert will contact you shortly.
    Send Again
    Close