Search code examples
pythonpython-docx

python-docx to set different styles for every paragraph


I am trying to set different style settings for paragraphs with python-docx, but I always end with the same style settings for all paragraphs, even when I specify different styles settings for each one.

This is my code:

def get_operation_word_file(self, request, context):
    import unicodedata
    from django.core.files import File
    from docx import Document
    from docx.shared import Inches, Pt

    document = Document()

    section = document.sections[-1]
    section.top_margin = Inches(0.5)
    section.bottom_margin = Inches(0.5)
    section.left_margin = Inches(0.5)
    section.right_margin = Inches(0.5)

    style = document.styles['Normal']
    font = style.font
    font.name ='Arial'
    font.size = Pt(10)

    company_paragraph = document.add_paragraph("EUROAMERICA TTOO INC").alignment = WD_ALIGN_PARAGRAPH.CENTER
    company_paragraph.style.font.size = Pt(20)
    company_paragraph.style.font.bold = True

    description_paragraph = document.add_paragraph("Operación de {} del día {}".format(operation_type[self.operation_type], self.operation_date)).alignment = WD_ALIGN_PARAGRAPH.CENTER
    description_paragraph.style.font.size = Pt(16)
    description_paragraph.style.font.bold = False

    day_paragraph = document.add_paragraph(weekdays[str(self.get_operation_date().weekday())]).alignment = WD_ALIGN_PARAGRAPH.CENTER
    day_paragraph.style.font.size = Pt(16)
    day_paragraph.style.font.bold = False

    current_directory = settings.MEDIA_DIR
    file_name = "Operaciones {} {}.docx".format(self.operation_type, self.operation_date)
    document.save("{}/{}".format(current_directory, file_name))

    return file_name

In the resulting document, the three paragraphs that I add end with the same size and bold setting.

I don't know what I am missing in order to make each paragraph to have its own style settings.


Solution

  • A style is applied to a paragraph by reference, not by copying its attributes. So if all your paragraphs have "Normal" style, they all get the styling that "Normal" ends up with, which is your last setting.

    So you will need to use a different style for each paragraph that needs to look different, or you can just apply the formatting directly to the paragraph, without using a style. This latter approach might be more suitable for a paragraph that is unique in the document.

    All of the formatting characteristics that can be set on a style can also be applied directly.

    The use of styles is covered in the python-docx documentation here:
    https://python-docx.readthedocs.io/en/latest/user/styles-using.html