Gestire i paragrafi di testo di PowerPoint in .NET

Panoramica

Aspose.Slides per .NET rappresenta il testo come una gerarchia di riquadri di testo, paragrafi e porzioni:

  • ITextFrame rappresenta il contenitore di testo in una forma e fornisce l’accesso alla sua collezione di paragrafi.
  • IParagraph rappresenta un paragrafo in un riquadro di testo e fornisce l’accesso alle sue porzioni e alla formattazione a livello di paragrafo.
  • IPortion rappresenta un blocco di testo all’interno di un paragrafo. Ogni porzione può avere il proprio testo e la formattazione a livello di carattere.

Un paragrafo può quindi contenere testo con caratteri, colori, dimensioni e altre formattazioni diverse usando più porzioni.

Creare e Formattare i Paragrafi

Crea paragrafi nel riquadro di testo di una forma e usa le porzioni per formattare blocchi di testo individuali. Questa sezione mostra come combinare più porzioni all’interno di ciascun paragrafo e applicare colori, dimensioni dei caratteri e stili diversi.

Creare Paragrafi con Più Porzioni

Il seguente esempio C# crea tre paragrafi, ciascuno contenente tre blocchi di testo nella sua collezione IParagraph.Portions. Riutilizza il paragrafo predefinito e la sua porzione vuota, quindi aggiunge i paragrafi e le porzioni rimanenti. La formattazione è applicata tramite IPortion.PortionFormat: la prima porzione di ciascun paragrafo è rossa, grassetto e 15 punti; la seconda è blu, corsivo e 18 punti. La terza porzione mantiene la formattazione predefinita:

using System.Drawing;
using Aspose.Slides;
using Aspose.Slides.Export;

using var presentation = new Presentation();
var slide = presentation.Slides[0];

var shape = slide.Shapes.AddAutoShape(ShapeType.Rectangle, 50, 150, 300, 150);
var textFrame = shape.TextFrame;

var firstParagraph = textFrame.Paragraphs[0];
firstParagraph.Portions.Add(new Portion());
firstParagraph.Portions.Add(new Portion());

var secondParagraph = new Paragraph();
secondParagraph.Portions.Add(new Portion());
secondParagraph.Portions.Add(new Portion());
secondParagraph.Portions.Add(new Portion());
textFrame.Paragraphs.Add(secondParagraph);

var thirdParagraph = new Paragraph();
thirdParagraph.Portions.Add(new Portion());
thirdParagraph.Portions.Add(new Portion());
thirdParagraph.Portions.Add(new Portion());
textFrame.Paragraphs.Add(thirdParagraph);

var paragraphCount = textFrame.Paragraphs.Count;
for (var paragraphIndex = 0; paragraphIndex < paragraphCount; paragraphIndex++)
{
    var paragragaph = textFrame.Paragraphs[paragraphIndex];
    var portionCount = paragragaph.Portions.Count;
    for (var portionIndex = 0; portionIndex < portionCount; portionIndex++)
    {
        var portion = paragragaph.Portions[portionIndex];
        portion.Text = $"Portion {paragraphIndex + 1}.{portionIndex + 1}";

        if (portionIndex == 0)
        {
            portion.PortionFormat.FillFormat.FillType = FillType.Solid;
            portion.PortionFormat.FillFormat.SolidFillColor.Color = Color.Red;
            portion.PortionFormat.FontBold = NullableBool.True;
            portion.PortionFormat.FontHeight = 15;
        }
        else if (portionIndex == 1)
        {
            portion.PortionFormat.FillFormat.FillType = FillType.Solid;
            portion.PortionFormat.FillFormat.SolidFillColor.Color = Color.Blue;
            portion.PortionFormat.FontItalic = NullableBool.True;
            portion.PortionFormat.FontHeight = 18;
        }
    }
}

presentation.Save("paragraphs_with_portions.pptx", SaveFormat.Pptx);

Creare Elenchi Puntati e Numerati

Organizza il testo dei paragrafi in elenchi con simboli, numeri o immagini personalizzate. Gli esempi in questa sezione coprono la formattazione dei puntatori, gli elenchi multilivello e i numeri di avvio personalizzati.

Creare un Elenco Puntato o Numerato

I puntatori e la numerazione rendono gli elementi correlati più facili da scorrere. In Aspose.Slides, le impostazioni dell’elenco sono definite tramite IBulletFormat.

Questo esempio C# aggiunge un puntatore a simbolo e un elemento numerato allo stesso riquadro di testo. IBulletFormat.Type seleziona il tipo di puntatore, mentre IBulletFormat.Char fornisce il simbolo e IBulletFormat.NumberedBulletStyle seleziona lo stile di numerazione. Entrambi gli elementi usano puntatori neri con un’altezza del 100 percento e un rientro del paragrafo di 25 punti:

