Як форматувати текст у .NET
Aspose.Slides FOSS for .NET provides fine-grained text formatting through the PortionFormat клас. A Portion є найменшою незалежною одиницею тексту; вона відповідає одному запуску форматування в межах абзацу. У цьому посібнику показано, як застосовувати жирний, курсив, розмір шрифту та кольорове форматування до тексту у презентації.
Покроковий посібник
Крок 1: Встановіть пакет
dotnet add package Aspose.Slides.FossКрок 2: Додайте форму з текстовим кадром
Перш ніж форматувати текст, форма повинна містити TextFrame. Використовуйте shape.AddTextFrame() щоб створити його.
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);Крок 3: Отримайте доступ до TextFrame
shape.AddTextFrame() повертає TextFrame об’єкт. Ви також можете отримати його пізніше за допомогою shape.TextFrame.
var tf = shape.TextFrame; // if the frame already exists
var tf = shape.AddTextFrame(""); // creates a new frameA TextFrame містить список Paragraph об’єктів (tf.Paragraphs) Paragraph містить Portion об’єктів (paragraph.Portions).
Крок 4: Застосуйте жирний та курсивний формат
Використовуйте PortionFormat.FontBold і PortionFormat.FontItalic. Ці властивості приймають NullableBool.True, NullableBool.False, або NullableBool.NotDefined (успадковується від 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);Крок 5: Встановіть розмір шрифту та колір
Встановити PortionFormat.FontHeight для розміру (у пунктах) і використовуйте FillFormat для кольору.
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) приймає значення 0-255 для кожного каналу.
Крок 6: Кілька частин в одному абзаці
Один абзац може містити кілька частин з різним форматуванням. Додайте новий Portion до абзацу’s Portions колекція:
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);Типові проблеми та їх вирішення
Текст залишається чорним, навіть після встановлення кольору
Переконайтеся FillFormat.FillType = FillType.Solid встановлено перед призначенням кольору. Без встановлення типу заповнення зміна кольору може не мати ефекту.
NullableBool.True проти true
PortionFormat.FontBold очікує NullableBool.True, а не C# true. Присвоєння C# true не скомпілюється, оскільки типи несумісні.
Шрифт не з’являється у збереженому файлі
The LatinFont властивість встановлює сімейство латинських шрифтів. Якщо не встановлено, використовується шрифт теми презентації. Користувацькі шрифти мають бути вбудовані або доступні на машині перегляду.
Часті запитання
Як змінити сімейство шрифту?
Встановити PortionFormat.LatinFont:
fmt.LatinFont = new FontData("Arial");FontData приймає назву сімейства шрифтів у вигляді рядка.
Як встановити вирівнювання абзацу?
Використовувати ParagraphFormat.Alignment:
tf.Paragraphs[0].ParagraphFormat.Alignment = TextAlignment.Center;Підтримувані значення: Left, Center, Right, Justify.
Як встановити міжрядковий інтервал?
Використовувати ParagraphFormat.SpaceBefore (точки перед абзацом) або ParagraphFormat.SpaceAfter (точки після абзацу):
tf.Paragraphs[0].ParagraphFormat.SpaceBefore = 12; // 12pt before
tf.Paragraphs[0].ParagraphFormat.SpaceAfter = 6; // 6pt after