Como formatar texto em .NET
Aspose.Slides FOSS for .NET fornece formatação de texto granular por meio da classe PortionFormat. Um Portion é a menor unidade independente de texto; ele corresponde a uma única execução de formatação dentro de um parágrafo. Este guia mostra como aplicar formatação em negrito, itálico, tamanho de fonte e cor ao texto em uma apresentação.
Guia passo a passo
Etapa 1: Instalar o Pacote
dotnet add package Aspose.Slides.FossEtapa 2: Adicionar uma Forma com uma Caixa de Texto
Antes de formatar o texto, uma forma deve conter um TextFrame. Use shape.AddTextFrame() para criar uma.
using Aspose.Slides.Foss;
using Aspose.Slides.Foss.Export;
using var prs = new Presentation();
var slide = prs.Slides[0];
var shape = slide.Shapes.AddAutoShape(ShapeType.Rectangle, 50, 50, 500, 150);
var tf = shape.AddTextFrame("Default text: will be formatted");
prs.Save("output.pptx", SaveFormat.Pptx);Etapa 3: Acessar o TextFrame
shape.AddTextFrame() retorna o objeto TextFrame. Você também pode recuperá‑lo mais tarde via shape.TextFrame.
var tf = shape.TextFrame; // if the frame already exists
var tf = shape.AddTextFrame(""); // creates a new frameUm TextFrame contém uma lista de objetos Paragraph (tf.Paragraphs). Cada Paragraph contém objetos Portion (paragraph.Portions).
Etapa 4: Aplicar formatação em negrito e itálico
Use PortionFormat.FontBold e PortionFormat.FontItalic. Essas propriedades aceitam NullableBool.True, NullableBool.False ou NullableBool.NotDefined (herda do master).
using Aspose.Slides.Foss;
using Aspose.Slides.Foss.Export;
using var prs = new Presentation();
var slide = prs.Slides[0];
var shape = slide.Shapes.AddAutoShape(ShapeType.Rectangle, 50, 50, 500, 150);
var tf = shape.AddTextFrame("Bold and italic text");
var fmt = tf.Paragraphs[0].Portions[0].PortionFormat;
fmt.FontBold = NullableBool.True;
fmt.FontItalic = NullableBool.True;
prs.Save("bold-italic.pptx", SaveFormat.Pptx);Passo 5: Definir Tamanho e Cor da Fonte
Defina PortionFormat.FontHeight para tamanho (em pontos) e use FillFormat para cor.
using Aspose.Slides.Foss;
using Aspose.Slides.Foss.Drawing;
using Aspose.Slides.Foss.Export;
using var prs = new Presentation();
var slide = prs.Slides[0];
var shape = slide.Shapes.AddAutoShape(ShapeType.Rectangle, 50, 50, 500, 150);
var tf = shape.AddTextFrame("Large corporate-blue heading");
var fmt = tf.Paragraphs[0].Portions[0].PortionFormat;
fmt.FontHeight = 32; // 32pt font
fmt.FontBold = NullableBool.True;
fmt.FillFormat.FillType = FillType.Solid;
fmt.FillFormat.SolidFillColor.Color = Color.FromArgb(255, 0, 70, 127);
prs.Save("colored-text.pptx", SaveFormat.Pptx);Color.FromArgb(alpha, red, green, blue) aceita valores de 0 a 255 para cada canal.
Etapa 6: Várias Porções em Um Parágrafo
Um único parágrafo pode conter várias partes com formatação diferente. Adicione um novo Portion à coleção Portions de um parágrafo:
using Aspose.Slides.Foss;
using Aspose.Slides.Foss.Drawing;
using Aspose.Slides.Foss.Export;
using var prs = new Presentation();
var slide = prs.Slides[0];
var shape = slide.Shapes.AddAutoShape(ShapeType.Rectangle, 50, 50, 600, 100);
var tf = shape.AddTextFrame(""); // start with empty frame
var paragraph = tf.Paragraphs[0];
// First portion: normal text
var portion1 = paragraph.Portions[0];
portion1.Text = "Normal text followed by ";
portion1.PortionFormat.FontHeight = 20;
// Second portion: bold red text
var portion2 = new Portion();
portion2.Text = "bold red text";
portion2.PortionFormat.FontHeight = 20;
portion2.PortionFormat.FontBold = NullableBool.True;
portion2.PortionFormat.FillFormat.FillType = FillType.Solid;
portion2.PortionFormat.FillFormat.SolidFillColor.Color = Color.FromArgb(255, 200, 0, 0);
paragraph.Portions.Add(portion2);
prs.Save("mixed-format.pptx", SaveFormat.Pptx);Problemas Comuns e Soluções
Texto aparece preto mesmo após definir a cor
Certifique‑se de que FillFormat.FillType = FillType.Solid esteja definido antes de atribuir a cor. Sem definir o tipo de preenchimento, a alteração de cor pode não ter efeito.
NullableBool.True vs true
PortionFormat.FontBold espera NullableBool.True, não o C# true. Atribuir C# true não compilará porque os tipos são incompatíveis.
Fonte não aparece no arquivo salvo
A propriedade LatinFont define a família de fontes latinas. Se não for definida, a fonte do tema da apresentação será usada. Fontes personalizadas devem ser incorporadas ou estar disponíveis na máquina de visualização.
Perguntas Frequentes
Como altero a família de fontes?
Definir PortionFormat.LatinFont:
fmt.LatinFont = new FontData("Arial");FontData aceita o nome da família de fontes como uma string.
Como definir o alinhamento de parágrafo?
Use ParagraphFormat.Alignment:
tf.Paragraphs[0].ParagraphFormat.Alignment = TextAlignment.Center;Valores suportados: Left, Center, Right, Justify.
Como defino o espaçamento entre linhas?
Use ParagraphFormat.SpaceBefore (pontos antes do parágrafo) ou ParagraphFormat.SpaceAfter (pontos depois do parágrafo):
tf.Paragraphs[0].ParagraphFormat.SpaceBefore = 12; // 12pt before
tf.Paragraphs[0].ParagraphFormat.SpaceAfter = 6; // 6pt after