using System;
using System.Drawing;
using Aspose.Slides;
using Aspose.Slides.Export;

using var presentation = new Presentation();
var slide = presentation.Slides[0];

var shape = slide.Shapes.AddAutoShape(ShapeType.Rectangle, 200, 200, 400, 200);
var textFrame = shape.TextFrame;
textFrame.Paragraphs.Clear();

var symbolParagraph = new Paragraph { Text = "Welcome to Aspose.Slides" };
symbolParagraph.ParagraphFormat.Bullet.Type = BulletType.Symbol;
symbolParagraph.ParagraphFormat.Bullet.Char = Convert.ToChar(0x2022);
symbolParagraph.ParagraphFormat.Indent = 25;
symbolParagraph.ParagraphFormat.Bullet.Color.ColorType = ColorType.RGB;
symbolParagraph.ParagraphFormat.Bullet.Color.Color = Color.Black;
symbolParagraph.ParagraphFormat.Bullet.IsBulletHardColor = NullableBool.True;
symbolParagraph.ParagraphFormat.Bullet.Height = 100;
textFrame.Paragraphs.Add(symbolParagraph);

var numberedParagraph = new Paragraph { Text = "This is a numbered item" };
numberedParagraph.ParagraphFormat.Bullet.Type = BulletType.Numbered;
numberedParagraph.ParagraphFormat.Bullet.NumberedBulletStyle = NumberedBulletStyle.BulletCircleNumWDBlackPlain;
numberedParagraph.ParagraphFormat.Indent = 25;
numberedParagraph.ParagraphFormat.Bullet.Color.ColorType = ColorType.RGB;
numberedParagraph.ParagraphFormat.Bullet.Color.Color = Color.Black;
numberedParagraph.ParagraphFormat.Bullet.IsBulletHardColor = NullableBool.True;
numberedParagraph.ParagraphFormat.Bullet.Height = 100;
textFrame.Paragraphs.Add(numberedParagraph);

presentation.Save("bulleted_and_numbered_list.pptx", SaveFormat.Pptx);

Usare Puntini con Immagine

I puntini con immagine consentono di usare un’immagine personalizzata al posto di un simbolo o di un numero.

Questo esempio C# aggiunge un’immagine alla collezione di immagini della presentazione come IPPImage e la usa come puntatore di paragrafo. Imposta IBulletFormat.Type per utilizzare un puntatore immagine e assegna l’immagine tramite IBulletFormat.Picture. IBulletFormat.Height è impostato al 100 percento per dimensionare il puntatore in relazione al testo del paragrafo:

using Aspose.Slides;
using Aspose.Slides.Export;

using var presentation = new Presentation();
var slide = presentation.Slides[0];

using var bulletImage = Images.FromFile("bullets.png");
var presentationImage = presentation.Images.AddImage(bulletImage);

var shape = slide.Shapes.AddAutoShape(ShapeType.Rectangle, 200, 200, 400, 200);
var textFrame = shape.TextFrame;
textFrame.Paragraphs.Clear();

var paragraph = new Paragraph { Text = "Welcome to Aspose.Slides" };
paragraph.ParagraphFormat.Bullet.Type = BulletType.Picture;
paragraph.ParagraphFormat.Bullet.Picture.Image = presentationImage;
paragraph.ParagraphFormat.Bullet.Height = 100;
textFrame.Paragraphs.Add(paragraph);

presentation.Save("picture_bullet.pptx", SaveFormat.Pptx);
presentation.Save("picture_bullet.ppt", SaveFormat.Ppt);

Creare un Elenco Multilivello

Imposta IParagraphFormat.Depth per posizionare i paragrafi a diversi livelli di un elenco. Il livello superiore ha una profondità di 0.

Questo esempio C# assegna valori IParagraphFormat.Depth da 0 a 3 a quattro paragrafi, creando una gerarchia all’interno di un singolo riquadro di testo. Ogni paragrafo usa un puntatore a simbolo, con IBulletFormat.Char alternato tra un puntatore rotondo e un trattino per distinguere i livelli adiacenti:

using System;
using System.Drawing;
using Aspose.Slides;
using Aspose.Slides.Export;

using var presentation = new Presentation();
var slide = presentation.Slides[0];

var shape = slide.Shapes.AddAutoShape(ShapeType.Rectangle, 200, 200, 400, 200);
var textFrame = shape.TextFrame;
textFrame.Paragraphs.Clear();

var firstParagraph = new Paragraph { Text = "Content" };
firstParagraph.ParagraphFormat.Bullet.Type = BulletType.Symbol;
firstParagraph.ParagraphFormat.Bullet.Char = Convert.ToChar(0x2022);
firstParagraph.ParagraphFormat.DefaultPortionFormat.FillFormat.FillType = FillType.Solid;
firstParagraph.ParagraphFormat.DefaultPortionFormat.FillFormat.SolidFillColor.Color = Color.Black;
firstParagraph.ParagraphFormat.Depth = 0;

