python-openxml / python-docx

Create and modify Word documents with Python
MIT License
4.54k stars 1.11k forks source link

Duplicate document styles #1375

Open pixelmultiplo opened 5 months ago

pixelmultiplo commented 5 months ago

I'm trying to duplicate a document styles in another. This is my code so far. The styles are copied but without any properties or formatting. In the target document i got all the styles, but they all look like the Normal style.

How can this be done? Another way could be make a deepcopy of the document and them empty it, but i'm not sure how to do it either.

Thanks.

`import pprint import copy from docx import Document

Load the .docx file

sourceDoc = Document('source.docx')

Create a new .docx file

termDoc = Document()

for style in sourceDoc.styles: if style.name not in termDoc.styles: termDoc.styles.add_style(style.name, style.type)

for paragraph in sourceDoc.paragraphs: if 'ž' in paragraph.text: paragraph.text = paragraph.text.replace('ž', '→') if '„' in paragraph.text: paragraph.text = paragraph.text.replace('„', '▶')

termDoc.add_paragraph(paragraph.text, paragraph.style.name)

termDoc.save('term.docx')`