Gestire i paragrafi di testo 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 singolo paragrafo in un riquadro di testo e fornisce l’accesso alle sue porzioni e alla formattazione a livello di paragrafo.
- IPortion rappresenta un run di testo all’interno di un paragrafo. Ogni porzione può avere il proprio testo e la propria formattazione a livello di carattere.
Un paragrafo può quindi contenere testo con caratteri, colori, dimensioni e altre formattazioni diversi utilizzando più porzioni.
Creare e formattare i paragrafi
Crea paragrafi nel riquadro di testo di una forma e utilizza le porzioni per formattare i singoli run di testo. Questa sezione mostra come combinare più porzioni all’interno di ciascun paragrafo e applicare diversi colori, dimensioni di carattere e stili.
Creare paragrafi con più porzioni
Il seguente esempio C# crea tre paragrafi, ognuno contenente tre run di testo nella sua collezione IParagraph.Portions. Riutilizza il paragrafo predefinito e la sua porzione vuota, poi aggiunge i paragrafi e le porzioni restanti. La formattazione è applicata tramite IPortion.PortionFormat: la prima porzione di ogni 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 punti elenco, elenchi a più livelli e numeri di partenza personalizzati.
Creare un elenco puntato o numerato
I punti elenco e la numerazione rendono più facile l’analisi degli elementi correlati. In Aspose.Slides, le impostazioni dell’elenco sono definite tramite IBulletFormat.
Questo esempio C# aggiunge un punto simbolo e un elemento numerato allo stesso riquadro di testo. IBulletFormat.Type seleziona il tipo di punto, mentre IBulletFormat.Char fornisce il simbolo e IBulletFormat.NumberedBulletStyle seleziona lo stile di numerazione. Entrambi gli elementi usano punti neri con un’altezza del 100 % 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 punti immagine
I punti immagine consentono di utilizzare 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 un IPPImage e la usa come punto del paragrafo. Imposta IBulletFormat.Type per usare un punto immagine e assegna l’immagine tramite IBulletFormat.Picture. IBulletFormat.Height è impostato al 100 % per dimensionare il punto rispetto 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 a più livelli
Imposta IParagraphFormat.Depth per posizionare i paragrafi a diversi livelli di un elenco. Il livello più alto ha una profondità di 0.
Questo esempio C# assegna valori di IParagraphFormat.Depth da 0 a 3 a quattro paragrafi, creando una gerarchia all’interno di un unico riquadro di testo. Ogni paragrafo usa un punto simbolo, con IBulletFormat.Char alternato tra un punto 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);
Impostare gli elementi numerati dell’elenco su valori personalizzati
Usa IBulletFormat.NumberedBulletStartWith per impostare il numero iniziale visualizzato per un paragrafo numerato.
Questo esempio C# imposta IBulletFormat.Type per usare la numerazione per tre paragrafi e assegna valori di IBulletFormat.NumberedBulletStartWith di 2, 3 e 7. Il valore di partenza è configurato separatamente per ciascun paragrafo, consentendo di saltare numeri visualizzati:
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 il layout del paragrafo e le proprietà di fine
Regola i margini e i rientri del paragrafo per controllare la posizione della prima riga e delle righe a capo. Puoi anche formattare il segno di fine paragrafo separatamente dalle porzioni di testo visibili.
Impostare un rientro della prima riga
Usa la proprietà IParagraphFormat.Indent per controllare il rientro della prima riga di un paragrafo. Questa proprietà sposta solo la prima riga rispetto al margine sinistro del paragrafo. Un valore positivo sposta la prima riga 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 riga.
L’esempio seguente assegna a tre paragrafi lo stesso IParagraphFormat.MarginLeft di 20 punti e valori di IParagraphFormat.Indent di 0, 20 e 40 punti. Le prime righe iniziano a offset progressivamente più ampi, mentre le righe 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:

Impostare un rientro sporgente
Un rientro sporgente è un layout di paragrafo in cui la prima riga inizia a sinistra delle righe successive. In Aspose.Slides, crei questo effetto con la proprietà IParagraphFormat.Indent. Imposta Indent a un valore negativo per spostare la prima riga verso 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 riga rispetto a quel margine. Per creare un rientro sporgente, 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 riga.
L’esempio C# seguente accoppia valori di IParagraphFormat.MarginLeft di 40 e 60 punti con valori di IParagraphFormat.Indent di -20 e -30 punti. In ciascun paragrafo, la prima riga inizia a sinistra delle righe a capo; il secondo paragrafo ha un rientro sporgente 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:

