Hello,
Aspose Word offers me to target a document.Range.Formfields (which I name old form fields) and StructuredDocumentTag (which I name new control form fields).
My use case is that I load a word document, search all fields and replace the content of such fields (text only). I implemented a method that does the job regarding existing documentation. In the documentation there is a .RemoveAllChildren() method that removes everything and after I add new child with my text.
My problem: I loose all format layouts (font, size, color, etc.).
My workaround at the moment is to defined those stuff outside of the control which do not work all the time (it is not handy to create a word document like this, many user fail to build their own working tempaltes).
So what I need:
I just want to replace content and keep all other layouts information.
—
My current code for this (which needs to be enhanced):
public void SetFormFieldValue(string name, string value)
{
if (_document == null) return;
// content controls
foreach (StructuredDocumentTag sdt in _document.GetChildNodes(NodeType.StructuredDocumentTag, true))
{
if (sdt.Tag != name || sdt.SdtType != SdtType.PlainText) continue;
try
{
if (sdt.FirstChild != null)
{
if (sdt.FirstChild.NodeType == NodeType.Cell)
{
var para = new Paragraph(_document);
var run = new Run(_document, value);
para.AppendChild(run);
var cell = (Cell)sdt.FirstChild;
cell.RemoveAllChildren();
cell.AppendChild(para);
}
if (sdt.FirstChild.NodeType == NodeType.Paragraph)
{
sdt.RemoveAllChildren();
var run = new Run(_document, value);
var para = new Paragraph(_document);
para.AppendChild(run);
sdt.AppendChild(para);
}
if (sdt.FirstChild.NodeType == NodeType.Run)
{
sdt.RemoveAllChildren();
var run = new Run(_document, value);
sdt.AppendChild(run);
}
}
else
{
if (sdt.Level == MarkupLevel.Block)
{
sdt.RemoveAllChildren();
var run = new Run(_document, value);
var para = new Paragraph(_document);
para.AppendChild(run);
sdt.AppendChild(para);
}
else
{
sdt.RemoveAllChildren();
var run = new Run(_document, value);
sdt.AppendChild(run);
}
}
}
catch (Exception ex)
{
_logger.ToLog(ex.ToString(), Company, "", Logfile);
}
}
// ActiveX controls
var documentFormFields = _document.Range.FormFields;
var count = documentFormFields.Count;
for (var i = 0; i < count; i++)
{
if (documentFormFields[i].Name == name)
documentFormFields[i].SetTextInputValue(value);
}
}