officefileapi-15291-word-processing-document-api-fields-field-codes-docvariable.md
Mixed field
{ DOCVARIABLE “variable name” “argument1” “argument 2”… }
Inserts a string associated with a document variable.
The following members are used to obtain a DOCVARIABLE field value.
| Member | Description |
|---|---|
| Document.Variables | RichEditDocumentServer first searches this collection for a specified variable. |
| Document.CalculateDocumentVariable | If variable is not found in the collection, the RichEditDocumentServer raises this event so you can specify the value in code. |
When you append document content, the DOCVARIABLE field from the appended content is updated. Since a source for the field value no longer exists, the field result is empty. You can set CalculateDocumentVariableEventArgs.FieldLocked to true in the CalculateDocumentVariable event handler. As a result, the DOCVARIABLE field is locked and not updated.
If you don’t need the DOCVARIABLE field in the future, you can call the Unlink method to replace this field with its value before saving the document, as shown below:
//...
document.CalculateDocumentVariable += WordProcessor_CalculateDocumentVariable;
Document.UpdateAllFields();
document.Fields[0].Unlink();
wordProcessor.SaveDocument("../../../test.docx", DocumentFormat.Docx);
'...
document.CalculateDocumentVariable += WordProcessor_CalculateDocumentVariable
Document.UpdateAllFields()
document.Fields(0).Unlink()
wordProcessor.SaveDocument("../../../test.docx", DocumentFormat.Docx)
View Example: Use DOCVARIABLE Fields
This code snippet demonstrates how to handle the Document.CalculateDocumentVariable event to insert dynamic content into the document. In this example, it is used to get weather conditions. A variable name specified in the DOCVARIABLE indicates a choice between location and weather, while the location itself is specified by the field argument.
private static void Document_CalculateDocumentVariable(object sender, CalculateDocumentVariableEventArgs e) {
if (e.Arguments.Count > 0) {
string location = e.Arguments[0].Value.ToString();
if ((location.Trim() == String.Empty) || (location.Contains("<"))) {
e.Value = " ";
e.Handled = true;
return;
}
switch (e.VariableName) {
case "Weather":
Conditions conditions = new Conditions();
conditions = Weather.GetCurrentConditions(location);
e.Value = String.Format("Weather for {0}: \nConditions: {1}\nTemperature (C) :{2}\nHumidity: {3}\nWind: {4}\n",
location, conditions.Condition, conditions.TempC, conditions.Humidity, conditions.Wind);
break;
case "LOCATION":
if (location == "DO NOT CHANGE!") e.Value = DocVariableValue.Current;
break;
default:
e.Value = "LOCKED FIELD UPDATED";
break;
}
}
else {
e.Value = "LOCKED FIELD UPDATED";
}
e.Handled = true;
}
Private Shared Sub Document_CalculateDocumentVariable(ByVal sender As Object, ByVal e As CalculateDocumentVariableEventArgs)
If e.Arguments.Count > 0 Then
Dim location As String = e.Arguments(0).Value.ToString()
If (location.Trim() = String.Empty) OrElse (location.Contains("<")) Then
e.Value = " "
e.Handled = True
Return
End If
Select Case e.VariableName
Case "Weather"
Dim conditions As Conditions = New Conditions()
conditions = Weather.GetCurrentConditions(location)
e.Value = String.Format("Weather for {0}: " & vbLf & "Conditions: {1}" & vbLf & "Temperature (C) :{2}" & vbLf & "Humidity: {3}" & vbLf & "Wind: {4}" & vbLf, location, conditions.Condition, conditions.TempC, conditions.Humidity, conditions.Wind)
Case "LOCATION"
If location = "DO NOT CHANGE!" Then e.Value = DocVariableValue.Current
Case Else
e.Value = "LOCKED FIELD UPDATED"
End Select
Else
e.Value = "LOCKED FIELD UPDATED"
End If
e.Handled = True
End Sub
Note
Set the event arguments’ CalculateDocumentVariableEventArgs.Value property to the DocVariableValue.Current value in the CalculateDocumentVariable event handler to save the initial DOCVARIABLE field value.
Use the Document.UpdateDocVariablesBeforePrint or the FieldOptions.UpdateDocVariablesBeforePrint properties to specify whether to update the DOCVARIABLE fields before print or export to PDF.
You can set another document’s content as the DOCVARIABLE field value. Create another RichEditDocumentServer object, generate a document with the required document content (a shape, a table and so on), and assign the RichEditDocumentServer object as a DOCVARIABLE field value in the CalculateDocumentVariable event handler.
The code sample below shows how to handle the RichEditDocumentServer.CalculateDocumentVariable event to insert a barcode and a table:
using (var wordProcessor = new RichEditDocumentServer()) {
wordProcessor.CreateNewDocument();
Document document = wordProcessor.Document;
// Create fields for a barcode and a table:
document.Fields.Create(document.Range.End, "DOCVARIABLE QRCODE");
document.Paragraphs.Append();
document.Fields.Create(document.Range.End, "DOCVARIABLE TABLE");
wordProcessor.CalculateDocumentVariable += WordProcessor_CalculateDocumentVariable;
// Update all document fields:
document.UpdateAllFields();
// Save the result:
wordProcessor.SaveDocument("result.docx", DocumentFormat.Docx);
}
void WordProcessor_CalculateDocumentVariable(object sender, CalculateDocumentVariableEventArgs e) {
switch (e.VariableName) {
case "QRCODE":
// Create new RichEditDocumentServer instance:
var doc = new RichEditDocumentServer();
// Insert a barcode as a shape
Shape picture = doc.Document.Shapes.InsertPicture(doc.Document.Range.End, GenerateQrCode());
picture.TextWrapping = TextWrappingType.InLineWithText;
// Set the field value to the RichEditDocumentServer instance:
e.Value = doc;
e.Handled = true;
break;
case "TABLE":
// Create new RichEditDocumentServer instance:
var doc1 = new RichEditDocumentServer();
// Insert a table:
GenerateTable(doc1.Document);
// Set the field value to the RichEditDocumentServer instance:
e.Value = doc1;
e.Handled = true;
break;
}
}
// This method generates a barcode:
static Bitmap GenerateQrCode() {
BarCode barCode = new BarCode();
barCode.Symbology = Symbology.QRCode;
barCode.CodeText = "https://www.devexpress.com/";
barCode.BackColor = Color.White;
barCode.ForeColor = Color.Black;
barCode.RotationAngle = 0;
barCode.CodeBinaryData = Encoding.Default.GetBytes(barCode.CodeText);
barCode.Options.QRCode.CompactionMode = QRCodeCompactionMode.Byte;
barCode.Options.QRCode.ErrorLevel = QRCodeErrorLevel.Q;
barCode.Options.QRCode.ShowCodeText = false;
barCode.DpiX = 72;
barCode.DpiY = 72;
barCode.Module = 2f;
return barCode.BarCodeImage;
}
// This method generates a table:
static Table GenerateTable(Document document) {
Table table = document.Tables.Create(document.Range.Start, 3,3);
document.InsertSingleLineText(table.Rows[0].Cells[1].Range.Start, "Active Customers");
document.InsertSingleLineText(table[1, 0].Range.Start, "Photo");
document.InsertSingleLineText(table[1, 1].Range.Start, "Customer Info");
document.InsertSingleLineText(table[1, 2].Range.Start, "Rentals");
return table;
}
Using wordProcessor = New RichEditDocumentServer()
wordProcessor.CreateNewDocument()
Dim document As Document = wordProcessor.Document
document.Fields.Create(document.Range.End, "DOCVARIABLE QRCODE")
document.Paragraphs.Append()
document.Fields.Create(document.Range.End, "DOCVARIABLE TABLE")
wordProcessor.CalculateDocumentVariable += WordProcessor_CalculateDocumentVariable
document.UpdateAllFields()
wordProcessor.SaveDocument("result.docx", DocumentFormat.Docx)
End Using
Private Sub WordProcessor_CalculateDocumentVariable(ByVal sender As Object, ByVal e As CalculateDocumentVariableEventArgs)
Select Case e.VariableName
Case "QRCODE"
Dim doc = New RichEditDocumentServer()
Dim picture As Shape = doc.Document.Shapes.InsertPicture(doc.Document.Range.End, GenerateQrCode())
picture.TextWrapping = TextWrappingType.InLineWithText
e.Value = doc
e.Handled = True
Case "TABLE"
Dim doc1 = New RichEditDocumentServer()
GenerateTable(doc1.Document)
e.Value = doc1
e.Handled = True
End Select
End Sub
Shared Function GenerateQrCode() As Bitmap
Dim barCode As New BarCode()
barCode.Symbology = Symbology.QRCode
barCode.CodeText = "https://www.devexpress.com/"
barCode.BackColor = Color.White
barCode.ForeColor = Color.Black
barCode.RotationAngle = 0
barCode.CodeBinaryData = Encoding.Default.GetBytes(barCode.CodeText)
barCode.Options.QRCode.CompactionMode = QRCodeCompactionMode.Byte
barCode.Options.QRCode.ErrorLevel = QRCodeErrorLevel.Q
barCode.Options.QRCode.ShowCodeText = False
barCode.DpiX = 72
barCode.DpiY = 72
barCode.Module = 2F
Return barCode.BarCodeImage
End Function
Shared Function GenerateTable(ByVal document As Document) As Table
Dim table As Table = document.Tables.Create(document.Range.Start, 3,3)
document.InsertSingleLineText(table.Rows(0).Cells(1).Range.Start, "Active Customers")
document.InsertSingleLineText(table(1, 0).Range.Start, "Photo")
document.InsertSingleLineText(table(1, 1).Range.Start, "Customer Info")
document.InsertSingleLineText(table(1, 2).Range.Start, "Rentals")
Return table
End Function