Apsose .Net - 将我的 rtf 文档中的所有文本框替换为表格



我想用表格替换 rtf 文档中的所有文本框。文本框使用 MS Word 插入。我在 C# 中尝试了以下代码:

Document rtfFile = new Document(@"C:ToolsdocwithTextBox.rtf");
DocumentBuilder builder = new DocumentBuilder(rtfFile);
var nodes = rtfFile.GetChildNodes(NodeType.Shape, true);
foreach (Shape shape in nodes)
{
if (shape.ShapeType == ShapeType.TextBox)
{
var width = shape.Width;
var height = shape.Height;
string text = shape.GetText();
builder.MoveTo(shape);
shape.Remove();
Aspose.Words.Tables.Table table = builder.StartTable();
Cell cell = builder.InsertCell();
builder.Write(text);
builder.RowFormat.Height = height;
builder.RowFormat.HeightRule = HeightRule.Exactly;
table.PreferredWidth = PreferredWidth.FromPoints(width);
builder.EndRow();
builder.EndTable();
}
}
rtfFile.Save(@"C:ToolsdocwithTextBox.rtf");

上述方法面临以下问题:

  1. 表格不会添加到相应文本框的位置。虽然我调用builder.MoveTo()但新表的left值与文本框的值不匹配。

  2. 某些表的高度与相应shape(TextBox的高度不匹配。宽度得到正确保留。

  3. shape.GetText()方法返回的字符串不会保留格式。例如,即使文本框内的文本为粗体或斜体,shape.GetText()方法也会返回无格式文本。在插入表格之前,我们如何保留格式?

请让我知道如何解决此问题。任何帮助将不胜感激。

谢谢

您可以使用以下代码将 Word 文档中的文本框形状替换为表格:

Document doc = new Document("D:\Temp\files\Files\1\nonNestedTexBox.rtf");
DocumentBuilder builder = new DocumentBuilder(doc);
ArrayList list = new ArrayList();
foreach (Shape shape in doc.GetChildNodes(NodeType.Shape, true))
{
builder.MoveTo(shape.GetAncestor(NodeType.Paragraph));
Table tab = builder.StartTable();
Cell cell = builder.InsertCell();
cell.EnsureMinimum();
foreach (Node node in shape.ChildNodes)
{
cell.AppendChild(node);
}
cell.FirstParagraph.Remove();
builder.EndRow();
builder.EndTable();
tab.TextWrapping = TextWrapping.Around;
tab.LeftIndent = shape.Left + 10;
tab.FirstRow.FirstCell.CellFormat.Width = shape.Width;
tab.FirstRow.RowFormat.Height = shape.Height;
tab.AutoFit(AutoFitBehavior.FixedColumnWidths);
list.Add(shape);
}
foreach (Shape s in list)
{
s.Remove();
}
doc.Save("D:\Temp\files\Files\1\18.6.docx");

我作为开发人员布道者与Aspose合作。

最新更新