Gestire le caselle di testo nelle presentazioni con Java
Introduzione
I testi sulle diapositive sono solitamente contenuti in caselle di testo o forme. Pertanto, per aggiungere un testo a una diapositiva, è necessario aggiungere una casella di testo e poi inserire del testo all’interno della casella. Aspose.Slides for Java fornisce l’interfaccia IAutoShape che consente di aggiungere una forma contenente del testo.
Info
Aspose.Slides fornisce anche l’interfaccia IShape che consente di aggiungere forme alle diapositive. Tuttavia, non tutte le forme aggiunte tramite l’interfacciaIShape possono contenere testo. Le forme aggiunte tramite l’interfaccia IAutoShape possono invece contenere testo.
Nota
Pertanto, quando si lavora con una forma a cui si desidera aggiungere testo, è opportuno verificare e confermare che sia stata convertita tramite l’interfacciaIAutoShape. Solo così sarà possibile lavorare con TextFrame, proprietà di IAutoShape. Vedere la sezione Aggiornare il testo su questa pagina.
Creare una casella di testo su una diapositiva
Per creare una casella di testo su una diapositiva, seguite questi passaggi:
- Create un’istanza della classe Presentation.
- Ottenete un riferimento alla prima diapositiva della presentazione appena creata.
- Aggiungete un oggetto IAutoShape con
ShapeTypeimpostato suRectanglenella posizione desiderata sulla diapositiva e ottenete il riferimento all’oggettoIAutoShapeappena aggiunto. - Aggiungete la proprietà
TextFrameall’oggettoIAutoShapeche conterrà del testo. Nell’esempio seguente, abbiamo aggiunto questo testo: Aspose TextBox - Infine, salvate il file PPTX tramite l’oggetto
Presentation.
Questo codice Java—un’implementazione dei passaggi sopra—mostra come aggiungere testo a una diapositiva:
// Instanzia la presentazione
Presentation pres = new Presentation();
try {
// Ottiene la prima diapositiva nella presentazione
ISlide sld = pres.getSlides().get_Item(0);
// Aggiunge un AutoShape con tipo impostato su Rectangle
IAutoShape ashp = sld.getShapes().addAutoShape(ShapeType.Rectangle, 150, 75, 150, 50);
// Aggiunge TextFrame al rettangolo
ashp.addTextFrame(" ");
// Accede al frame di testo
ITextFrame txtFrame = ashp.getTextFrame();
// Crea l'oggetto Paragraph per il frame di testo
IParagraph para = txtFrame.getParagraphs().get_Item(0);
// Crea un oggetto Portion per il paragrafo
IPortion portion = para.getPortions().get_Item(0);
// Imposta il testo
portion.setText("Aspose TextBox");
// Salva la presentazione su disco
pres.save("TextBox_out.pptx", SaveFormat.Pptx);
} finally {
if (pres != null) pres.dispose();
}
Verificare la presenza di una forma casella di testo
Aspose.Slides fornisce il metodo isTextBox dell’interfaccia IAutoShape che consente di esaminare le forme e identificare le caselle di testo.