var secondParagraph = new Paragraph { Text = "Second level" };
secondParagraph.ParagraphFormat.Bullet.Type = BulletType.Symbol;
secondParagraph.ParagraphFormat.Bullet.Char = '-';
secondParagraph.ParagraphFormat.DefaultPortionFormat.FillFormat.FillType = FillType.Solid;
secondParagraph.ParagraphFormat.DefaultPortionFormat.FillFormat.SolidFillColor.Color = Color.Black;
secondParagraph.ParagraphFormat.Depth = 1;

var thirdParagraph = new Paragraph { Text = "Third level" };
thirdParagraph.ParagraphFormat.Bullet.Type = BulletType.Symbol;
thirdParagraph.ParagraphFormat.Bullet.Char = Convert.ToChar(0x2022);
thirdParagraph.ParagraphFormat.DefaultPortionFormat.FillFormat.FillType = FillType.Solid;
thirdParagraph.ParagraphFormat.DefaultPortionFormat.FillFormat.SolidFillColor.Color = Color.Black;
thirdParagraph.ParagraphFormat.Depth = 2;

var fourthParagraph = new Paragraph { Text = "Fourth level" };
fourthParagraph.ParagraphFormat.Bullet.Type = BulletType.Symbol;
fourthParagraph.ParagraphFormat.Bullet.Char = '-';
fourthParagraph.ParagraphFormat.DefaultPortionFormat.FillFormat.FillType = FillType.Solid;
fourthParagraph.ParagraphFormat.DefaultPortionFormat.FillFormat.SolidFillColor.Color = Color.Black;
fourthParagraph.ParagraphFormat.Depth = 3;

textFrame.Paragraphs.Add(firstParagraph);
textFrame.Paragraphs.Add(secondParagraph);
textFrame.Paragraphs.Add(thirdParagraph);
textFrame.Paragraphs.Add(fourthParagraph);

presentation.Save("multilevel_list.pptx", SaveFormat.Pptx);

Iniziare gli Elementi Numerati con Valori Personalizzati

Usa IBulletFormat.NumberedBulletStartWith per impostare il numero iniziale visualizzato per un paragrafo numerato.

Questo esempio C# imposta IBulletFormat.Type per utilizzare la numerazione per tre paragrafi e assegna valori IBulletFormat.NumberedBulletStartWith di 2, 3 e 7. Il valore di partenza è configurato separatamente per ciascun paragrafo, consentendo ai numeri visualizzati di saltare valori:

using Aspose.Slides;
using Aspose.Slides.Export;

using var presentation = new Presentation();
var slide = presentation.Slides[0];

var shape = slide.Shapes.AddAutoShape(ShapeType.Rectangle, 200, 200, 400, 200);
var textFrame = shape.TextFrame;
textFrame.Paragraphs.Clear();

var firstParagraph = new Paragraph { Text = "Start at 2" };
firstParagraph.ParagraphFormat.Bullet.Type = BulletType.Numbered;
firstParagraph.ParagraphFormat.Bullet.NumberedBulletStartWith = 2;
textFrame.Paragraphs.Add(firstParagraph);

var secondParagraph = new Paragraph { Text = "Start at 3" };
secondParagraph.ParagraphFormat.Bullet.Type = BulletType.Numbered;
secondParagraph.ParagraphFormat.Bullet.NumberedBulletStartWith = 3;
textFrame.Paragraphs.Add(secondParagraph);

var thirdParagraph = new Paragraph { Text = "Start at 7" };
thirdParagraph.ParagraphFormat.Bullet.Type = BulletType.Numbered;
thirdParagraph.ParagraphFormat.Bullet.NumberedBulletStartWith = 7;
textFrame.Paragraphs.Add(thirdParagraph);

presentation.Save("custom_numbered_list.pptx", SaveFormat.Pptx);

Controllare Layout del Paragrafo e Proprietà di Fine

Regola i margini e i rientri del paragrafo per controllare la posizione della prima riga e delle righe a capo. È inoltre possibile formattare il segno di fine paragrafo separatamente dalle porzioni di testo visibili.

Impostare un Rientro della Prima Linea

Usa la proprietà IParagraphFormat.Indent per controllare il rientro della prima linea di un paragrafo. Questa proprietà sposta solo la prima linea rispetto al margine sinistro del paragrafo. Un valore positivo sposta la prima linea verso destra, mentre le righe rimanenti rimangono allineate al corpo del paragrafo.

Usa IParagraphFormat.MarginLeft quando devi spostare l’intero paragrafo. Usa IParagraphFormat.Indent quando devi spostare solo la prima linea.

