How can I get all the text from a document, with the fields showing up as in the original document.
(ex: “{MACROBUTTON NoMacro F11}”)
How can I get all the text from a document, with the fields showing up as in the original document.
(ex: “{MACROBUTTON NoMacro F11}”)
Hi
Thanks for your request. Please try using the following simple code as example:
var doc = new Document(@"C:\Temp\in.doc");
var showFieldCode = new ShowFieldCode();
doc.Accept(showFieldCode);
Console.WriteLine(doc.ToTxt());
class ShowFieldCode: DocumentVisitor
{
public override VisitorAction VisitFieldStart(Aspose.Words.Fields.FieldStart fieldStart)
{
if (fieldStart.FieldType == Aspose.Words.Fields.FieldType.FieldMacroButton)
fieldStart.Remove();
return VisitorAction.Continue;
}
public override VisitorAction VisitFieldSeparator(Aspose.Words.Fields.FieldSeparator fieldSeparator)
{
if (fieldSeparator.FieldType == Aspose.Words.Fields.FieldType.FieldMacroButton)
fieldSeparator.Remove();
return VisitorAction.Continue;
}
public override VisitorAction VisitFieldEnd(Aspose.Words.Fields.FieldEnd fieldEnd)
{
if (fieldEnd.FieldType == Aspose.Words.Fields.FieldType.FieldMacroButton)
fieldEnd.Remove();
return VisitorAction.Continue;
}
}
Hope this helps.
Best regards,
Or you can try retrieving the field code using the following way:
var doc = new Document(@"C:\Temp\in.doc");
Node[] nodes = doc.GetChildNodes(NodeType.FieldStart, true).ToArray();
foreach (FieldStart node in nodes)
{
Console.WriteLine(GetFieldCode(node));
}
private static string GetFieldCode(Aspose.Words.Fields.FieldStart fieldStart)
{
var builder = new StringBuilder();
for (Node node = fieldStart; node != null && node.NodeType != NodeType.FieldSeparator && node.NodeType != NodeType.FieldEnd; node = node.NextPreOrder(node.Document))
{
// Use the text only of Run nodes to avoid duplication.
if (node.NodeType == NodeType.Run)
builder.Append(node.GetText());
}
return builder.ToString();
}
Best regards,
Thank you very much. This looks like exactly what I’m looking for. I will tweak it a bit to do exactly what I need.