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

时间:2018-06-24 16:08:25

标签: .net aspose aspose.words

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

        Document rtfFile = new Document(@"C:\Tools\docwithTextBox.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:\Tools\docwithTextBox.rtf");

以上方法使我面临以下问题:

  1. 未将表添加到相应文本框的位置。尽管我正在调用builder.MoveTo(),但新表的left值与文本框的值不匹配。

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

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

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

谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码将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一起担任开发人员推广人员。

相关问题