Impostare le proprietà di fine run del paragrafo
La proprietà IParagraph.EndParagraphPortionFormat controlla la formattazione del segno di fine paragrafo. L’esempio seguente 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 righe renderizzate
Per le regole del paragrafo che influenzano l’andata a capo automatica e la punteggiatura a fine riga, vedi Control Line Breaking e Control Hanging Punctuation.
Usa IParagraph.GetLinesCount per contare le righe occupate da un paragrafo dopo il layout del testo, inclusa l’andata a capo automatica. Questo è utile quando si verifica la lunghezza e il layout del testo nei modelli di presentazione.
Un paragrafo è un elemento in ITextFrame.Paragraphs, e può occupare diverse righe renderizzate. Un’interruzione di riga esplicita all’interno di un paragrafo fornisce una nuova riga senza creare un altro paragrafo. L’andata a capo automatica crea righe in base alla larghezza disponibile senza inserire interruzioni di riga esplicite nel testo. Pertanto, contare paragrafi o caratteri di interruzione di riga non fornisce il conteggio delle righe renderizzate.
L’esempio seguente crea una forma di testo, ne conta le righe, restringe la forma e poi sostituisce il testo con una stringa più breve. L’esempio abilita ITextFrameFormat.WrapText e disabilita ITextFrameFormat.AutofitType in modo che la larghezza della forma controlli l’andata a capo 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 righe nell’intero 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 righe, mentre sostituire il testo con la stringa breve lo riduce. I conteggi esatti possono variare in base alla disponibilità dei caratteri e alle sostituzioni, alla dimensione del carattere, ai margini, all’indentazione, all’andata a capo e alle impostazioni di adattamento automatico. Usa i caratteri e le impostazioni di layout previsti per l’ambiente di destinazione quando verifichi un modello.
Il solo conteggio delle righe non determina se il testo supera i confini del contenitore. Anche l’altezza disponibile, le altezze delle righe, la spaziatura di paragrafi e righe e il comportamento di autofit sono importanti; anche una singola riga può eccedere la larghezza disponibile quando l’andata a capo è disabilitata.
Importare ed esportare il contenuto dei paragrafi
Usa HTML per inserire testo in una presentazione o esportare paragrafi esistenti per usarli al di fuori di essa. Questa sezione mostra anche come rendere singoli paragrafi come immagini, inclusi paragrafi in celle di tabella.
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 conservare l’enfasi locale senza trasferire i tipi di carattere, le dimensioni o gli stili della casella di testo della presentazione. Imposta TextToHtmlConversionOptions.TextInheritanceLimit per controllare fino a che punto l’esportatore segue l’eredità 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 ogni 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; 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, grassetto, corsivo a 28 pt in Calibri, se quel carattere è disponibile. |
TextBox.html |
color:#0000ff; font-style:italic; font-weight:bold |
Testo blu, grassetto, corsivo; la pagina o il browser circostante fornisce famiglia di caratteri e dimensione. |
ParagraphOnly.html |
font-weight:bold |
Testo in grassetto; la pagina o il browser circostante fornisce famiglia di caratteri, dimensione, colore e stile corsivo. |
La seconda porzione mantiene color:#ff0000, font-size:18pt e font-weight:bold in tutti e tre gli output. Mantiene anche il corsivo in All e TextBox, ma non in ParagraphOnly. Limitare l’eredità non rimuove quindi 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 finale dipende da dove viene usato l’HTML.
Generare un frammento HTML per gli appunti
Imposta AddClipboardFragmentHeader su false per HTML ordinario o su true per includere un’intestazione per gli appunti. Entrambe le chiamate restituiscono una stringa. L’intestazione fornisce gli offset in byte UTF‑8 dell’HTML circostante (StartHTML e EndHTML) e il contenuto da incollare (StartFragment e EndFragment).
Questo esempio esporta due paragrafi formattati come HTML ordinario (html) e come frammento HTML per gli appunti (clipboardHtml). Scrivere il frammento negli appunti di sistema è un passaggio separato dell’applicazione. Un’API degli 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 un bitmap manualmente.
IParagraph.GetImage può restituire null se il paragrafo non è presente nella collezione genitore, 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 la cui prima forma è una casella di testo contenente tre paragrafi.

L’esempio seguente 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:

Renderizzare un paragrafo in una cella di tabella con scaling
Usa la sovraccarico di IParagraph.GetImage che accetta i parametri float scaleX e float scaleY per impostare i fattori di scala orizzontale e verticale. L’esempio seguente 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 sua dimensione pixel predefinita. 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ù alti producono generalmente testo più nitido per lo zoom o uscite ad alta risoluzione, ma aumentano anche l’uso di memoria e le dimensioni 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 resta 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’andata a capo all’interno di un riquadro di testo?
Sì. Imposta ITextFrameFormat.WrapText per disabilitare l’andata a capo così le righe non si interrompono ai bordi del riquadro di testo.
Come posso ottenere le coordinate esatte 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.