Il seguente esempio assegna a tre paragrafi lo stesso IParagraphFormat.MarginLeft di 20 punti e valori IParagraphFormat.Indent di 0, 20 e 40 punti. Le prime linee iniziano a offset crescenti, mentre le linee a capo mantengono lo stesso margine sinistro:

using System.Drawing;
using Aspose.Slides;
using Aspose.Slides.Export;

using var presentation = new Presentation();
var slide = presentation.Slides[0];

var shape = slide.Shapes.AddAutoShape(ShapeType.Rectangle, 50, 50, 420, 220);
shape.FillFormat.FillType = FillType.NoFill;
shape.LineFormat.FillFormat.FillType = FillType.Solid;
shape.LineFormat.FillFormat.SolidFillColor.Color = Color.Gray;

var textFrame = shape.TextFrame;
textFrame.TextFrameFormat.AutofitType = TextAutofitType.Shape;
textFrame.Paragraphs.Clear();

var firstParagraph = new Paragraph { Text = "No first-line indent. Wrapped lines start at the same position as the first line." };
firstParagraph.ParagraphFormat.DefaultPortionFormat.FillFormat.FillType = FillType.Solid;
firstParagraph.ParagraphFormat.DefaultPortionFormat.FillFormat.SolidFillColor.Color = Color.Black;
firstParagraph.ParagraphFormat.MarginLeft = 20;
firstParagraph.ParagraphFormat.Indent = 0;

var secondParagraph = new Paragraph { Text = "First-line indent of 20 points. The first line moves to the right, while wrapped lines remain aligned to the paragraph body." };
secondParagraph.ParagraphFormat.DefaultPortionFormat.FillFormat.FillType = FillType.Solid;
secondParagraph.ParagraphFormat.DefaultPortionFormat.FillFormat.SolidFillColor.Color = Color.Black;
secondParagraph.ParagraphFormat.MarginLeft = 20;
secondParagraph.ParagraphFormat.Indent = 20;

var thirdParagraph = new Paragraph { Text = "First-line indent of 40 points. This paragraph shows a larger first-line offset to make the effect easier to see." };
thirdParagraph.ParagraphFormat.DefaultPortionFormat.FillFormat.FillType = FillType.Solid;
thirdParagraph.ParagraphFormat.DefaultPortionFormat.FillFormat.SolidFillColor.Color = Color.Black;
thirdParagraph.ParagraphFormat.MarginLeft = 20;
thirdParagraph.ParagraphFormat.Indent = 40;

textFrame.Paragraphs.Add(firstParagraph);
textFrame.Paragraphs.Add(secondParagraph);
textFrame.Paragraphs.Add(thirdParagraph);

presentation.Save("paragraph_indent.pptx", SaveFormat.Pptx);

Il risultato:

Il rientro della prima linea dei paragrafi

Impostare un Rientro Sospeso

Un rientro sospeso è un layout di paragrafo in cui la prima linea inizia a sinistra delle righe rimanenti. In Aspose.Slides, crei questo effetto con la proprietà IParagraphFormat.Indent. Imposta Indent a un valore negativo per spostare la prima linea a sinistra rispetto al corpo del paragrafo.

In pratica, IParagraphFormat.MarginLeft definisce la posizione sinistra del corpo del paragrafo, e IParagraphFormat.Indent definisce la posizione della prima linea rispetto a quel margine. Per creare un rientro sospeso, imposta un valore positivo di MarginLeft e un valore negativo di Indent.

Questa formattazione è utile per bibliografie, riferimenti, voci di glossario e altri paragrafi in cui le righe a capo devono allinearsi sotto il corpo del paragrafo anziché sotto il primo carattere della prima linea.

Il seguente esempio C# associa valori IParagraphFormat.MarginLeft di 40 e 60 punti con valori IParagraphFormat.Indent di -20 e -30 punti. In ogni paragrafo, la prima linea inizia a sinistra delle righe a capo; il secondo paragrafo ha un rientro sospeso più profondo:

using System.Drawing;
using Aspose.Slides;
using Aspose.Slides.Export;

using var presentation = new Presentation();
var slide = presentation.Slides[0];

var shape = slide.Shapes.AddAutoShape(ShapeType.Rectangle, 50, 50, 420, 220);
shape.FillFormat.FillType = FillType.NoFill;
shape.LineFormat.FillFormat.FillType = FillType.Solid;
shape.LineFormat.FillFormat.SolidFillColor.Color = Color.Gray;

var textFrame = shape.TextFrame;
textFrame.TextFrameFormat.AutofitType = TextAutofitType.Shape;
textFrame.Paragraphs.Clear();

