Search code examples
pythonms-worddocxpython-docx

Write a word document with each character having a different font


I have 3 fonts. I want to modify the Word document such that each character (alphabet) is assigned one of the three fonts randomly or in some order, I don't mind. No two consecutive characters should be of the same font.

I tried writing a python script but the much I tried to understand the docx-Python library I think only the paragraph-level styling is possible.

This is what I attempted:

import docx
from docx.shared import Pt

doc = docx.Document("Hey.docx")

mydoc = docx.Document()

style1 = mydoc.styles['Normal']
font1=style1.font
font1.name = 'Times New Roman'
font1.size = Pt(12.5)

style2 = mydoc.styles['Normal']
font2=style2.font
font2.name = 'Arial'
font2.size = Pt(15)

all_paras = doc.paragraphs
for para in all_paras:
    mydoc.add_paragraph(para.text,style=style1)
    print("-------")
mydoc.save("bye.docx")

If hey.docx has "Hello" as text : Bye.docx should have "H(in font A)e(in font B) l(in font C)l(in font A)o(in font B)"


Solution

  • Add each character as a separate run within the paragraph and assign a character style to each run.

    from docx import Document
    from docx.enum.style import WD_STYLE_TYPE as ST
    
    document = Document()
    
    styles = document.styles
    style_A = styles.add_style("A", ST.CHARACTER)
    style_A.font.name = "Arial"
    style_A.font.size = Pt(15)
    style_B = styles.add_style("B", ST.CHARACTER)
    style_B.font.name = "Times New Roman"
    style_B.font.size = Pt(12.5)
    
    paragraph = document.add_paragraph()
    for idx, char in enumerate("abcde"):
        paragraph.add_run(char, style_A if idx % 2 else style_B)
    
    document.save("output.docx")
    

    I'll leave it to you to create additional character styles and invent a more sophisticated way of determining which style to assign to each character.