Home > Software design >  How to ask python docx to write in italic type just
How to ask python docx to write in italic type just

Time:10-25

How to ask python docx to write in italic type but not the entire sentence, just some words ?

I have this code :

names = ["names1"]
dates = ["dates1"]
client = ["client1"]

from docx import Document

document = Document('filename.docx')

paragraphs = document.paragraphs




paragraphs[0].insert_paragraph_before("       To    " names "         Date  " dates)
paragraphs[0].insert_paragraph_before("                                             ")
paragraphs[0].insert_paragraph_before("      From   " names "             Ref   " client)
paragraphs[0].insert_paragraph_before("                                                ")

I know how to specify an entire sentence to be in italic type, but not how to tell python to transform just one word in italic type.

Here, I would like to transform To, Date, From, Ref but just those four word, not the rest.

Have you an idea how to do that ?

CodePudding user response:

Character formatting, such as bold and italic, is applied to a run. A paragraph is composed of zero or more runs.

When you specify the paragraph text as a parameter to the .add_paragraph() call (or .insert_paragraph_before() call), the resulting paragraph contains a single run containing all the specified text and having default formatting.

To do what you want, you will need to build up the paragraph text run by run, like so:

paragraph = paragraphs[0].insert_paragraph_before()

paragraph.add_run("       ")
run = paragraph.add_run("To")
run.italic = True
paragraph.add_run("    "   names   "         ")
run = paragraph.add_run("Date")
run.italic = True
paragraph.add_run("  "   dates)

CodePudding user response:

You can do something like this:

p = document.add_paragraph()
p.add_run('To').italic = True
p.add_run(" " names " ")
p.add_run('Date').italic = True

and so on.

  • Related