var firstParagraph = new Paragraph { Text = "A hanging indent is created by combining a positive left margin with a negative indent. The first line starts to the left, while wrapped lines align with the paragraph body." };
firstParagraph.ParagraphFormat.DefaultPortionFormat.FillFormat.FillType = FillType.Solid;
firstParagraph.ParagraphFormat.DefaultPortionFormat.FillFormat.SolidFillColor.Color = Color.Black;
firstParagraph.ParagraphFormat.MarginLeft = 40;
firstParagraph.ParagraphFormat.Indent = -20;

var secondParagraph = new Paragraph { Text = "This second example uses a deeper hanging indent so the difference between the first line and the wrapped lines is easier to compare." };
secondParagraph.ParagraphFormat.DefaultPortionFormat.FillFormat.FillType = FillType.Solid;
secondParagraph.ParagraphFormat.DefaultPortionFormat.FillFormat.SolidFillColor.Color = Color.Black;
secondParagraph.ParagraphFormat.MarginLeft = 60;
secondParagraph.ParagraphFormat.Indent = -30;

textFrame.Paragraphs.Add(firstParagraph);
textFrame.Paragraphs.Add(secondParagraph);

presentation.Save("hanging_indent.pptx", SaveFormat.Pptx);

Il risultato:

Il rientro sospeso dei paragrafi

Impostare le Proprietà di Esecuzione di Fine Paragrafo

La proprietà IParagraph.EndParagraphPortionFormat controlla la formattazione del segno di fine paragrafo. Il seguente esempio crea un PortionFormat con IBasePortionFormat.FontHeight impostato a 48 punti e IBasePortionFormat.LatinFont impostato a Times New Roman. Assegna questo formato al segno di fine del secondo paragrafo, lasciando inalterate le porzioni di testo visibili:

using Aspose.Slides;
using Aspose.Slides.Export;

using var presentation = new Presentation("Test.pptx");
var slide = presentation.Slides[0];

var shape = slide.Shapes.AddAutoShape(ShapeType.Rectangle, 10, 10, 200, 250);
var textFrame = shape.TextFrame;
textFrame.Paragraphs.Clear();

var firstParagraph = new Paragraph();
firstParagraph.Portions.Add(new Portion("Sample text"));

var secondParagraph = new Paragraph();
secondParagraph.Portions.Add(new Portion("Sample text 2"));

var endParagraphFormat = new PortionFormat();
endParagraphFormat.FontHeight = 48;
endParagraphFormat.LatinFont = new FontData("Times New Roman");
secondParagraph.EndParagraphPortionFormat = endParagraphFormat;

textFrame.Paragraphs.Add(firstParagraph);
textFrame.Paragraphs.Add(secondParagraph);

presentation.Save("end_paragraph_format.pptx", SaveFormat.Pptx);

Contare le Linee Renderizzate

Per le regole dei paragrafi che influenzano l’andare a capo automatico e la punteggiatura alla fine della linea, vedere Control Line Breaking e Control Hanging Punctuation.

Usa IParagraph.GetLinesCount per contare le linee occupate da un paragrafo dopo il layout del testo, inclusi gli a capo automatici. Questo è utile quando si verifica la lunghezza del testo e il layout nei modelli di presentazione.

Un paragrafo è un elemento in ITextFrame.Paragraphs, e può occupare diverse linee renderizzate. Un interruzione di linea esplicita all’interno di un paragrafo fornisce una nuova linea senza creare un nuovo paragrafo. L’avvolgimento automatico crea linee basate sulla larghezza disponibile senza inserire interruzioni di linea esplicite nel testo. Pertanto contare i paragrafi o i caratteri di interruzione di linea non restituisce il conteggio delle linee renderizzate.

Il seguente esempio crea una forma di testo, conta le sue linee, restringe la forma e poi sostituisce il testo con una stringa più corta. L’esempio abilita ITextFrameFormat.WrapText e disabilita ITextFrameFormat.AutofitType in modo che la larghezza della forma controlli l’avvolgimento senza ridurre automaticamente il testo o ridimensionare la forma. Ogni misurazione utilizza IParagraph.GetLinesCount. Le dimensioni della forma sono in punti. Infine, l’esempio aggiunge un altro paragrafo e somma i conteggi delle linee all’interno del riquadro di testo.

using System;
using Aspose.Slides;

using var presentation = new Presentation();
var slide = presentation.Slides[0];

var shape = slide.Shapes.AddAutoShape(ShapeType.Rectangle, 50, 50, 400, 200);
var textFrame = shape.TextFrame;
textFrame.TextFrameFormat.WrapText = NullableBool.True;
textFrame.TextFrameFormat.AutofitType = TextAutofitType.None;

