Search code examples
pythonpython-3.xpython-docx

How to activate "Track changes"-Mode in a word document generated with python


for a recent project I've been generating .docx-Documents via python. I solved this by using the docxtpl-Package and Word docs as my jinja2-templates so the entire structure of the currently used word template can be maintained.

Now we've discussed that it would be really useful to see it visually in the document if anyone has changed the numbers or texts from the automatically generated document.

My question is - as i unfortunately have found no answers to this yet:

Is it possible to automatically turn on the "Track changes"-mode within every word document that's being generated?

The only way of doing, I found so far is this command-line tool - which i couldn't get to work so far and it looks like it has not been maintained the last 6 years:

https://github.com/kopz9999/track-word-changes

I'm currently developing on macOS, but the system will be running on Ubuntu machines. Thus, we can not use the pywin32 module.

Example Code, if it's any help:

from docxtpl import DocxTemplate
import json
import time
from docx2pdf import convert

class DocumentGenerator():
    def render_document(self, customerid, context):
        """
        :params customerid: Engagement number
        :params context: dict containing values for jinja2 template
        :return: returns absolute path of generated document
        _____________________________
        
        """
    
        doc = DocxTemplate("./templates/functional/template.docx")

    
        doc.render(context)
        save_path = f"./demo/{customerid}_generated_document.docx"
    
        doc.save(save_path)
    
        return save_path

Solution

  • Just turn it on in your template.docx that you're using as the starting point. The items you generate will not be tracked because python-docx doesn't (know how to) do that, so when opened in Word, it should start tracking (enclosing within revision marks) with any edits made to the generated version.

    This will bear testing of course, but I'm betting this will work fine. Make sure to clear any revision marks in template.docx before turning on "track-revisions" so you don't capture any "old" ones.