Como formatar texto em .NET
Aspose.Slides FOSS for .NET provides fine-grained text formatting through the PortionFormat classe. A Portion é a menor unidade independente de texto; 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: Instale o pacote
dotnet add package Aspose.Slides.FossEtapa 2: Adicionar uma Forma com um Quadro de Texto
Antes de formatar o texto, uma forma deve conter um TextFrame. Use shape.AddTextFrame() para criar um.
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 TextFrame objeto. 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 Paragraph objetos (tf.Paragraphs). Cada Paragraph contém Portion objetos (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 (herdar 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);Etapa 5: Definir Tamanho da Fonte e Cor
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 0-255 para cada canal.
Etapa 6: Múltiplas Porções em um Único Parágrafo
Um único parágrafo pode conter várias partes com formatação diferente. Adicione um novo Portion para a Portions coleção:
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 correções
O texto aparece preto mesmo após definir a cor
Certifique‑se FillFormat.FillType = FillType.Solid é definido antes de atribuir a cor. Sem definir o tipo de preenchimento, a mudança de cor pode não ter efeito.
NullableBool.True vs true
PortionFormat.FontBold espera NullableBool.True, não o C# true. Atribuindo C# true não compilará porque os tipos são incompatíveis.
A fonte não aparece no arquivo salvo
O LatinFont a propriedade define a família de fontes Latin. Se não for definida, a fonte do tema da apresentação será usada. Fontes personalizadas devem estar incorporadas ou 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 defino o alinhamento do parágrafo?
Usar ParagraphFormat.Alignment:
tf.Paragraphs[0].ParagraphFormat.Alignment = TextAlignment.Center;Valores suportados: Left, Center, Right, Justify.
Como defino o espaçamento entre linhas?
Usar 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