var paragraph = textFrame.Paragraphs[0];
paragraph.ParagraphFormat.DefaultPortionFormat.FontHeight = 20;
paragraph.Text = "This text demonstrates how automatic wrapping changes the number of rendered lines.";
Console.WriteLine($"Original width: {paragraph.GetLinesCount()}");

shape.Width = 150;
Console.WriteLine($"Narrower shape: {paragraph.GetLinesCount()}");

paragraph.Text = "Short text.";
Console.WriteLine($"Shorter text: {paragraph.GetLinesCount()}");

var secondParagraph = new Paragraph { Text = "Another paragraph." };
secondParagraph.ParagraphFormat.DefaultPortionFormat.FontHeight = 20;
textFrame.Paragraphs.Add(secondParagraph);

var totalLineCount = 0;
foreach (var currentParagraph in textFrame.Paragraphs)
{
    totalLineCount += currentParagraph.GetLinesCount();
}
Console.WriteLine($"Total lines in the text frame: {totalLineCount}");

Con questo testo e queste dimensioni, restringere la forma aumenta il conteggio delle linee, mentre sostituire il testo con la stringa breve lo riduce. I conteggi esatti possono variare in base alla disponibilità e sostituzione dei caratteri, alla dimensione del carattere, ai margini, all’indentazione, all’avvolgimento e alle impostazioni di adattamento. Usa i caratteri e le impostazioni di layout previsti per l’ambiente di destinazione quando verifichi un modello.

Il solo conteggio delle linee non determina se il testo supera il contenitore. Anche l’altezza disponibile, le altezze delle linee, la spaziatura di paragrafi e linee e il comportamento di adattamento influenzano; anche una singola linea può superare la larghezza disponibile quando l’avvolgimento è disabilitato.

Importare ed Esportare il Contenuto del Paragrafo

Usa HTML per importare testo in una presentazione o esportare i paragrafi esistenti per l’uso al di fuori di essa. Questa sezione mostra anche come rendere singoli paragrafi come immagini, inclusi i paragrafi nelle celle delle tabelle.

Importare Testo HTML nei Paragrafi

Usa ParagraphCollection.AddFromHtml per convertire il markup HTML in paragrafi e porzioni in un riquadro di testo.

Questo esempio C# legge HTML da un file e passa il markup a ParagraphCollection.AddFromHtml. Cancella il paragrafo predefinito del riquadro di testo in modo che il riquadro contenga solo il contenuto importato. La forma rettangolare lascia un margine di 10 punti su ciascun lato della diapositiva:

using System.IO;
using Aspose.Slides;
using Aspose.Slides.Export;

using var presentation = new Presentation();
var slide = presentation.Slides[0];

var shapeWidth = presentation.SlideSize.Size.Width - 20;
var shapeHeight = presentation.SlideSize.Size.Height - 20;
var shape = slide.Shapes.AddAutoShape(ShapeType.Rectangle, 10, 10, shapeWidth, shapeHeight);
shape.FillFormat.FillType = FillType.NoFill;
shape.TextFrame.Paragraphs.Clear();

using var reader = new StreamReader("file.html");
var html = reader.ReadToEnd();
shape.TextFrame.Paragraphs.AddFromHtml(html);

presentation.Save("html_text.pptx", SaveFormat.Pptx);

Esportare il Testo del Paragrafo in HTML

Usa ParagraphCollection.ExportToHtml per esportare un intervallo selezionato di paragrafi come HTML. Quando riutilizzi il testo della presentazione su un sito web, potresti voler preservare l’enfasi locale senza portare avanti il carattere, la dimensione o gli stili della casella di testo della presentazione. Imposta TextToHtmlConversionOptions.TextInheritanceLimit per controllare quanto in profondità l’esportatore segue l’ereditarietà della formattazione.

Scarica la presentazione di esempio e posizionala nella directory di lavoro dell’applicazione. La sua prima diapositiva contiene una forma di testo con il testo “Inherited text; explicit red 18pt”. L’input utilizza deliberatamente diversi livelli di formattazione:

  • Lo stile di testo predefinito della presentazione fornisce Calibri e una dimensione di 28 pt.
  • Lo stile di testo di primo livello del riquadro fornisce testo blu e corsivo.
  • Il paragrafo imposta esplicitamente il testo in grassetto.
  • La seconda porzione, “explicit red 18pt”, imposta esplicitamente testo rosso e una dimensione di 18 pt.

Il seguente esempio completo esporta gli stessi paragrafi tre volte. Passa TextToHtmlConversionOptions al metodo di esportazione e scrive ciascun risultato in un file HTML UTF‑8 separato:

using System.IO;
using System.Text;
using Aspose.Slides;
using Aspose.Slides.Export;

using var presentation = new Presentation("text-inheritance.pptx");
var textShape = (IAutoShape)presentation.Slides[0].Shapes[0];

