Cómo formatear texto en .NET

Cómo formatear texto en .NET

Aspose.Slides FOSS for .NET proporciona un formato de texto de gran precisión a través de la clase PortionFormat. Un 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.Foss

Paso 2: Añadir una forma con un marco de texto

Antes de formatear texto, una forma debe contener un TextFrame. Use 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 objeto TextFrame. 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 frame

Un TextFrame contiene una lista de objetos Paragraph (tf.Paragraphs). Cada Paragraph contiene objetos Portion (paragraph.Portions).


Paso 4: Aplicar formato en negrita y cursiva

Utilice PortionFormat.FontBold y PortionFormat.FontItalic. Estas propiedades aceptan NullableBool.True, NullableBool.False o NullableBool.NotDefined (heredan del 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);

Paso 5: Establecer tamaño y color de fuente

Establezca PortionFormat.FontHeight para el tamaño (en puntos) y use FillFormat para el 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 de 0 a 255 para cada canal.


Paso 6: Múltiples porciones en un párrafo

Un solo párrafo puede contener múltiples porciones con diferente formato. Añade un nuevo Portion a la colección Portions de un párrafo:

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úrese de que FillFormat.FillType = FillType.Solid esté configurado 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

La propiedad LatinFont establece la familia de fuentes latinas. 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 tipográfica?

Establecer PortionFormat.LatinFont:

fmt.LatinFont = new FontData("Arial");

FontData acepta el nombre de la familia tipográfica como una cadena.

¿Cómo configuro la alineación del párrafo?

Utilice ParagraphFormat.Alignment:

tf.Paragraphs[0].ParagraphFormat.Alignment = TextAlignment.Center;

Valores admitidos: Left, Center, Right, Justify.

¿Cómo configuro el interlineado?

Utilice 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

Ver también

 Español