Questo codice Java mostra come verificare se una forma è stata creata come casella di testo:
Presentation presentation = new Presentation("sample.pptx");
try {
ForEach.shape(presentation, (shape, slide, index) -> {
if (shape instanceof IAutoShape) {
IAutoShape autoShape = (IAutoShape) shape;
System.out.println(autoShape.isTextBox() ? "shape is a text box" : "shape is not a text box");
}
});
} finally {
presentation.dispose();
}
Nota che, se si aggiunge semplicemente un’autoshape usando il metodo addAutoShape dell’interfaccia IShapeCollection, il metodo isTextBox dell’autoshape restituirà false. Tuttavia, dopo aver aggiunto testo all’autoshape usando il metodo addTextFrame o il metodo setText, la proprietà isTextBox restituirà true.
Presentation presentation = new Presentation();
ISlide slide = presentation.getSlides().get_Item(0);
IAutoShape shape1 = slide.getShapes().addAutoShape(ShapeType.Rectangle, 10, 10, 100, 40);
// shape1.isTextBox() restituisce false
shape1.addTextFrame("shape 1");
// shape1.isTextBox() restituisce true
IAutoShape shape2 = slide.getShapes().addAutoShape(ShapeType.Rectangle, 10, 110, 100, 40);
// shape2.isTextBox() restituisce false
shape2.getTextFrame().setText("shape 2");
// shape2.isTextBox() restituisce true
IAutoShape shape3 = slide.getShapes().addAutoShape(ShapeType.Rectangle, 10, 210, 100, 40);
// shape3.isTextBox() restituisce false
shape3.addTextFrame("");
// shape3.isTextBox() restituisce false
IAutoShape shape4 = slide.getShapes().addAutoShape(ShapeType.Rectangle, 10, 310, 100, 40);
// shape4.isTextBox() restituisce false
shape4.getTextFrame().setText("");
// shape4.isTextBox() restituisce false
Aggiungere colonne a una casella di testo
Aspose.Slides fornisce le proprietà ColumnCount e ColumnSpacing (dall’interfaccia ITextFrameFormat e dalla classe TextFrameFormat) che consentono di aggiungere colonne alle caselle di testo. È possibile specificare il numero di colonne in una casella di testo e impostare la spaziatura, in punti, tra le colonne.
Questo codice Java dimostra l’operazione descritta:
Presentation pres = new Presentation();
try {
// Ottiene la prima diapositiva nella presentazione
ISlide slide = pres.getSlides().get_Item(0);
// Aggiunge un AutoShape con tipo impostato su Rectangle
IAutoShape aShape = slide.getShapes().addAutoShape(ShapeType.Rectangle, 100, 100, 300, 300);
// Aggiunge TextFrame al rettangolo
aShape.addTextFrame("All these columns are limited to be within a single text container -- " +
"you can add or delete text and the new or remaining text automatically adjusts " +
"itself to flow within the container. You cannot have text flow from one container " +
"to other though -- we told you PowerPoint's column options for text are limited!");
// Ottiene il formato del testo del TextFrame
ITextFrameFormat format = aShape.getTextFrame().getTextFrameFormat();
// Specifica il numero di colonne nel TextFrame
format.setColumnCount(3);
// Specifica la spaziatura tra le colonne
format.setColumnSpacing(10);
// Salva la presentazione
pres.save("ColumnCount.pptx", SaveFormat.Pptx);
} finally {
if (pres != null) pres.dispose();
}
Aggiungere colonne a un Text Frame
Aspose.Slides for Java fornisce la proprietà ColumnCount (dall’interfaccia ITextFrameFormat) che consente di aggiungere colonne nei Text Frame. Tramite questa proprietà è possibile specificare il numero desiderato di colonne in un Text Frame.
Questo codice Java mostra come aggiungere una colonna all’interno di un Text Frame:
String outPptxFileName = "ColumnsTest.pptx";
Presentation pres = new Presentation();
try {
IAutoShape shape1 = pres.getSlides().get_Item(0).getShapes().addAutoShape(ShapeType.Rectangle, 100, 100, 300, 300);
TextFrameFormat format = (TextFrameFormat)shape1.getTextFrame().getTextFrameFormat();
format.setColumnCount(2);
shape1.getTextFrame().setText("All these columns are forced to stay within a single text container -- " +
"you can add or delete text - and the new or remaining text automatically adjusts " +
"itself to stay within the container. You cannot have text spill over from one container " +
"to other, though -- because PowerPoint's column options for text are limited!");
pres.save(outPptxFileName, SaveFormat.Pptx);
Presentation test = new Presentation(outPptxFileName);
try {
IAutoShape autoShape = ((AutoShape)test.getSlides().get_Item(0).getShapes().get_Item(0));
Assert.assertTrue(2 == autoShape.getTextFrame().getTextFrameFormat().getColumnCount());
Assert.assertTrue(Double.NaN == autoShape.getTextFrame().getTextFrameFormat().getColumnSpacing());
} finally {
if (test != null) test.dispose();
}
format.setColumnSpacing(20);
pres.save(outPptxFileName, SaveFormat.Pptx);
Presentation test1 = new Presentation(outPptxFileName);
try {
IAutoShape autoShape = ((AutoShape)test1.getSlides().get_Item(0).getShapes().get_Item(0));
Assert.assertTrue(2 == autoShape.getTextFrame().getTextFrameFormat().getColumnCount());
Assert.assertTrue(20 == autoShape.getTextFrame().getTextFrameFormat().getColumnSpacing());
} finally {
if (test1 != null) test1.dispose();
}
format.setColumnCount(3);
format.setColumnSpacing(15);
pres.save(outPptxFileName, SaveFormat.Pptx);
Presentation test2 = new Presentation(outPptxFileName);
try {
IAutoShape autoShape = ((AutoShape)test2.getSlides().get_Item(0).getShapes().get_Item(0));
Assert.assertTrue(3 == autoShape.getTextFrame().getTextFrameFormat().getColumnCount());
Assert.assertTrue(15 == autoShape.getTextFrame().getTextFrameFormat().getColumnSpacing());
} finally {
if (test2 != null) test2.dispose();
}
} finally {
if (pres != null) pres.dispose();
}
Aggiornare il testo
Aspose.Slides consente di modificare o aggiornare il testo contenuto in una casella di testo o tutti i testi contenuti in una presentazione.
Questo codice Java dimostra un’operazione in cui tutti i testi di una presentazione vengono aggiornati o modificati:
Presentation pres = new Presentation("text.pptx");
try {
for (ISlide slide : pres.getSlides())
{
for (IShape shape : slide.getShapes())
{
if (shape instanceof IAutoShape) //Verifica se la forma supporta il text frame (IAutoShape).
{
IAutoShape autoShape = (IAutoShape)shape;
for (IParagraph paragraph : autoShape.getTextFrame().getParagraphs()) //Itera i paragrafi nel text frame
{
for (IPortion portion : paragraph.getPortions()) //Itera ogni porzione nel paragrafo
{
portion.setText(portion.getText().replace("years", "months")); //Modifica il testo
portion.getPortionFormat().setFontBold(NullableBool.True); //Modifica la formattazione
}
}
}
}
}
//Salva la presentazione modificata
pres.save("text-changed.pptx", SaveFormat.Pptx);
} finally {
if (pres != null) pres.dispose();
}
Aggiungere una casella di testo con collegamento ipertestuale
È possibile inserire un collegamento all’interno di una casella di testo. Quando la casella di testo viene cliccata, gli utenti vengono indirizzati all’apertura del collegamento.
Per aggiungere una casella di testo contenente un collegamento, seguite questi passaggi:
- Create un’istanza della classe
Presentation. - Ottenete un riferimento alla prima diapositiva della presentazione appena creata.
- Aggiungete un oggetto
AutoShapeconShapeTypeimpostato suRectanglenella posizione desiderata sulla diapositiva e ottenete il riferimento all’oggetto AutoShape appena aggiunto. - Aggiungete un
TextFrameall’oggettoAutoShapeche contiene Aspose TextBox come testo predefinito. - Istanziate la classe
IHyperlinkManager. - Assegnate l’oggetto
IHyperlinkManageralla proprietà HyperlinkClick associata alla porzione desiderata delTextFrame. - Infine, salvate il file PPTX tramite l’oggetto
Presentation.
Questo codice Java—un’implementazione dei passaggi sopra—mostra come aggiungere una casella di testo con collegamento ipertestuale a una diapositiva:
// Instanzia una classe Presentation che rappresenta un PPTX
Presentation pres = new Presentation();
try {
// Ottiene la prima diapositiva nella presentazione
ISlide slide = pres.getSlides().get_Item(0);
// Aggiunge un oggetto AutoShape con tipo impostato su Rectangle
IShape shape = slide.getShapes().addAutoShape(ShapeType.Rectangle, 150, 150, 150, 50);
// Converte la forma in AutoShape
IAutoShape pptxAutoShape = (IAutoShape)shape;
// Accede alla proprietà ITextFrame associata all'AutoShape
pptxAutoShape.addTextFrame("");
ITextFrame textFrame = pptxAutoShape.getTextFrame();
// Aggiunge del testo al frame
textFrame.getParagraphs().get_Item(0).getPortions().get_Item(0).setText("Aspose.Slides");
// Imposta l'Hyperlink per il testo della porzione
IHyperlinkManager hyperlinkManager = textFrame.getParagraphs().get_Item(0).getPortions().get_Item(0).
getPortionFormat().getHyperlinkManager();
hyperlinkManager.setExternalHyperlinkClick("http://www.aspose.com");
// Salva la presentazione PPTX
pres.save("hLink_out.pptx", SaveFormat.Pptx);
} finally {
if (pres != null) pres.dispose();
}
FAQ
Qual è la differenza tra una casella di testo e un segnaposto testo quando si lavora con le diapositive master?
Un segnaposto eredita stile/posizione dal master e può essere sovrascritto nei layout, mentre una casella di testo normale è un oggetto indipendente su una diapositiva specifica e non cambia quando si cambiano i layout.
Come posso eseguire una sostituzione massiva del testo nell’intera presentazione senza modificare il testo all’interno di grafici, tabelle e SmartArt?
Limitate l’iterazione alle autoshape che possiedono Text Frame ed escludete gli oggetti incorporati (chart, table, SmartArt) attraversando le loro collezioni separatamente o saltando quei tipi di oggetti.