var paragraphs = textShape.TextFrame.Paragraphs;
var modes = new[] { TextInheritanceLimit.All, TextInheritanceLimit.TextBox, TextInheritanceLimit.ParagraphOnly };

foreach (var mode in modes)
{
    var options = new TextToHtmlConversionOptions { TextInheritanceLimit = mode };

    var html = paragraphs.ExportToHtml(0, paragraphs.Count, options);
    File.WriteAllText($"{mode}.html", html, Encoding.UTF8);
}

L’HTML generato contiene il seguente CSS per la prima porzione, “Inherited text; “. La tabella elenca le dichiarazioni rilevanti; le altre proprietà generate sono omesse per chiarezza.

Output CSS Rilevante per la Prima Porzione Aspetto
All.html font-family:'Calibri'; font-size:28pt; color:#0000ff; font-style:italic; font-weight:bold Testo blu, in grassetto e italico a 28 pt in Calibri, se quel carattere è disponibile.
TextBox.html color:#0000ff; font-style:italic; font-weight:bold Testo blu, in grassetto e italico; la pagina o il browser circostante fornisce la famiglia di caratteri e la dimensione.
ParagraphOnly.html font-weight:bold Testo in grassetto; la pagina o il browser circostante fornisce la famiglia di caratteri, la dimensione, il colore e lo stile italico.

La seconda porzione mantiene color:#ff0000, font-size:18pt e font-weight:bold in tutti e tre gli output. Mantiene inoltre il corsivo in All e TextBox, ma non in ParagraphOnly. Limitare l’ereditarietà quindi non rimuove la formattazione assegnata esplicitamente a un paragrafo o a una porzione.

Apri i file nello stesso browser per confrontarli. Nei due modi limitati, le proprietà CSS omesse sono risolte dagli stili della pagina di destinazione o dai valori predefiniti del browser, quindi l’aspetto risultante dipende da dove l’HTML viene usato.

Salvare i Paragrafi Esportati come HTML UTF‑8

ITextToHtmlConversionOptions.EncodingName imposta il set di caratteri dichiarato nella stringa HTML restituita da ParagraphCollection.ExportToHtml. Quando salvi quella stringa, la codifica che passi a File.WriteAllText determina i byte effettivi. Usa la stessa codifica per entrambi in modo che il browser possa decodificare correttamente il testo multilingue.

using System.IO;
using System.Text;
using Aspose.Slides;
using Aspose.Slides.Export;

using var presentation = new Presentation();
var slide = presentation.Slides[0];

var shape = slide.Shapes.AddAutoShape(ShapeType.Rectangle, 0, 0, 400, 100);
shape.TextFrame.Text = "Café | Ωω | 日本語 | 😀";

var options = new TextToHtmlConversionOptions 
{ 
    EncodingName = "utf-8", 
    AddClipboardFragmentHeader = false 
};

var paragraphs = shape.TextFrame.Paragraphs;
var html = paragraphs.ExportToHtml(0, paragraphs.Count, options);
File.WriteAllText("paragraphs.html", html, new UTF8Encoding(false));

Il file salvato dichiara charset=utf-8 e contiene byte UTF‑8. Aprire paragraphs.html in un browser preserva il testo “Café | Ωω | 日本語 | 😀”.

Generare un Frammento di Appunti HTML

Imposta AddClipboardFragmentHeader a false per HTML ordinario o a true per includere un’intestazione di appunti. Entrambe le chiamate restituiscono una stringa. L’intestazione fornisce gli offset byte UTF‑8 dell’HTML circostante (StartHTML e EndHTML) e del contenuto da incollare (StartFragment e EndFragment).

Questo esempio esporta due paragrafi formattati come HTML ordinario (html) e come frammento di appunti HTML (clipboardHtml). Scrivere il frammento negli appunti di sistema è un passaggio applicativo separato. Un’API appunti che accetta byte HTML grezzi richiede UTF‑8 senza BOM.

using Aspose.Slides;
using Aspose.Slides.Export;

using var presentation = new Presentation();
var slide = presentation.Slides[0];

var shape = slide.Shapes.AddAutoShape(ShapeType.Rectangle, 0, 0, 400, 100);
var paragraphs = shape.TextFrame.Paragraphs;
paragraphs.Clear();
paragraphs.AddFromHtml("<p>Status: <b>Ready</b></p><p><i>Next steps</i></p>");

var options = new TextToHtmlConversionOptions { AddClipboardFragmentHeader = false };
var html = paragraphs.ExportToHtml(0, paragraphs.Count, options);

options.AddClipboardFragmentHeader = true;
var clipboardHtml = paragraphs.ExportToHtml(0, paragraphs.Count, options);

Renderizzare un Paragrafo come Immagine

