A
A
Alan Gibizov2020-12-25 09:10:02
Python
Alan Gibizov, 2020-12-25 09:10:02

How to remove fields from docx from python and at the same time keep the text entered there?

According to the zoldaten recipe, I open docx using python using the docxtemplate library , the values ​​​​are decomposed from the dictionary into managed document fields (or what is it called? ContentControls?)

The code
context = {'Договор': agreement,
           'Название_подрядчика': opponent_name,
           'Подрядчик_коротко': opponent_short_name,
           'ГД_подрядчика': directors_name}


def make_next_doc(path_to_temple: Path, 
                  context: dict, 
                  output_name: str, 
                  directory: Path):
    doc = DocxTemplate(path_to_temple/"template.docx")
    doc.render(context)
    doc.save(directory/f"{output_name}.docx")

At the same time, the template.docx file should contain formula fields with approximately the following content:
{{Agreement}}
- instead of them, the value from agreement is substituted.
This is all working fine.
But there is a nuance...
The next time you open the document, all these fields are highlighted, and word goes into "design" mode. It doesn't look very good, and it's not in order at all. Users are scared.
How to remove all these fields, but leave what the script entered there.

Digging in the internet, I found that it seems like you can do this with the Word command "RemoveContentControlsAndKeepContents".

But how does this command work from Python? Maybe through win32 and Word.Application get confused? But how, I don’t catch up with something ... I kept red-eyed all night.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question