【问题标题】:Apsose .Net - Replace all text boxes in my rtf document with tablesAspose .Net - 用表格替换我的 rtf 文档中的所有文本框
【发布时间】:2018-06-24 16:08:25
【问题描述】:

我想用表格替换我的 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) 输入 RTF 文件 2) Aspose.Words 18.6 生成的输出文件显示不希望的行为,3) 显示正确输出的预期文档(您可以使用 MS Word 创建预期文档) 和 4) 简单的控制台应用程序(没有编译错误的源代码)到 Dropbox 并在此处共享下载链接以进行测试。我与 Aspose 一起担任开发人员宣传员。
  • 我们正在检查这种情况,很快就会回复您。
  • 对于“nonNestedTexBox.rtf”文档,您可以在this code 上构建以满足您的要求。

标签: .net aspose aspose.words


【解决方案1】:

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

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 合作,担任开发人员宣传员。

【讨论】:

    猜你喜欢
    • 2013-09-25
    • 2015-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-25
    • 2018-04-04
    相关资源
    最近更新 更多