2020 年 2 月 1 日更新:
GemBox.Document 的当前最新错误修复版本引入了对 的 API 支持Field.Update
,因此从现在开始,可以将 DOCPROPERTY 和 DOCVARIABLE 字段的更新简化如下:
For Each field As Field In document.GetChildElements(True, ElementType.Field)
field.Update()
Next
2017 年 11 月 10 日更新:GemBox.Document
的当前最新错误修复版本引入了对 的 API 支持DocumentModel.Variables
,因此从现在开始可以更新自己的 DOCVARIABLE 字段,例如使用以下内容:
Dim variables As VariablesDictionary = document.Variables
For Each field As Field In document.GetChildElements(True, ElementType.Field).Cast(Of Field)().Where(Function(f) f.FieldType = FieldType.DocVariable)
Dim instruction As String = field.GetInstructionText()
Dim variableName As String = If(instruction.IndexOf(" "c) < 0, instruction, instruction.Remove(instruction.IndexOf(" "c)))
Dim value As String = Nothing
If variables.TryGetValue(variableName, value) Then
field.ResultInlines.Clear()
field.ResultInlines.Add(New Run(document, value) With {.CharacterFormat = field.CharacterFormat.Clone()})
End If
Next
原创:
GemBox.Document 在保存到 DOCX 文件时不会自动更新 DOCPROPERTY 字段。但是,它们会在保存为 PDF、XPS 或图像格式以及打印时更新。
不过,您可以使用以下内容更新它们:
Dim properties As DocumentProperties = document.DocumentProperties
For Each field As Field In document.GetChildElements(True, ElementType.Field).Cast(Of Field)().Where(Function(f) f.FieldType = FieldType.DocProperty)
Dim instruction As String = field.GetInstructionText()
Dim propertyName As String = If(instruction.IndexOf(" "c) < 0, instruction, instruction.Remove(instruction.IndexOf(" "c)))
Dim value As String = Nothing
Dim customValue As Object = Nothing
Dim buildInProperty As BuiltInDocumentProperty
If properties.Custom.TryGetValue(propertyName, customValue) Then
value = customValue.ToString()
ElseIf [Enum].TryParse(propertyName, buildInProperty) Then
properties.BuiltIn.TryGetValue(buildInProperty, value)
End If
If Not String.IsNullOrEmpty(value) Then
field.ResultInlines.Clear()
field.ResultInlines.Add(New Run(document, value) With {.CharacterFormat = field.CharacterFormat.Clone()})
End If
Next
此外,关于 DOCVARIABLE 字段,这些字段目前无法使用 GemBox.Document 进行更新。