1

Microsoft Word tool has default privacy settings with disabled macros and Trusted VB scripts set unchecked. So, writing Macros(VB script) to update fields is not a good idea in order to tell users to allow Macros attached to the document file by changing settings.

Open your generated Docx file and press 'alt' + 'F9'. This command will reveal all the field codes. We will be using field code '{NUMPAGES}'(with curly braces) for total number of pages. Note, footer and header are auto updated fields(automatically updates the fields once the document is opened), but for TOC we cannot put it in header or footer. Close the document file.

In your code where you have used xml tags for {NUMPAGES}, set dirty to true, ie., var totalPages = '<w:instrText w:instr="TOC" w:dirty="true"> NUMPAGES </w:instrText> and in Docx Template file, use {@totalPages} to map xml value.

Docx file is actually a zip file, rename the template document file from '.docx' to '.zip'. You will find couple of folders and files in zip. Folder 'word' contains your main document.xml(document file content) and settings.xml(document file settings) files. Open 'settings.xml', and write <w:updateFields w:val="true" /> under <w:settings> tag make sure you write above code before </w:settings>. This will ask user to update fields at the time of opening the docx file, this is because we have set updateFields value to true in our 'settings.xml' file. Now save 'settings.xml' and update the zip file (if asked). Rename zip file back to '.docx'. Generate docx file now, it will auto update all the fields.

Shashank
  • 56
  • 8
  • 1
    Did you have a question? Maybe this was intended for the Documentation portion of this site? – Andrew Mortimer Aug 09 '16 at 07:09
  • Yes, but stackoverflow did not allow me to post a new document about docxtemplater as the tags are less. – Shashank Aug 09 '16 at 07:41
  • I will move this to Document(Beta) once reviewed, Thanks! – Shashank Aug 09 '16 at 07:49
  • 1
    Thanks for this technique! However, I've seen that it will always ask the user to update fields, every time the document is opened. Is there a way to avoid this? – Guillermo Grau Feb 16 '19 at 07:23
  • Not sure of that. For some security reasons, Microsoft Word team has set it as a user's choice. But there may be some way to pass through it. – Shashank Feb 17 '19 at 16:56

0 Answers0