Back to Top

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

Updated 13 July 2021

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

Searching for an experienced
Odoo Company ?
Find out More

cd python-docx-{version}

python setup.py install

4) 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:[email protected]   .   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.

Test_file

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

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


9 comments

  • Emilio
    • Jahangir Naik (Moderator)
      • Emilio
  • Divyansh Tripathi
    • Jahangir Naik (Moderator)
      • Divyansh
        • Ankit
          • Jahangir
      • Megha Joshi (Moderator)
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home