IParagraph.GetImage renderizza direttamente un singolo paragrafo e restituisce un IImage. Salva il risultato in un file o stream con IImage.Save. Non è necessario renderizzare la forma contenente o ritagliare manualmente una bitmap.

IParagraph.GetImage può restituire null se il paragrafo non può essere trovato nella sua collezione padre, non ha limiti di rendering validi o non può essere renderizzato. Controlla il risultato prima di salvarlo e rilascia l’immagine restituita dopo l’uso.

Renderizzare un Paragrafo alla Scala Predefinita

L’esempio usa una presentazione con una diapositiva il cui primo elemento è una casella di testo contenente tre paragrafi.

La casella di testo con tre paragrafi

Il seguente esempio seleziona il secondo paragrafo all’indice 1 e chiama IParagraph.GetImage senza parametri di scala. Verifica che la forma contenga il paragrafo richiesto e che il rendering restituisca un’immagine prima di chiamare IImage.Save per salvarla in formato PNG. La dichiarazione using rilascia l’immagine dopo l’uso.

using System;
using Aspose.Slides;

using var presentation = new Presentation("sample.pptx");
var shape = presentation.Slides[0].Shapes[0];

if (shape is IAutoShape textShape && 
    textShape.TextFrame != null && 
    textShape.TextFrame.Paragraphs.Count > 1)
{
    var paragraph = textShape.TextFrame.Paragraphs[1];
    using var paragraphImage = paragraph.GetImage();

    if (paragraphImage != null)
    {
        paragraphImage.Save("paragraph.png", ImageFormat.Png);
    }
    else
    {
        Console.WriteLine("The paragraph could not be rendered.");
    }
}
else
{
    Console.WriteLine("The expected text shape or paragraph was not found.");
}

Il risultato:

L’immagine del paragrafo

Renderizzare un Paragrafo in una Cella di Tabella con Scala

Usa la sovraccarica di IParagraph.GetImage che accetta i parametri float scaleX e float scaleY per impostare i fattori di scala orizzontale e verticale. Il seguente esempio crea una tabella, renderizza il paragrafo nella sua prima cella a una larghezza e altezza doppie rispetto al valore predefinito, e salva il risultato come immagine PNG.

using System;
using Aspose.Slides;

var scaleX = 2f;
var scaleY = 2f;

using var presentation = new Presentation();
var slide = presentation.Slides[0];

var table = slide.Shapes.AddTable(50, 50, new[] { 300d }, new[] { 80d });
var paragraph = table[0, 0].TextFrame.Paragraphs[0];
paragraph.Text = "Text in a table cell";

using var paragraphImage = paragraph.GetImage(scaleX, scaleY);
if (paragraphImage != null)
{
    paragraphImage.Save("table_paragraph.png", ImageFormat.Png);
}
else
{
    Console.WriteLine("The paragraph could not be rendered.");
}

Un fattore di scala di 1 mantiene quell’asse alla dimensione predefinita in pixel. Per esempio, 2 per entrambi i fattori produce un’immagine la cui larghezza e altezza sono circa il doppio delle dimensioni predefinite, risultando in quattro volte più pixel. Fattori più grandi generano generalmente testo più nitido per lo zoom o output ad alta risoluzione, ma aumentano anche l’uso di memoria e la dimensione del file. Fattori inferiori a 1 producono immagini più piccole con meno dettaglio. Usa fattori uguali per preservare il rapporto d’aspetto del paragrafo; fattori orizzontali e verticali diversi allungano l’output indipendentemente.

Renderizzare un’intera forma con IShape.GetImage rimane utile quando l’output deve includere il riempimento, il bordo o altro contesto visivo della forma. Per un’immagine solo del paragrafo, usa IParagraph.GetImage.

FAQ

Posso disabilitare completamente l’andare a capo all’interno di un riquadro di testo?

Sì. Imposta ITextFrameFormat.WrapText per disabilitare l’avvolgimento in modo che le linee non vengano interrotte ai bordi del riquadro di testo.

Come posso ottenere i limiti esatti sullo slide di un paragrafo specifico?

Usa IParagraph.GetRect per recuperare il rettangolo di delimitazione del paragrafo. IPortion.GetRect fornisce i limiti di una singola porzione.

Dove è controllato l’allineamento del paragrafo (sinistra, destra, centro o giustificato)?

IParagraphFormat.Alignment è un’impostazione a livello di paragrafo e si applica all’intero paragrafo indipendentemente dalla formattazione delle singole porzioni.

Per allineare verticalmente le porzioni di diverse dimensioni di carattere all’interno di ogni riga, vedi Align Fonts Within a Line.

Posso impostare la lingua di correzione per una parte di un paragrafo?

Sì. Imposta IBasePortionFormat.LanguageId per le singole porzioni, così un paragrafo può contenere testo in più lingue.