Python docx font size

To set the font size in a Python docx file, you can use the “python-docx” library. This library allows you to create and modify Word documents programmatically. To demonstrate this, consider the following example:

    
      from docx import Document
      from docx.shared import Pt

      # Create a new Word document
      document = Document()

      # Add a paragraph with a custom font size
      paragraph = document.add_paragraph('This is a paragraph with custom font size.')
      run = paragraph.runs[0]
      run.font.size = Pt(14)  # Set font size to 14pt

      # Save the document
      document.save('example.docx')
    
  

In the above example, we import the required modules from the “python-docx” library. We then create a new Word document using the “Document” class. Next, we add a paragraph to the document using the “add_paragraph” method. We access the first run (sequence of characters with the same style) in the paragraph using “paragraph.runs[0]”. Finally, we set the font size of the run to 14pt using “run.font.size = Pt(14)”.

Remember to install the “python-docx” library if you haven’t already. You can install it using pip:

    
      pip install python-docx
    
  

This code will create a Word document named “example.docx” with a paragraph containing custom font size.

Leave a comment