Cómo dar formato al texto en .NET
Aspose.Slides FOSS for .NET provides fine-grained text formatting through the PortionFormat clase. A Portion es la unidad independiente más pequeña de texto; se corresponde con una única ejecución de formato dentro de un párrafo. Esta guía muestra cómo aplicar formato en negrita, cursiva, tamaño de fuente y color al texto en una presentación.
Guía paso a paso
Paso 1: Instalar el paquete
dotnet add package Aspose.Slides.FossPaso 2: Añadir una forma con un marco de texto
Antes de formatear el texto, una forma debe contener un TextFrame. Utilice shape.AddTextFrame() para crear una.
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);Paso 3: Acceder al TextFrame
shape.AddTextFrame() devuelve el TextFrame objeto. También puedes recuperarlo más tarde mediante shape.TextFrame.
var tf = shape.TextFrame; // if the frame already exists
var tf = shape.AddTextFrame(""); // creates a new frameUna TextFrame contiene una lista de Paragraph objetos (tf.Paragraphs). Cada Paragraph contiene Portion objetos (paragraph.Portions).
Paso 4: Aplicar formato de negrita y cursiva
Usar PortionFormat.FontBold y PortionFormat.FontItalic. Estas propiedades aceptan NullableBool.True, NullableBool.False, o NullableBool.NotDefined (heredar del maestro).
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);Paso 5: Establecer tamaño de fuente y color
Establecer PortionFormat.FontHeight para tamaño (en puntos) y usar FillFormat para color.
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) acepta valores 0-255 para cada canal.
Paso 6: Múltiples porciones en un mismo párrafo
Un solo párrafo puede contener múltiples porciones con diferente formato. Añade un nuevo Portion a la Portions colección:
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 comunes y soluciones
El texto aparece negro incluso después de establecer el color
Asegúrate FillFormat.FillType = FillType.Solid se establece antes de asignar el color. Sin establecer el tipo de relleno, el cambio de color puede no tener efecto.
NullableBool.True vs true
PortionFormat.FontBold espera NullableBool.True, no el C# true. Asignar C# true no compilará porque los tipos son incompatibles.
La fuente no aparece en el archivo guardado
El LatinFont La propiedad establece la familia de fuentes Latin. Si no se establece, se utiliza la fuente del tema de la presentación. Las fuentes personalizadas deben estar incrustadas o disponibles en la máquina de visualización.
Preguntas frecuentes
¿Cómo cambio la familia de fuentes?
Establecer PortionFormat.LatinFont:
fmt.LatinFont = new FontData("Arial");FontData acepta el nombre de la familia de fuentes como una cadena.
¿Cómo establezco la alineación del párrafo?
Usar ParagraphFormat.Alignment:
tf.Paragraphs[0].ParagraphFormat.Alignment = TextAlignment.Center;Valores admitidos: Left, Center, Right, Justify.
¿Cómo configuro el espaciado de líneas?
Usar ParagraphFormat.SpaceBefore (puntos antes del párrafo) o ParagraphFormat.SpaceAfter (puntos después del párrafo):
tf.Paragraphs[0].ParagraphFormat.SpaceBefore = 12; // 12pt before
tf.Paragraphs[0].ParagraphFormat.SpaceAfter = 6; // 6pt after