SoFunction
Updated on 2025-04-21

Python implements automated Word layout

Word is a widely used document editing tool, but may encounter tedious and repetitive operations during the typography process. Fortunately, with the power of the Python programming language, we can realize automated Word typography and improve the efficiency and quality of document editing. This article will introduce how to use Python to implement automated Word typesetting to make document editing more efficient and convenient.

1. Import the necessary libraries

In Python, we can use the python-docx library to manipulate Word documents. It provides a wealth of functions and methods for creating, modifying, and formatting Word documents. We can import the python-docx library through the following code:

import docx

2. Open Word document

First, we need to open the Word document to be typed. You can use the `Document` class provided by the python-docx library to open an existing document.

Open Word document:

doc = ('')

3. Automatic layout

Next, we will use the features provided by the python-docx library to implement automated Word typography. Here are some common typesetting examples:

1. Set page size and margins:

[0].page_width = (8.5)
[0].page_height = (11)
[0].left_margin = (1)
[0].right_margin = (1)
[0].top_margin = (1)
[0].bottom_margin = (1)

2. Insert the title:

doc.add_heading('Automated Word Typesetting', level=1)

3. Insert paragraph:

doc.add_paragraph('In today's article, we will introduce how to use Python to implement automated Word typography.  ')

4. Set font style:

paragraph = doc.add_paragraph()
run = paragraph.add_run('This is a sample text.  ')
font = 
 = 'Arial'
 = (12)
 = True

5. Insert the picture:

doc.add_picture('', width=(4), height=(3))

4. Save and close the document

After completing the layout, we need to save and close the document.

1. Save the document:

('formatted_example.docx')

2. Close the document:

()

5. Summary

By using Python's python-docx library, we can easily implement automated Word typography. By opening documents, automating typography, and saving and closing documents, we can improve the efficiency and quality of document editing.

Reference code:

import docx
doc = ('')
#Automatic typesetting operation examples[0].page_width = (8.5)
[0].page_height = (11)
[0].left_margin = (1)
[0].right_margin = (1)
[0].top_margin = (1)
[0].bottom_margin = (1)
doc.add_heading('Automated Word Typesetting', level=1)
doc.add_paragraph('In today's article, we will introduce how to use Python to implement automated Word typography.  ')
paragraph = doc.add_paragraph()
run = paragraph.add_run('This is a sample text.  ')
font = 
 = 'Arial'
 = (12)
 = True
doc.add_picture('', width=(4), height=(3))
# Save and close the document('formatted_example.docx')
()

6. Supplementary method

One-click Word layout tool written in Python

import docx
from  import qn
from  import Pt, Cm, Mm
from  import *
import os
import sys
from docx import Document
from  import QApplication, QFileDialog
# Delete paragraphdef delete_paragraph(paragraph):
    p = paragraph._element
    ().remove(p)
# p._p = p._element = None
    paragraph._p = paragraph._element = None
 
#Judge whether it is signed formatdef LuoKuan(str):
    for i in str:
        if i in punc:
            return False
    if ((str[0] in num) and (str[-1] == "day") and (len(str) <= 12)) or ((str[0] in cn_num) and (str[-1] == "day") and (len(str) <= 12)):
        return True
    else:
        return False
def setMargin(docx):
    section = [0]
    section.page_height = Cm(29.7)
    section.page_width = Cm(21.0)
    section.left_margin = Cm(2.8)
    section.right_margin = Cm(2.6)
    section.top_margin = Cm(3.7)
    section.bottom_margin = Cm(3.5)
 
#Determine whether it is a first-level title format (such as: 1, xxx)def GradeOneTitle(str):
    if ((str[0] in cn_num) and (str[1] == "、")) or ((str[0] in cn_num) and (str[1] in cn_num) and (str[2] == "、")):
        return True
    else:
        return False
 
#Determine whether it is a secondary title format (such as: (a) xxx)def GradeTwoTitle(str):
    if ((str[0] == "(") and (str[1] in cn_num) and (str[2] == ")")) or ((str[0] == "(") and (str[1] in cn_num) and (str[2] in cn_num) and (str[3] == ")")):
        return True
    else:
        return False
#Determine whether it is a third-level title format (such as:)def GradeThreeTitle(str):
    if ((str[0] in num) and (str[1] in punc)) or ((str[0] in num) and (str[1] in num) and (str[2] in punc)):
        return True
    else:
        return False
#Determine whether it is a Level 4 title format (such as: (1) xxx)def GradeFourTitle(str):
    if ((str[0] == "(") and (str[1] in num) and (str[2] == ")")) or ((str[0] == "(") and (str[1] in num) and (str[2] in num) and (str[3] == ")")):
        return True
    else:
        return False
 
#Determine whether it is a level five title format (such as: one is XXX)def GradeFiveTitle(str):
    if ((str[0] in cn_num) and (str[1] in must)) or ((str[0] in cn_num) and (str[1] in cn_num) and (str[1] in must)):
        return True
    else:
        return False
 
def OneKeyWord():
    global cn_num,num,punc,must
    cn_num = ["one", "two", "three", "Four", "five", "six", "seven", "eight", "Nine", "ten"]
    num = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
    punc = ["。", ",", "!", "?", ":", ";", "、", ".", "(", ")","."]
    must = ["want", "yes", "able"]
    filecnt = 0
    print('Welcome to use Word one-click layout tool!  Creator QQ: 124500535')
    confirm= input("Do you open the Word document? Enter "Y" to indicate "Open", and enter "N" to indicate "Cancel"!")
    if confirm == 'Y' or confirm == 'y':
        a = QApplication([''])
        files, stylel = (caption="Multiple file selection", directory="/", filter="Word document(*.docx)")
        print(files)  # Print all paths of the selected file (including file name and suffix name) and file type        for file in files:
            docx = Document(file)
            paragraphcnt = 0
            filecnt= filecnt+1
            print('This is the %s file: %s' %(filecnt,file))
            for paragraph in :
                paragraphcnt = paragraphcnt +1
                =(",",",")
                =(";",";")
                =(":",":")
                =("!","!")
                =("?","?")
                =("(","(")
                =(")",")")
                =(" ","")
                =("\t", "")
                 = ("\n", "")
                if  == '':
                    delete_paragraph(paragraph)
                    paragraphcnt = paragraphcnt-1
                    continue
                paragraph.paragraph_format.left_indent = 0  #Assign values ​​to indentation in advance to prevent errors from being empty                paragraph.paragraph_format.(qn("w:firstLineChars"), '0')  # and remove indentation                paragraph.paragraph_format.(qn("w:firstLine"), '0')
                paragraph.paragraph_format.(qn("w:leftChars"), '0')
                paragraph.paragraph_format.(qn("w:left"), '0')
                paragraph.paragraph_format.(qn("w:rightChars"), '0')
                paragraph.paragraph_format.(qn("w:right"), '0')
                print('This is the %s paragraph' %paragraphcnt)
                print()
                if paragraphcnt == 1 and len()<40:
                    #Processing empty lines on the head                    #Title (Fangzheng Xiaobiao Song_GBK, No. 2, bold, center, lower end press No. 2 to empty one line)                    paragraph.paragraph_format.line_spacing=Pt(28)  #Fixed value of 28 pounds                    paragraph.paragraph_format.space_after = Pt(0)  #Segment spacing = 0                    for run in :
                         = Pt(22)  # Font size 2                         = False  # Bold                         = 'Fang Zheng Xiaobiao Song_GBK'  # Control is a font in Western language                        (qn('w:eastAsia'), 'Fang Zheng Xiaobiao Song_GBK')  # Control the font when it is Chinese                         = WD_ALIGN_PARAGRAPH.CENTER # Center                    continue
                elif paragraphcnt == 2 and len() < 30:
                    # Author's unit, name                    paragraph.paragraph_format.line_spacing = Pt(28)  # Line spacing fixed value 28 pounds                    paragraph.paragraph_format.space_after = Pt(0)  # The spacing after segment = 0                    for run in :
                         = Pt(16)  # Font size 2                         = False  # Bold                         = 'Kaiyi'  # Control is a font in Western language                        (qn('w:eastAsia'), 'Kaiyi')  # Control the font when it is Chinese                         = WD_ALIGN_PARAGRAPH.CENTER  # Center                    continue
                elif paragraphcnt == 3 and len() < 30 and ([0] == "(") and ([1] in num):
                    # Date, such as (June 15, 2023)                    paragraph.paragraph_format.line_spacing = Pt(28)  # Line spacing fixed value 28 pounds                    paragraph.paragraph_format.space_after = Pt(0)  # The spacing after segment = 0                    for run in :
                         = Pt(16)  # Font size 2                         = False  # Bold                         = 'Kaiyi'  # Control is a font in Western language                        (qn('w:eastAsia'), 'Kaiyi')  # Control the font when it is Chinese                         = WD_ALIGN_PARAGRAPH.CENTER  # Center                    continue
                    # #Processing the text                else:
                    paragraph.paragraph_format.line_spacing = Pt(28)  # Line spacing fixed value 28 pounds                    paragraph.paragraph_format.space_after = Pt(0)  # The spacing after segment = 0                    paragraph.paragraph_format.first_line_indent = Pt(32)
                    for run in :
                         = Pt(16)  # Font size 3                         = False  # Font not thick                         = 'Imitation Song_GB2312'
                        (qn('w:eastAsia'), 'Imitation Song_GB2312')
                        if GradeOneTitle(): #Determine whether it is a first-level title format (such as: 1, xxx)                             = 'Boldbody'
                            (qn('w:eastAsia'), 'Boldbody')
                        elif GradeTwoTitle(): #Determine whether it is a secondary title format (such as: (a) xxx)                            if "。" not in :
                                 = 'Kaiyi'
                                (qn('w:eastAsia'), 'Kaiyi')
                            else:
                                 = ('。',1)
                                 = 'Kaiyi'
                                (qn('w:eastAsia'), 'Kaiyi')
                        elif GradeThreeTitle(): #Determine whether it is a third-level title format (such as:)                            if "。" not in :
                                if ([0] in num) and ([1] in punc):
                                     = ([1], ".",1)
                                if ([0] in num) and ([1] in num) and ([2] in punc):
                                     = ([2], ".", 1)
                                 = 'Imitation Song_GB2312'
                                (qn('w:eastAsia'), 'Imitation Song_GB2312')
                                 = True  # font bold                            else:
                                if ([0] in num) and ([1] in punc):
                                     = ([1], ".", 1)
                                if ([0] in num) and ([1] in num) and ([2] in punc):
                                     = ([2], ".", 1)
                                sentence_to_bold = ('。')[0]+"。"
                                sentence_not_to_bold = ('。',1)[1]
                                paragraph.insert_paragraph_before(sentence_to_bold)
                                [paragraphcnt - 1].paragraph_format.first_line_indent = Pt(32)
                                [paragraphcnt - 1].paragraph_format.line_spacing = Pt(28)  # Line spacing fixed value 28 pounds                                [paragraphcnt - 1].paragraph_format.space_after = Pt(0)  # The spacing after segment = 0                                [paragraphcnt - 1].runs[0]. = 'Imitation Song_GB2312'
                                [paragraphcnt - 1].runs[0]. = Pt(16)  # Font size 3                                [paragraphcnt - 1].runs[0].(qn('w:eastAsia'), 'Imitation Song_GB2312')
                                [paragraphcnt - 1].runs[0].bold = True  # font bold                                [paragraphcnt - 1].add_run(sentence_not_to_bold).bold = False
                                [paragraphcnt - 1].runs[1]. = 'Imitation Song_GB2312'
                                [paragraphcnt - 1].runs[1]. = Pt(16)  # Font size 3                                [paragraphcnt - 1].runs[1].(qn('w:eastAsia'), 'Imitation Song_GB2312')
                                delete_paragraph(paragraph)
                        elif GradeFourTitle(): #Determine whether it is a Level 4 title format (such as: (1) xxx)                            if "。" not in :
                                 = 'Imitation Song_GB2312'
                                (qn('w:eastAsia'), 'Imitation Song_GB2312')
                                 = True  # font bold                            else:
                                sentence_to_bold = ('。')[0]+"。"
                                sentence_not_to_bold = ('。',1)[1]
                                paragraph.insert_paragraph_before(sentence_to_bold)
                                [paragraphcnt - 1].paragraph_format.first_line_indent = Pt(32)
                                [paragraphcnt - 1].paragraph_format.line_spacing = Pt(28)  # Line spacing fixed value 28 pounds                                [paragraphcnt - 1].paragraph_format.space_after = Pt(0)  # The spacing after segment = 0                                [paragraphcnt - 1].runs[0]. = 'Imitation Song_GB2312'
                                [paragraphcnt - 1].runs[0]. = Pt(16)  # Font size 3                                [paragraphcnt - 1].runs[0].(qn('w:eastAsia'), 'Imitation Song_GB2312')
                                [paragraphcnt - 1].runs[0].bold = True  # font bold                                [paragraphcnt - 1].add_run(sentence_not_to_bold).bold = False
                                [paragraphcnt - 1].runs[1]. = 'Imitation Song_GB2312'
                                [paragraphcnt - 1].runs[1]. = Pt(16)  # Font size 3                                [paragraphcnt - 1].runs[1].(qn('w:eastAsia'), 'Imitation Song_GB2312')
                                delete_paragraph(paragraph)
                        elif GradeFiveTitle(): #Determine whether it is a level five title format (such as: one is xxx)                            if "。" not in :                                
                                 = 'Imitation Song_GB2312'
                                (qn('w:eastAsia'), 'Imitation Song_GB2312')
                                 = True  # font bold                            else:                                
                                sentence_to_bold = ('。')[0]+"。"
                                sentence_not_to_bold = ('。',1)[1]
                                paragraph.insert_paragraph_before(sentence_to_bold)
                                [paragraphcnt - 1].paragraph_format.first_line_indent = Pt(32)
                                [paragraphcnt - 1].paragraph_format.line_spacing = Pt(28)  # Line spacing fixed value 28 pounds                                [paragraphcnt - 1].paragraph_format.space_after = Pt(0)  # The spacing after segment = 0                                [paragraphcnt - 1].runs[0]. = 'Imitation Song_GB2312'
                                [paragraphcnt - 1].runs[0]. = Pt(16)  # Font size 3                                [paragraphcnt - 1].runs[0].(qn('w:eastAsia'), 'Imitation Song_GB2312')
                                [paragraphcnt - 1].runs[0].bold = True  # font bold                                [paragraphcnt - 1].add_run(sentence_not_to_bold).bold = False
                                [paragraphcnt - 1].runs[1]. = 'Imitation Song_GB2312'
                                [paragraphcnt - 1].runs[1]. = Pt(16)  # Font size 3                                [paragraphcnt - 1].runs[1].(qn('w:eastAsia'), 'Imitation Song_GB2312')
                                delete_paragraph(paragraph)
                        elif LuoKuan():  # Determine whether it is signed format                             = 'Imitation Song_GB2312'
                            (qn('w:eastAsia'), 'Imitation Song_GB2312')
                             = "\r" * 2 +   # The front space, top to the right, and the space needs to be adjusted manually                            paragraph.paragraph_format.left_indent = Pt(288)    #18B*16Pt=288Pt
                        else: #Normal body format                             = 'Imitation Song_GB2312'
                            (qn('w:eastAsia'), 'Imitation Song_GB2312')
            setMargin(docx)
            (file)
if __name__ == '__main__':
    OneKeyWord()
    ("pause")

This is the end of this article about Python’s automated Word typography. For more related Python Word typography, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!