2

我的文档有 DOCPROPERTY 字段,我正在尝试更新它们(标题、子标题等)。

Dim title As String = "New Title"
Dim subTitle As String = "New Sub Title"
Dim document = DocumentModel.Load(inputFile)

document.DocumentProperties.BuiltIn(BuiltInDocumentProperty.Title) = title
document.DocumentProperties.Custom("SubTitle") = subTitle

document.Save(outputFile)

但是最终文档没有显示更新的值,我只能在 MS Word 中按 F9 刷新它们后才能看到它们。如何使用 GemBox.Document 刷新它们?

我还有一些用宏更新的 DOCVARIABLE 字段。我可以用 GemBox.Document 更新它们吗?

4

1 回答 1

2

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 进行更新。

于 2017-09-26T07:42:42.483 回答