In order to copy the text with its styles, you will need to write your own function, as there is no
python-docx function that does such a thing. This is the function I wrote:
def get_para_data(output_doc_name, paragraph)
output_para = output_doc_name.add_paragraph()
for run in paragraph.runs:
output_run = output_para.add_run(run.text)
output_run.bold = run.bold
output_run.italic = run.italic
output_run.underline = run.underline
output_run.font.color.rgb = run.font.color.rgb
output_run.style.name = run.style.name
output_para.paragraph_format.alignment = paragraph.paragraph_format.alignment
How The Function Works
1. Adds a new
paragraph
object to the file.
2. Adds a new
run
to that paragraph.
3. Checks whether each of the styles
bold,
italic and
underline is
True
,
False
,
None
. If it's
True
, the
run
will be in that style, if it's
False
, it won't be in that style, and if it's
None
, it will be inherited by the default style of the paragraph it's in. Then it applies the styles to the
run
.
3. Checks what's the color of the run in
RGB and applies the found color to the
run
.
4. Checks what's the font of the run and applies the found font to the
run
.
5. Checks what's the alignment of the run and applies the found alignment setting to the
run
.
How to Use the Function:
You need to give it the name you gave your output document and the paragraphs you want to copy.
For Example:
input_doc = Document('InputDoc.docx')
output_doc = Document()
get_para_data(output_doc, input_doc.paragraphs[3])
output_doc.save('OutputDoc.docx')
If you'd like to copy the entire document I suggest you do this:
for para in input_doc.paragraphs:
get_para_data(output_doc, para)
output_doc.save('OutputDoc.docx')