C# Slide Element Tutorial – IronPPT
IronPPT é uma biblioteca robusta para PowerPoint, projetada para ajudar desenvolvedores .NET C# a integrar facilmente a capacidade de criar, ler e editar apresentações do PowerPoint em seus aplicativos. No contexto de uma apresentação em PowerPoint, os slides são os elementos fundamentais que estruturam e organizam o conteúdo.
Início rápido: Inserir texto em um slide novo ou existente
Este exemplo mostra como é fácil adicionar texto a um slide com o IronPPT. Em apenas algumas linhas, insira o conteúdo no primeiro slide, se ele já existir, ou crie um novo e salve — configuração rápida e sem complicações.
-
Instale IronPPT com o Gerenciador de Pacotes NuGet
PM > Install-Package IronPPT -
Copie e execute este trecho de código.
var doc = new IronPPT.PresentationDocument(); var text = doc.Slides.Count > 0 ? doc.Slides[0].AddText("Quick Option") : doc.Slides.Add(new IronPPT.Models.Slide()).AddText("Quick Option"); doc.Save("quick.pptx"); -
Implante para testar em seu ambiente de produção.
Comece a usar IronPPT em seu projeto hoje com uma avaliação gratuita
Índice
- Adicionar texto
- Conteúdo de texto (Adicionar, Anexar e Remover)
- Definir estilo (família e tamanho da fonte, cor, negrito e itálico, tachado, sublinhado)
- Adicionar imagem
- Carregar imagem (arquivo e fluxo de arquivo)
- Definir dimensões e ângulo (largura e altura)
- Definir posição
- Adicionar Forma
Adicionar texto
Conteúdo do texto
Seja para criar uma nova apresentação ou editar uma já existente, as ferramentas de gerenciamento de texto oferecem controle total sobre o posicionamento e a formatação do texto, permitindo que você crie slides que transmitam sua mensagem de forma clara e profissional.
:path=/static-assets/ppt/content-code-examples/tutorials/slide-element-add-text.cs
using IronPPT;
using IronPPT.Models;
// Create a new PowerPoint presentation
var document = new PresentationDocument();
// Ensure there is at least one slide to work with
if (document.Slides.Count == 0)
{
document.Slides.Add(new Slide());
}
// Add text to the first slide
var text = document.Slides[0].AddText("Hello");
// Append text to the existing text on the slide
text.Content += " There!";
// Check if there is any text element to remove from the first slide
if (document.Slides[0].Texts.Count > 0)
{
document.Slides[0].Texts[0].Remove();
}
// Export the PowerPoint presentation with the specified file name
document.Save("addText.pptx");
Imports IronPPT
Imports IronPPT.Models
' Create a new PowerPoint presentation
Private document = New PresentationDocument()
' Ensure there is at least one slide to work with
If document.Slides.Count = 0 Then
document.Slides.Add(New Slide())
End If
' Add text to the first slide
Dim text = document.Slides(0).AddText("Hello")
' Append text to the existing text on the slide
text.Content &= " There!"
' Check if there is any text element to remove from the first slide
If document.Slides(0).Texts.Count > 0 Then
document.Slides(0).Texts(0).Remove()
End If
' Export the PowerPoint presentation with the specified file name
document.Save("addText.pptx")
Estilização de Conjunto
A formatação de texto permite personalizar sua aparência visual definindo atributos como tamanho da fonte, cor, estilo, tachado e sublinhado. Aplicar esses estilos aprimora a apresentação do texto e melhora a aparência geral do documento.
:path=/static-assets/ppt/content-code-examples/tutorials/slide-element-text-style.cs
using IronPPT;
using IronPPT.Models; // Ensure the library is available
// Create a new presentation document
var document = new PresentationDocument();
// Define and customize the text style
var textStyle = new TextStyle
{
IsBold = true, // Text is bold
IsItalic = true, // Text is italic
Color = Color.Blue, // Text color is blue
Strike = StrikeValue.SingleStrike, // Text is single struck-off
Outline = true, // Text has an outline
NoProof = true, // Disables proofing for the text
Spacing = 10.0, // Text spacing is set to 10
Underline = new Underline
{
LineValue = UnderlineValues.Single, // Single underline
Color = Color.Red // Underline color is red
},
Languages = "en-US", // Text language is set to U.S. English
SpecVanish = false, // Text does not vanish when special formatting is applied
};
// Create text content and apply the defined style
var text = new Text("Hello World"); // Instantiate text with a string
text.TextStyle = textStyle; // Apply the defined style to the text
// Add a new slide if none exist
if (document.Slides.Count == 0)
{
document.Slides.Add(new Slide()); // Add a new slide to the document
}
// Add the styled text to the first slide
document.Slides[0].AddText(text); // Add the newly created text object to the first slide
// Save the presentation document to a file
document.Save("textStyle.pptx"); // Save the document with the filename "textStyle.pptx"
Imports IronPPT
Imports IronPPT.Models ' Ensure the library is available
' Create a new presentation document
Private document = New PresentationDocument()
' Define and customize the text style
Private textStyle = New TextStyle With {
.IsBold = True,
.IsItalic = True,
.Color = Color.Blue,
.Strike = StrikeValue.SingleStrike,
.Outline = True,
.NoProof = True,
.Spacing = 10.0,
.Underline = New Underline With {
.LineValue = UnderlineValues.Single,
.Color = Color.Red
},
.Languages = "en-US",
.SpecVanish = False
}
' Create text content and apply the defined style
Private text = New Text("Hello World") ' Instantiate text with a string
text.TextStyle = textStyle ' Apply the defined style to the text
' Add a new slide if none exist
If document.Slides.Count = 0 Then
document.Slides.Add(New Slide()) ' Add a new slide to the document
End If
' Add the styled text to the first slide
document.Slides(0).AddText(text) ' Add the newly created text object to the first slide
' Save the presentation document to a file
document.Save("textStyle.pptx") ' Save the document with the filename "textStyle.pptx"
Adicionar imagens
Ajuste as configurações de imagem para obter a melhor visualização. Uma configuração adequada garante que as imagens sejam visualmente atraentes e apropriadas ao seu contexto.
:path=/static-assets/ppt/content-code-examples/tutorials/slide-element-add-image.cs
using IronPPT;
using IronPPT.Models;
using System.Drawing;
// This script demonstrates the creation of a PowerPoint presentation using the IronPPT library.
// An image is added to the presentation, its properties are modified, and then the presentation is saved.
// Create a new PowerPoint presentation
var document = new PresentationDocument();
// Create a new Image object and load an image file.
var image = new Image();
image.LoadFromFile("sample.png");
// Add the image to the first slide (index 0) of the presentation.
var newImage = document.AddImage(image, 0);
// Set the properties of the added image.
// Position property is set using a Point object, which holds X and Y coordinates.
newImage.Position = new Point(200, 200); // Set image position on the slide
newImage.Angle = 45; // Set the rotation angle of the image
newImage.Name = "new image"; // Assign a descriptive name to the image
newImage.Width = 150; // Set the width of the image in pixels
newImage.Height = 150; // Set the height of the image in pixels
// Export the PowerPoint presentation to a file named "addImage.pptx"
document.Save("addImage.pptx");
Imports IronPPT
Imports IronPPT.Models
Imports System.Drawing
' This script demonstrates the creation of a PowerPoint presentation using the IronPPT library.
' An image is added to the presentation, its properties are modified, and then the presentation is saved.
' Create a new PowerPoint presentation
Private document = New PresentationDocument()
' Create a new Image object and load an image file.
Private image = New Image()
image.LoadFromFile("sample.png")
' Add the image to the first slide (index 0) of the presentation.
Dim newImage = document.AddImage(image, 0)
' Set the properties of the added image.
' Position property is set using a Point object, which holds X and Y coordinates.
newImage.Position = New Point(200, 200) ' Set image position on the slide
newImage.Angle = 45 ' Set the rotation angle of the image
newImage.Name = "new image" ' Assign a descriptive name to the image
newImage.Width = 150 ' Set the width of the image in pixels
newImage.Height = 150 ' Set the height of the image in pixels
' Export the PowerPoint presentation to a file named "addImage.pptx"
document.Save("addImage.pptx")
Adicionar Formas
Adicione e personalize formas facilmente em sua apresentação, definindo o tipo, as dimensões (largura e altura), as cores de preenchimento e contorno e a posição no slide.
:path=/static-assets/ppt/content-code-examples/tutorials/slide-element-add-shape.cs
using IronPPT;
using IronPPT.Models;
using IronPPT.Enums;
// Load a PowerPoint presentation.
// The PresentationDocument is assumed to represent an entire PPTX file loaded from disk.
var document = new PresentationDocument("output.pptx");
// Configure a new shape.
// Shape is assumed to be a model object representing drawable elements on a slide.
Shape shape = new Shape
{
Name = "triangle",
Type = ShapeType.Triangle,
Width = 100,
FillColor = new Color("#444444"),
OutlineColor = Color.Black,
// Position is set via assumed X and Y positioning properties.
// It's important that these properties are set to valid coordinates for display on the slide.
XPosition = 200,
YPosition = 200
};
// Add the shape to the first slide in the presentation.
// Slides[0] refers to the first slide in the collection. Ensure a slide exists at this index.
document.Slides[0].AddShape(shape);
// Export the modified PowerPoint presentation.
// Saves the changes to a new file, ensuring the original presentation is not overwritten.
document.Save("addShape.pptx");
Imports IronPPT
Imports IronPPT.Models
Imports IronPPT.Enums
' Load a PowerPoint presentation.
' The PresentationDocument is assumed to represent an entire PPTX file loaded from disk.
Private document = New PresentationDocument("output.pptx")
' Configure a new shape.
' Shape is assumed to be a model object representing drawable elements on a slide.
Private shape As New Shape With {
.Name = "triangle",
.Type = ShapeType.Triangle,
.Width = 100,
.FillColor = New Color("#444444"),
.OutlineColor = Color.Black,
.XPosition = 200,
.YPosition = 200
}
' Add the shape to the first slide in the presentation.
' Slides[0] refers to the first slide in the collection. Ensure a slide exists at this index.
document.Slides(0).AddShape(shape)
' Export the modified PowerPoint presentation.
' Saves the changes to a new file, ensuring the original presentation is not overwritten.
document.Save("addShape.pptx")
Perguntas frequentes
Para que é usado o IronPPT?
IronPPT é uma biblioteca completa do PowerPoint para desenvolvedores .NET C#, permitindo que eles criem, leiam e editem apresentações do PowerPoint dentro de suas aplicações.
Como adiciono texto a um slide usando IronPPT?
Para adicionar texto a um slide usando IronPPT, você pode simplesmente usar algumas linhas de código para inserir texto em um slide existente ou criar um novo, e então salvar a apresentação.
Posso personalizar a formatação do texto no IronPPT?
Sim, o IronPPT permite que você personalize a formatação do texto definindo atributos como tamanho da fonte, cor, estilo, tachado e sublinhado para melhorar a aparência do texto.
Como posso adicionar imagens a uma apresentação do PowerPoint com IronPPT?
IronPPT fornece ferramentas para carregar imagens de arquivos ou FileStreams, e configurar suas dimensões, ângulo e posição para garantir uma exibição ótima em suas apresentações.
É possível adicionar formas no IronPPT?
Sim, você pode adicionar e personalizar formas no IronPPT definindo seu tipo, dimensões, cores de preenchimento e contorno, e posição no slide.
O IronPPT suporta edição de apresentações do PowerPoint existentes?
IronPPT permite criar novas apresentações e editar as existentes, dando a você controle total sobre o conteúdo e formatação.
Posso definir a posição do texto e das imagens no IronPPT?
Sim, o IronPPT permite que você defina a posição do texto e das imagens nos slides, permitindo um posicionamento preciso para atender ao layout da sua apresentação.
Quais formatos de arquivo são suportados para inserção de imagens no IronPPT?
IronPPT suporta inserção de imagens de vários formatos de arquivo, garantindo compatibilidade com os recursos visuais da sua apresentação.
Como o IronPPT melhora o apelo visual da apresentação?
IronPPT melhora o apelo visual fornecendo ferramentas para personalizar formatação de texto, configurações de imagem e designs de formas, garantindo uma aparência profissional para a apresentação.
O IronPPT é compatível com diferentes versões do PowerPoint?
O IronPPT é projetado para ser compatível com várias versões do PowerPoint, permitindo integração perfeita em suas aplicações C#.

