文本框

在 Aspose.Slides 中,文本框AutoShape 表示。几乎任何形状都可以包含文本,但典型的文本框没有填充或边框,仅显示文本。

本指南说明如何以编程方式添加、访问和删除文本框。

添加文本框

文本框就是一个没有填充和边框且带有一些格式化文本的 AutoShape。以下是创建方法:

public static void Add_TextBox()
{
    using var pres = new Presentation();

    // Create a rectangle shape (defaults to filled with border and no text)
    var textBox = pres.Slides[0].Shapes.AddAutoShape(ShapeType.Rectangle, x: 50, y: 75, width: 150, height: 100);

    // Remove fill and border to make it look like a typical text box
    textBox.FillFormat.FillType = FillType.NoFill;
    textBox.LineFormat.FillFormat.FillType = FillType.NoFill;

    // Set text formatting
    textBox.TextFrame.Paragraphs[0].ParagraphFormat.DefaultPortionFormat.FillFormat.FillType = FillType.Solid;
    textBox.TextFrame.Paragraphs[0].ParagraphFormat.DefaultPortionFormat.FillFormat.SolidFillColor.Color = Color.Black;

    // Assign the actual text content
    textBox.TextFrame.Text = "Some text...";
}

💡 注意: 任何包含非空 TextFrameAutoShape 都可以充当文本框。

按内容访问文本框

要查找所有包含特定关键字(例如 “Slide”)的文本框,可遍历形状并检查其文本:

public static void Access_TextBox()
{
    using var pres = new Presentation();

    foreach (var shape in pres.Slides[0].Shapes)
    {
        // Only AutoShapes can contain editable text
        if (shape is AutoShape autoShape)
        {
            if (autoShape.TextFrame.Text.Contains("Slide"))
            {
                // Do something with the matching text box
            }
        }
    }
}

按内容删除文本框

此示例查找并删除第一张幻灯片上所有包含特定关键字的文本框:

public static void Remove_TextBox()
{
    using var pres = new Presentation();

    var shapesToRemove = pres.Slides[0].Shapes
        .Where(s => s is AutoShape autoShape && autoShape.TextFrame.Text.Contains("Slide"))
        .ToList();

    shapesToRemove.ForEach(shape => pres.Slides[0].Shapes.Remove(shape));
}

💡 提示: 在遍历时修改形状集合前,请始终先创建该集合的副本,以避免集合修改错误。