cognidox / OfficeToPDF

A command line tool to convert Microsoft Office documents to PDFs
https://www.cognidox.com/
Other
610 stars 137 forks source link

Prevent Word field updates #30

Open ptar opened 5 years ago

ptar commented 5 years ago

Word (up to 2016) sometimes(?) ignores the option about not updating fields, which is an unchecked Display->Update fields before printing (and misled a long time by missing some text in Advanced->Print->Allow fields containing tracked changes to update before printing)

The option /word_no_field_update doesn't prevent the field update, but it's absence urges OfficeToPDF to update the fields explicitly.

So, currently it's impossible to prevent the field update at all. The only solution is to unlink all fields, before they could be updated.

There could be a new option /word_prevent_field_updates, which does the same as UpdateDocumentFields but instead of updating the fields it unlinks them. (Hint: It's use should be combined with /readonly!)

A workaround with AutoOpen-VBA code to unlink the fields looks like this:

Attribute VB_Name = "UnlinkFields"
' NOTE: If macros are deactivated, this module needs to be saved in the Normal.dotm!
' (c) ptar, 2018

' On opening a document, all fields are replaced by their text value (AKA 'unlinked)
' This way, they can't be updated during printing
Sub AutoOpen()
    unlinkFields
End Sub

' Replace all fields by their text value
Public Sub unlinkFields()

    ' Word-BUG: ActiveDocument.Fields gives 0, if there are no fields in Main, but e.g. only in the Header :-(
    ' That is, we have to search all StoryRanges on our own...

    Application.ScreenUpdating = False

    On Error Resume Next

    Dim storyRange As Range
    For Each storyRange In ActiveDocument.StoryRanges
        If (storyRange.Fields.Count > 0) Then
            For Each fld In storyRange.Fields
                fld.Unlink
            Next
        End If
    Next
End Sub

Please consider to integrate this as a new option in OfficeToPDF. Thanks!