Formatear texto de presentación en C++
Visión general
Este artículo muestra cómo dar formato al texto en presentaciones de PowerPoint y OpenDocument utilizando Aspose.Slides para C++. Cubre colores de fondo, transparencia, espaciado de caracteres, propiedades de fuentes, rotación, espaciado de párrafos, comportamiento de ajuste automático, anclaje de texto, tabuladores y configuraciones de idioma.
A menos que se indique lo contrario, los ejemplos utilizan sample.pptx. La primera forma en su primera diapositiva es un cuadro de texto, y su primer párrafo contiene el texto que se muestra a continuación. Tanto los índices de diapositiva como los de forma son basados en cero. Los ejemplos que seleccionan porciones en negrita usan formato efectivo, incluido el formato de negrita heredado:

Para encontrar y resaltar texto literal o coincidencias de expresiones regulares, vea Buscar y reemplazar texto.
Establecer color de fondo del texto
Utilice IParagraphFormat::get_DefaultPortionFormat para establecer el color de resaltado predeterminado de un párrafo, o utilice IBasePortionFormat::get_HighlightColor para porciones de texto individuales.
El siguiente ejemplo establece un resaltado gris claro como predeterminado para el primer párrafo. Los colores de resaltado explícitos en porciones individuales tienen prioridad sobre este predeterminado:
#include <DOM/IAutoShape.h>
#include <DOM/IColorFormat.h>
#include <DOM/IParagraph.h>
#include <DOM/IParagraphFormat.h>
#include <DOM/IPortionFormat.h>
#include <DOM/ISlide.h>
#include <DOM/ITextFrame.h>
#include <DOM/Presentation.h>
#include <Export/SaveFormat.h>
#include <drawing/color.h>
using namespace Aspose::Slides;
using namespace Aspose::Slides::Export;
auto presentation = System::MakeObject<Presentation>(u"sample.pptx");
auto firstShape = presentation->get_Slide(0)->get_Shape(0);
auto autoShape = System::ExplicitCast<IAutoShape>(firstShape);
auto paragraph = autoShape->get_TextFrame()->get_Paragraph(0);
auto defaultPortionFormat = paragraph->get_ParagraphFormat()->get_DefaultPortionFormat();
auto highlightColor = System::Drawing::Color::get_LightGray();
// Establecer el color de resaltado para todo el párrafo.
presentation->Save(u"gray_paragraph.pptx", SaveFormat::Pptx);
presentation->Dispose();
El resultado:

El siguiente ejemplo de código muestra cómo establecer el color de fondo para porciones de texto con una fuente en negrita:
#include <DOM/IAutoShape.h>
#include <DOM/IColorFormat.h>
#include <DOM/IParagraph.h>
#include <DOM/IPortion.h>
#include <DOM/IPortionCollection.h>
#include <DOM/IPortionFormat.h>
#include <DOM/IPortionFormatEffectiveData.h>
#include <DOM/ISlide.h>
#include <DOM/ITextFrame.h>
#include <DOM/Presentation.h>
#include <Export/SaveFormat.h>
#include <drawing/color.h>
using namespace Aspose::Slides;
using namespace Aspose::Slides::Export;
auto presentation = System::MakeObject<Presentation>(u"sample.pptx");
auto firstShape = presentation->get_Slide(0)->get_Shape(0);
auto autoShape = System::ExplicitCast<IAutoShape>(firstShape);
auto paragraph = autoShape->get_TextFrame()->get_Paragraph(0);
auto portions = paragraph->get_Portions();
int portionCount = portions->get_Count();
auto highlightColor = System::Drawing::Color::get_LightGray();
for (int portionIndex = 0; portionIndex < portionCount; portionIndex++)
{
auto portion = paragraph->get_Portion(portionIndex);
auto portionFormat = portion->get_PortionFormat();
if (portionFormat->GetEffective()->get_FontBold())
{
// Establecer el color de resaltado para la porción de texto.
portionFormat->get_HighlightColor()->set_Color(highlightColor);
}
}
presentation->Save(u"gray_text_portions.pptx", SaveFormat::Pptx);
presentation->Dispose();
El resultado:

Alinear párrafos de texto
Utilice IParagraphFormat::set_Alignment para establecer la alineación de párrafos dentro de un marco de texto. El valor puede ser centrado, alineado a la izquierda, alineado a la derecha, justificado, etc.
El siguiente ejemplo de código muestra cómo alinear el párrafo al centro:
#include <DOM/IAutoShape.h>
#include <DOM/IParagraph.h>
#include <DOM/IParagraphFormat.h>
#include <DOM/ISlide.h>
#include <DOM/ITextFrame.h>
#include <DOM/Presentation.h>
#include <DOM/TextAlignment.h>
#include <Export/SaveFormat.h>
using namespace Aspose::Slides;
using namespace Aspose::Slides::Export;
auto presentation = System::MakeObject<Presentation>(u"sample.pptx");
auto firstShape = presentation->get_Slide(0)->get_Shape(0);
auto autoShape = System::ExplicitCast<IAutoShape>(firstShape);
auto paragraph = autoShape->get_TextFrame()->get_Paragraph(0);
// Establecer la alineación del párrafo al centro.
paragraph->get_ParagraphFormat()->set_Alignment(TextAlignment::Center);
presentation->Save(u"aligned_paragraph.pptx", SaveFormat::Pptx);
presentation->Dispose();
El resultado:

Alinear fuentes dentro de una línea
Utilice IParagraphFormat::set_FontAlignment para alinear verticalmente las porciones de texto de diferentes tamaños de fuente dentro de una línea. Esta configuración se aplica a todo el párrafo y controla la alineación dentro de cada una de sus líneas.
El siguiente ejemplo autocontenido crea cuatro cuadros de texto etiquetados en una diapositiva. Cada párrafo contiene el mismo texto en 18, 36 y 54 puntos, con una alineación de fuente diferente. Utiliza Arial, desactiva el ajuste automático y el ajuste de línea, y mantiene los marcos de texto lo suficientemente grandes para una sola línea.
#include <DOM/FontAlignment.h>
#include <DOM/Fonts/FontData.h>
#include <DOM/IAutoShape.h>
#include <DOM/IColorFormat.h>
#include <DOM/IFillFormat.h>
#include <DOM/ILineFormat.h>
#include <DOM/IParagraph.h>
#include <DOM/IParagraphCollection.h>
#include <DOM/IParagraphFormat.h>
#include <DOM/IPortionCollection.h>
#include <DOM/IPortionFormat.h>
#include <DOM/IShapeCollection.h>
#include <DOM/ISlide.h>
#include <DOM/ITextFrame.h>
#include <DOM/ITextFrameFormat.h>
#include <DOM/FillType.h>
#include <DOM/NullableBool.h>
#include <DOM/Paragraph.h>
#include <DOM/Portion.h>
#include <DOM/Presentation.h>
#include <DOM/ShapeType.h>
#include <DOM/TextAlignment.h>
#include <DOM/TextAnchorType.h>
#include <DOM/TextAutofitType.h>
#include <Export/SaveFormat.h>
#include <drawing/color.h>
using namespace Aspose::Slides;
using namespace Aspose::Slides::Export;
using namespace System;
using namespace System::Drawing;
auto presentation = MakeObject<Presentation>();
auto slide = presentation->get_Slide(0);
FontAlignment alignments[] = { FontAlignment::Baseline, FontAlignment::Top, FontAlignment::Center, FontAlignment::Bottom };
String labels[] = { u"Baseline", u"Top", u"Center", u"Bottom" };
float fontSizes[] = { 18.0f, 36.0f, 54.0f };
auto font = MakeObject<FontData>(u"Arial");
for (auto i = 0; i < 4; i++)
{
auto shape = slide->get_Shapes()->AddAutoShape(ShapeType::Rectangle, 30, 20 + i * 130, 660, 120);
shape->get_FillFormat()->set_FillType(FillType::NoFill);
shape->get_LineFormat()->get_FillFormat()->set_FillType(FillType::NoFill);
auto textFrame = shape->get_TextFrame();
textFrame->get_TextFrameFormat()->set_AnchoringType(TextAnchorType::Top);
textFrame->get_TextFrameFormat()->set_AutofitType(TextAutofitType::None);
textFrame->get_TextFrameFormat()->set_WrapText(NullableBool::False);
auto label = textFrame->get_Paragraph(0);
label->set_Text(labels[i]);
label->get_ParagraphFormat()->set_Alignment(TextAlignment::Left);
auto labelFormat = label->get_ParagraphFormat()->get_DefaultPortionFormat();
labelFormat->set_FontHeight(14);
labelFormat->set_LatinFont(font);
labelFormat->get_FillFormat()->set_FillType(FillType::Solid);
labelFormat->get_FillFormat()->get_SolidFillColor()->set_Color(Color::get_Gray());
auto paragraph = MakeObject<Paragraph>();
paragraph->get_ParagraphFormat()->set_FontAlignment(alignments[i]);
paragraph->get_ParagraphFormat()->set_Alignment(TextAlignment::Left);
auto portionFormat = paragraph->get_ParagraphFormat()->get_DefaultPortionFormat();
portionFormat->set_LatinFont(font);
portionFormat->get_FillFormat()->set_FillType(FillType::Solid);
portionFormat->get_FillFormat()->get_SolidFillColor()->set_Color(Color::get_Black());
for (auto fontSize : fontSizes)
{
auto portion = MakeObject<Portion>(u"Ag ");
portion->get_PortionFormat()->set_FontHeight(fontSize);
paragraph->get_Portions()->Add(portion);
}
textFrame->get_Paragraphs()->Add(paragraph);
}
presentation->Save(u"font_alignment.pptx", SaveFormat::Pptx);
presentation->Dispose();
El resultado:

La alineación de fuentes utiliza métricas tipográficas, por lo que los bordes visibles de letras individuales no necesariamente se alinean exactamente. El ejemplo incluye tanto una letra mayúscula como un descendente para ayudar a mostrar la diferencia entre la alineación de línea base y la inferior. La disponibilidad y sustitución de fuentes, los caracteres utilizados y la diferencia en los tamaños de fuente afectan el resultado. Las dimensiones del marco, los márgenes, el espaciado de líneas, el ajuste y el ajuste automático también influyen en el diseño; use las mismas fuentes y configuraciones de diseño al comparar los modos.
Esta configuración difiere de IParagraphFormat::set_Alignment, que controla la alineación horizontal del párrafo, y de ITextFrameFormat::set_AnchoringType, que posiciona el bloque de texto verticalmente dentro de su forma. El formato de superíndice y subíndice mediante IBasePortionFormat::set_Escapement desplaza porciones individuales respecto a la línea base en lugar de establecer la alineación de fuente para las líneas del párrafo.
Establecer transparencia para el texto
La transparencia del texto se controla mediante el componente alfa del color asignado a través de IBasePortionFormat::get_FillFormat. En los ejemplos siguientes, alpha = 50 es un valor de canal alfa ARGB en la escala 0‑255, no un porcentaje de transparencia.
El siguiente ejemplo de código muestra cómo aplicar transparencia al párrafo completo:
#include <DOM/FillType.h>
#include <DOM/IAutoShape.h>
#include <DOM/IColorFormat.h>
#include <DOM/IFillFormat.h>
#include <DOM/IParagraph.h>
#include <DOM/IParagraphFormat.h>
#include <DOM/IPortionFormat.h>
#include <DOM/ISlide.h>
#include <DOM/ITextFrame.h>
#include <DOM/Presentation.h>
#include <Export/SaveFormat.h>
#include <drawing/color.h>
using namespace Aspose::Slides;
using namespace Aspose::Slides::Export;
int alpha = 50;
auto presentation = System::MakeObject<Presentation>(u"sample.pptx");
auto firstShape = presentation->get_Slide(0)->get_Shape(0);
auto autoShape = System::ExplicitCast<IAutoShape>(firstShape);
auto paragraph = autoShape->get_TextFrame()->get_Paragraph(0);
auto defaultPortionFormat = paragraph->get_ParagraphFormat()->get_DefaultPortionFormat();
// Establecer el color de relleno del texto a color transparente.
defaultPortionFormat->get_FillFormat()->set_FillType(FillType::Solid);
auto baseColor = System::Drawing::Color::get_Black();
auto transparentColor = System::Drawing::Color::FromArgb(alpha, baseColor);
defaultPortionFormat->get_FillFormat()->get_SolidFillColor()->set_Color(transparentColor);
presentation->Save(u"transparent_paragraph.pptx", SaveFormat::Pptx);
presentation->Dispose();
El resultado:

El siguiente ejemplo de código muestra cómo aplicar transparencia a porciones de texto con una fuente en negrita:
#include <DOM/FillType.h>
#include <DOM/IAutoShape.h>
#include <DOM/IColorFormat.h>
#include <DOM/IFillFormat.h>
#include <DOM/IParagraph.h>
#include <DOM/IPortion.h>
#include <DOM/IPortionCollection.h>
#include <DOM/IPortionFormat.h>
#include <DOM/IPortionFormatEffectiveData.h>
#include <DOM/ISlide.h>
#include <DOM/ITextFrame.h>
#include <DOM/Presentation.h>
#include <Export/SaveFormat.h>
#include <drawing/color.h>
using namespace Aspose::Slides;
using namespace Aspose::Slides::Export;
int alpha = 50;
auto presentation = System::MakeObject<Presentation>(u"sample.pptx");
auto firstShape = presentation->get_Slide(0)->get_Shape(0);
auto autoShape = System::ExplicitCast<IAutoShape>(firstShape);
auto paragraph = autoShape->get_TextFrame()->get_Paragraph(0);
auto portions = paragraph->get_Portions();
int portionCount = portions->get_Count();
for (int portionIndex = 0; portionIndex < portionCount; portionIndex++)
{
auto portion = paragraph->get_Portion(portionIndex);
auto portionFormat = portion->get_PortionFormat();
if (portionFormat->GetEffective()->get_FontBold())
{
// Establecer la transparencia de la porción de texto.
portionFormat->get_FillFormat()->set_FillType(FillType::Solid);
auto baseColor = System::Drawing::Color::get_Black();
auto transparentColor = System::Drawing::Color::FromArgb(alpha, baseColor);
portionFormat->get_FillFormat()->get_SolidFillColor()->set_Color(transparentColor);
}
}
presentation->Save(u"transparent_text_portions.pptx", SaveFormat::Pptx);
presentation->Dispose();
El resultado:

Establecer espaciado de caracteres para el texto
Utilice IBasePortionFormat::set_Spacing para ampliar o condensar el espaciado entre caracteres en un cuadro de texto. Los ejemplos añaden 3 puntos de espaciado; los valores negativos condensan el texto.
El siguiente código C++ muestra cómo ampliar el espaciado de caracteres en el párrafo completo:
#include <DOM/IAutoShape.h>
#include <DOM/IParagraph.h>
#include <DOM/IParagraphFormat.h>
#include <DOM/IPortionFormat.h>
#include <DOM/ISlide.h>
#include <DOM/ITextFrame.h>
#include <DOM/Presentation.h>
#include <Export/SaveFormat.h>
using namespace Aspose::Slides;
using namespace Aspose::Slides::Export;
auto presentation = System::MakeObject<Presentation>(u"sample.pptx");
auto firstShape = presentation->get_Slide(0)->get_Shape(0);
auto autoShape = System::ExplicitCast<IAutoShape>(firstShape);
auto paragraph = autoShape->get_TextFrame()->get_Paragraph(0);
// Nota: use valores negativos para comprimir el espaciado de caracteres.
paragraph->get_ParagraphFormat()->get_DefaultPortionFormat()->set_Spacing(3.0f); // Expandir el espaciado de caracteres.
presentation->Save(u"character_spacing_in_paragraph.pptx", SaveFormat::Pptx);
presentation->Dispose();
El resultado:

El siguiente ejemplo de código muestra cómo ampliar el espaciado de caracteres en porciones de texto con una fuente en negrita:
#include <DOM/IAutoShape.h>
#include <DOM/IParagraph.h>
#include <DOM/IPortion.h>
#include <DOM/IPortionCollection.h>
#include <DOM/IPortionFormat.h>
#include <DOM/IPortionFormatEffectiveData.h>
#include <DOM/ISlide.h>
#include <DOM/ITextFrame.h>
#include <DOM/Presentation.h>
#include <Export/SaveFormat.h>
using namespace Aspose::Slides;
using namespace Aspose::Slides::Export;
auto presentation = System::MakeObject<Presentation>(u"sample.pptx");
auto firstShape = presentation->get_Slide(0)->get_Shape(0);
auto autoShape = System::ExplicitCast<IAutoShape>(firstShape);
auto paragraph = autoShape->get_TextFrame()->get_Paragraph(0);
auto portions = paragraph->get_Portions();
int portionCount = portions->get_Count();
for (int portionIndex = 0; portionIndex < portionCount; portionIndex++)
{
auto portion = paragraph->get_Portion(portionIndex);
auto portionFormat = portion->get_PortionFormat();
if (portionFormat->GetEffective()->get_FontBold())
{
// Nota: use valores negativos para comprimir el espaciado de caracteres.
portionFormat->set_Spacing(3.0f); // Expandir el espaciado de caracteres.
}
}
presentation->Save(u"character_spacing_in_text_portions.pptx", SaveFormat::Pptx);
presentation->Dispose();
El resultado:

Desactivar el kerning para fuentes específicas
En algunos casos, el texto renderizado por Aspose.Slides puede verse ligeramente más compacto que el mismo texto mostrado en PowerPoint. Esto puede ocurrir porque PowerPoint puede ignorar los datos de kerning para ciertas fuentes, incluso cuando la fuente contiene información de kerning válida y el kerning está activado en la configuración de PowerPoint.
Para que la salida renderizada se acerque más a PowerPoint en estos casos, puede desactivar el kerning para las porciones de texto que usan la fuente afectada. Utilice IBasePortionFormat::set_KerningMinimalSize para establecer un valor mayor que el tamaño real de la fuente. Este ejemplo requiere “presentation.pptx” con un cuadro de texto como primera forma en la primera diapositiva. Comprueba los nombres de fuentes efectivos, incluidas las fuentes heredadas, y establece un umbral de 100 puntos para las porciones que usan Roboto. Esto desactiva el kerning para las porciones coincidentes con un tamaño de fuente inferior a 100 puntos:
#include <DOM/IAutoShape.h>
#include <DOM/IFontData.h>
#include <DOM/IPortionFormatEffectiveData.h>
#include <DOM/IParagraph.h>
#include <DOM/IParagraphCollection.h>
#include <DOM/IPortion.h>
#include <DOM/IPortionCollection.h>
#include <DOM/IPortionFormat.h>
#include <DOM/ISlide.h>
#include <DOM/ITextFrame.h>
#include <DOM/Presentation.h>
#include <Export/SaveFormat.h>
using namespace Aspose::Slides;
using namespace Aspose::Slides::Export;
auto presentation = System::MakeObject<Presentation>(u"presentation.pptx");
auto firstShape = presentation->get_Slide(0)->get_Shape(0);
auto autoShape = System::ExplicitCast<IAutoShape>(firstShape);
System::String targetFont = u"Roboto";
auto textFrame = autoShape->get_TextFrame();
auto paragraphs = textFrame->get_Paragraphs();
int paragraphCount = paragraphs->get_Count();
for (int paragraphIndex = 0; paragraphIndex < paragraphCount; paragraphIndex++)
{
auto paragraph = textFrame->get_Paragraph(paragraphIndex);
auto portions = paragraph->get_Portions();
int portionCount = portions->get_Count();
for (int portionIndex = 0; portionIndex < portionCount; portionIndex++)
{
auto portion = paragraph->get_Portion(portionIndex);
auto portionFormat = portion->get_PortionFormat();
auto textFormat = portionFormat->GetEffective();
auto latinFont = textFormat->get_LatinFont();
auto eastAsianFont = textFormat->get_EastAsianFont();
auto complexScriptFont = textFormat->get_ComplexScriptFont();
bool isLatinFont = latinFont != nullptr && latinFont->get_FontName() == targetFont;
bool isEastAsianFont = eastAsianFont != nullptr && eastAsianFont->get_FontName() == targetFont;
bool isComplexScriptFont = complexScriptFont != nullptr && complexScriptFont->get_FontName() == targetFont;
if (isLatinFont || isEastAsianFont || isComplexScriptFont)
{
portionFormat->set_KerningMinimalSize(100.0f);
}
}
}
presentation->Save(u"output.pptx", SaveFormat::Pptx);
presentation->Dispose();
Para el texto coincidente por debajo del umbral, esta configuración evita el kerning y puede ayudar a alinear la representación de Aspose.Slides con la salida visual de PowerPoint para fuentes afectadas por este comportamiento específico de PowerPoint.
Administrar propiedades de fuente del texto
Las propiedades de la fuente pueden establecerse a nivel de párrafo a través de IParagraphFormat::get_DefaultPortionFormat o en porciones individuales mediante IPortionFormat.
El siguiente ejemplo establece la fuente predeterminada del primer párrafo en Times New Roman de 12 puntos con formato en negrita, cursiva y subrayado punteado. El formato explícito en porciones individuales tiene prioridad sobre estos valores predeterminados.
#include <DOM/Fonts/FontData.h>
#include <DOM/IAutoShape.h>
#include <DOM/IParagraph.h>
#include <DOM/IParagraphFormat.h>
#include <DOM/IPortionFormat.h>
#include <DOM/ISlide.h>
#include <DOM/ITextFrame.h>
#include <DOM/NullableBool.h>
#include <DOM/Presentation.h>
#include <DOM/TextUnderlineType.h>
#include <Export/SaveFormat.h>
using namespace Aspose::Slides;
using namespace Aspose::Slides::Export;
auto presentation = System::MakeObject<Presentation>(u"sample.pptx");
auto firstShape = presentation->get_Slide(0)->get_Shape(0);
auto autoShape = System::ExplicitCast<IAutoShape>(firstShape);
auto paragraph = autoShape->get_TextFrame()->get_Paragraph(0);
auto defaultPortionFormat = paragraph->get_ParagraphFormat()->get_DefaultPortionFormat();
// Establecer las propiedades de la fuente para el párrafo.
defaultPortionFormat->set_FontHeight(12.0f);
defaultPortionFormat->set_FontBold(NullableBool::True);
defaultPortionFormat->set_FontItalic(NullableBool::True);
defaultPortionFormat->set_FontUnderline(TextUnderlineType::Dotted);
auto font = System::MakeObject<FontData>(u"Times New Roman");
defaultPortionFormat->set_LatinFont(font);
presentation->Save(u"font_properties_for_paragraph.pptx", SaveFormat::Pptx);
presentation->Dispose();
El resultado:

El siguiente ejemplo aplica Times New Roman de 13 puntos, formato cursiva y subrayado punteado a las porciones cuyo formato efectivo es en negrita:
#include <DOM/Fonts/FontData.h>
#include <DOM/IAutoShape.h>
#include <DOM/IParagraph.h>
#include <DOM/IPortion.h>
#include <DOM/IPortionCollection.h>
#include <DOM/IPortionFormat.h>
#include <DOM/IPortionFormatEffectiveData.h>
#include <DOM/ISlide.h>
#include <DOM/ITextFrame.h>
#include <DOM/NullableBool.h>
#include <DOM/Presentation.h>
#include <DOM/TextUnderlineType.h>
#include <Export/SaveFormat.h>
using namespace Aspose::Slides;
using namespace Aspose::Slides::Export;
auto presentation = System::MakeObject<Presentation>(u"sample.pptx");
auto firstShape = presentation->get_Slide(0)->get_Shape(0);
auto autoShape = System::ExplicitCast<IAutoShape>(firstShape);
auto paragraph = autoShape->get_TextFrame()->get_Paragraph(0);
auto portions = paragraph->get_Portions();
int portionCount = portions->get_Count();
auto font = System::MakeObject<FontData>(u"Times New Roman");
for (int portionIndex = 0; portionIndex < portionCount; portionIndex++)
{
auto portion = paragraph->get_Portion(portionIndex);
auto portionFormat = portion->get_PortionFormat();
if (portionFormat->GetEffective()->get_FontBold())
{
// Establecer las propiedades de la fuente para la porción de texto.
portionFormat->set_FontHeight(13.0f);
portionFormat->set_FontItalic(NullableBool::True);
portionFormat->set_FontUnderline(TextUnderlineType::Dotted);
portionFormat->set_LatinFont(font);
}
}
presentation->Save(u"font_properties_for_text_portions.pptx", SaveFormat::Pptx);
presentation->Dispose();
El resultado:

Establecer rotación del texto
Utilice ITextFrameFormat::set_TextVerticalType para establecer una orientación de texto predefinida dentro de una forma.
El siguiente ejemplo de código establece la orientación del texto en la forma a TextVerticalType::Vertical270, que rota el texto 90 grados en sentido antihorario:
#include <DOM/IAutoShape.h>
#include <DOM/ISlide.h>
#include <DOM/ITextFrame.h>
#include <DOM/ITextFrameFormat.h>
#include <DOM/Presentation.h>
#include <DOM/TextVerticalType.h>
#include <Export/SaveFormat.h>
using namespace Aspose::Slides;
using namespace Aspose::Slides::Export;
auto presentation = System::MakeObject<Presentation>(u"sample.pptx");
auto firstShape = presentation->get_Slide(0)->get_Shape(0);
auto autoShape = System::ExplicitCast<IAutoShape>(firstShape);
autoShape->get_TextFrame()->get_TextFrameFormat()->set_TextVerticalType(TextVerticalType::Vertical270);
presentation->Save(u"text_rotation.pptx", SaveFormat::Pptx);
presentation->Dispose();
El resultado:

Establecer rotación personalizada para marcos de texto
Utilice ITextFrameFormat::set_RotationAngle para establecer un ángulo de rotación personalizado para un ITextFrame.
El siguiente ejemplo de código rota el marco de texto 3 grados en sentido horario dentro de la forma:
#include <DOM/IAutoShape.h>
#include <DOM/ISlide.h>
#include <DOM/ITextFrame.h>
#include <DOM/ITextFrameFormat.h>
#include <DOM/Presentation.h>
#include <Export/SaveFormat.h>
using namespace Aspose::Slides;
using namespace Aspose::Slides::Export;
auto presentation = System::MakeObject<Presentation>(u"sample.pptx");
auto firstShape = presentation->get_Slide(0)->get_Shape(0);
auto autoShape = System::ExplicitCast<IAutoShape>(firstShape);
autoShape->get_TextFrame()->get_TextFrameFormat()->set_RotationAngle(3.0f);
presentation->Save(u"custom_text_rotation.pptx", SaveFormat::Pptx);
presentation->Dispose();
El resultado:

Establecer espaciado entre líneas de los párrafos
Aspose.Slides ofrece IParagraphFormat::set_SpaceAfter, IParagraphFormat::set_SpaceBefore, y IParagraphFormat::set_SpaceWithin para controlar el espaciado entre párrafos. Estos métodos se usan de la siguiente manera:
- Use un valor positivo para especificar el espaciado entre líneas como un porcentaje de la altura de línea.
- Use un valor negativo para especificar el espaciado entre líneas en puntos.
El siguiente ejemplo establece el espaciado dentro del primer párrafo al 200 % de la altura de línea (espaciado doble):
#include <DOM/IAutoShape.h>
#include <DOM/IParagraph.h>
#include <DOM/IParagraphFormat.h>
#include <DOM/ISlide.h>
#include <DOM/ITextFrame.h>
#include <DOM/Presentation.h>
#include <Export/SaveFormat.h>
using namespace Aspose::Slides;
using namespace Aspose::Slides::Export;
auto presentation = System::MakeObject<Presentation>(u"sample.pptx");
auto firstShape = presentation->get_Slide(0)->get_Shape(0);
auto autoShape = System::ExplicitCast<IAutoShape>(firstShape);
auto paragraph = autoShape->get_TextFrame()->get_Paragraph(0);
paragraph->get_ParagraphFormat()->set_SpaceWithin(200.0f);
presentation->Save(u"line_spacing.pptx", SaveFormat::Pptx);
presentation->Dispose();
El resultado:

Controlar la separación de líneas
Las reglas de separación de líneas de párrafo son útiles en bloques de texto estrechos y presentaciones que combinan texto latino y asiático oriental. Los siguientes métodos pertenecen a IParagraphFormat, por lo que se aplican a todo un párrafo:
- IParagraphFormat::set_LatinLineBreak controla las reglas de separación de líneas latinas. En texto mixto, cambiarlo también puede alterar dónde se ajustan el texto asiático oriental adyacente y la puntuación.
- IParagraphFormat::set_EastAsianLineBreak controla las reglas de separación de líneas para el asiático oriental, incluidas las restricciones de caracteres al principio y al final de una línea.
Estas reglas no sustituyen a ITextFrameFormat::set_WrapText, que habilita el ajuste automático dentro de un marco de texto. Influyen en el diseño cuando se produce el ajuste; no insertan caracteres de salto de línea. Un salto de línea explícito fuerza una nueva línea dentro del párrafo independientemente del ancho disponible.
El siguiente ejemplo autocontenido crea un bloque de texto estrecho que contiene chino y texto latino. Establece ambas reglas de separación de líneas explícitamente y guarda “line_breaking.pptx”. Para experimentar con cualquiera de las reglas, cambie el valor pasado a su setter manteniendo las otras configuraciones fijas. El ejemplo utiliza Arial y SimSun de 24 puntos con un ancho de marco de 160 puntos y márgenes horizontales del marco de texto en cero. Se llama a ITextFrameFormat::set_AutofitType con TextAutofitType::None para que el tamaño del texto y las dimensiones del marco permanezcan fijos.
#include <DOM/Fonts/FontData.h>
#include <DOM/IAutoShape.h>
#include <DOM/IColorFormat.h>
#include <DOM/IFillFormat.h>
#include <DOM/IParagraph.h>
#include <DOM/IParagraphFormat.h>
#include <DOM/IPortionFormat.h>
#include <DOM/IShapeCollection.h>
#include <DOM/ISlide.h>
#include <DOM/ITextFrame.h>
#include <DOM/ITextFrameFormat.h>
#include <DOM/FillType.h>
#include <DOM/NullableBool.h>
#include <DOM/Presentation.h>
#include <DOM/ShapeType.h>
#include <DOM/TextAlignment.h>
#include <DOM/TextAutofitType.h>
#include <Export/SaveFormat.h>
#include <drawing/color.h>
using namespace Aspose::Slides;
using namespace Aspose::Slides::Export;
auto presentation = System::MakeObject<Presentation>();
auto slide = presentation->get_Slide(0);
auto shape = slide->get_Shapes()->AddAutoShape(ShapeType::Rectangle, 50.0f, 50.0f, 160.0f, 300.0f);
shape->get_FillFormat()->set_FillType(FillType::NoFill);
auto textFrame = shape->get_TextFrame();
textFrame->get_TextFrameFormat()->set_WrapText(NullableBool::True);
textFrame->get_TextFrameFormat()->set_AutofitType(TextAutofitType::None);
textFrame->get_TextFrameFormat()->set_MarginLeft(0);
textFrame->get_TextFrameFormat()->set_MarginRight(0);
auto paragraph = textFrame->get_Paragraph(0);
paragraph->set_Text(u"中文排版测试,PowerPoint 中文演示。");
auto format = paragraph->get_ParagraphFormat();
format->set_Alignment(TextAlignment::Left);
auto portionFormat = format->get_DefaultPortionFormat();
portionFormat->set_FontHeight(24.0f);
auto latinFont = System::MakeObject<FontData>(u"Arial");
portionFormat->set_LatinFont(latinFont);
auto eastAsianFont = System::MakeObject<FontData>(u"SimSun");
portionFormat->set_EastAsianFont(eastAsianFont);
portionFormat->get_FillFormat()->set_FillType(FillType::Solid);
portionFormat->get_FillFormat()->get_SolidFillColor()->set_Color(System::Drawing::Color::get_Black());
format->set_LatinLineBreak(NullableBool::False);
format->set_EastAsianLineBreak(NullableBool::True);
presentation->Save(u"line_breaking.pptx", SaveFormat::Pptx);
presentation->Dispose();
Controlar puntuación colgante
IParagraphFormat::set_HangingPunctuation permite que la puntuación elegible se extienda más allá del borde derecho de la línea de texto en lugar de ocupar la siguiente línea. Se aplica a todo el párrafo y es diferente de una sangría colgante.
El siguiente ejemplo autocontenido habilita la puntuación colgante en un marco de texto de 100 puntos de ancho y guarda “hanging_punctuation.pptx”. Con Arial de 24 puntos y márgenes horizontales del marco de texto en cero, el punto final permanece después de “sentence” y se extiende más allá del borde derecho del texto. Pase NullableBool::False al setter para comparar: con estas configuraciones, el punto ocupa una línea separada. El ajuste está habilitado y el ajuste automático está desactivado para mantener el ancho disponible fijo.
#include <DOM/Fonts/FontData.h>
#include <DOM/IAutoShape.h>
#include <DOM/IColorFormat.h>
#include <DOM/IFillFormat.h>
#include <DOM/IParagraph.h>
#include <DOM/IParagraphFormat.h>
#include <DOM/IPortionFormat.h>
#include <DOM/IShapeCollection.h>
#include <DOM/ISlide.h>
#include <DOM/ITextFrame.h>
#include <DOM/ITextFrameFormat.h>
#include <DOM/FillType.h>
#include <DOM/NullableBool.h>
#include <DOM/Presentation.h>
#include <DOM/ShapeType.h>
#include <DOM/TextAlignment.h>
#include <DOM/TextAutofitType.h>
#include <Export/SaveFormat.h>
#include <drawing/color.h>
using namespace Aspose::Slides;
using namespace Aspose::Slides::Export;
auto presentation = System::MakeObject<Presentation>();
auto slide = presentation->get_Slide(0);
auto shape = slide->get_Shapes()->AddAutoShape(ShapeType::Rectangle, 50.0f, 50.0f, 100.0f, 200.0f);
shape->get_FillFormat()->set_FillType(FillType::NoFill);
auto textFrame = shape->get_TextFrame();
textFrame->get_TextFrameFormat()->set_WrapText(NullableBool::True);
textFrame->get_TextFrameFormat()->set_AutofitType(TextAutofitType::None);
textFrame->get_TextFrameFormat()->set_MarginLeft(0);
textFrame->get_TextFrameFormat()->set_MarginRight(0);
auto paragraph = textFrame->get_Paragraph(0);
paragraph->set_Text(u"Simple text, next sentence.");
auto format = paragraph->get_ParagraphFormat();
format->set_Alignment(TextAlignment::Left);
auto portionFormat = format->get_DefaultPortionFormat();
portionFormat->set_FontHeight(24.0f);
auto latinFont = System::MakeObject<FontData>(u"Arial");
portionFormat->set_LatinFont(latinFont);
portionFormat->get_FillFormat()->set_FillType(FillType::Solid);
portionFormat->get_FillFormat()->get_SolidFillColor()->set_Color(System::Drawing::Color::get_Black());
format->set_HangingPunctuation(NullableBool::True);
presentation->Save(u"hanging_punctuation.pptx", SaveFormat::Pptx);
presentation->Dispose();
No todos los signos de puntuación pueden colgar. Las condiciones de fuente y diseño descritas arriba también se aplican a esta comparación: cambiar la fuente, el ancho disponible, los márgenes o la configuración de ajuste automático puede eliminar la diferencia visible.
Establecer tipo de ajuste automático para marcos de texto
ITextFrameFormat::set_AutofitType determina cómo se comporta el texto cuando supera los límites de su contenedor. Úselo para controlar si el texto se reduce, desborda o redimensiona la forma automáticamente. El siguiente ejemplo configura la forma para redimensionarse y ajustarse a su texto y guarda el resultado en “autofit_type.pptx”.
#include <DOM/IAutoShape.h>
#include <DOM/ISlide.h>
#include <DOM/ITextFrame.h>
#include <DOM/ITextFrameFormat.h>
#include <DOM/Presentation.h>
#include <DOM/TextAutofitType.h>
#include <Export/SaveFormat.h>
using namespace Aspose::Slides;
using namespace Aspose::Slides::Export;
auto presentation = System::MakeObject<Presentation>(u"sample.pptx");
auto firstShape = presentation->get_Slide(0)->get_Shape(0);
auto autoShape = System::ExplicitCast<IAutoShape>(firstShape);
autoShape->get_TextFrame()->get_TextFrameFormat()->set_AutofitType(TextAutofitType::Shape);
presentation->Save(u"autofit_type.pptx", SaveFormat::Pptx);
presentation->Dispose();
Para contar líneas después del ajuste automático y ver cómo cambia el resultado al variar el ancho del texto o de la forma, consulte Count Rendered Lines. El recuento de líneas por sí solo no indica si el texto desborda su contenedor.
Establecer anclaje de marcos de texto
ITextFrameFormat::set_AnchoringType define cómo se posiciona verticalmente el texto dentro de una forma, por ejemplo, en la parte superior, media o inferior. El siguiente ejemplo ancla el texto a la parte inferior de la primera forma y guarda el resultado en “text_anchor.pptx”.
#include <DOM/IAutoShape.h>
#include <DOM/ISlide.h>
#include <DOM/ITextFrame.h>
#include <DOM/ITextFrameFormat.h>
#include <DOM/Presentation.h>
#include <DOM/TextAnchorType.h>
#include <Export/SaveFormat.h>
using namespace Aspose::Slides;
using namespace Aspose::Slides::Export;
auto presentation = System::MakeObject<Presentation>(u"sample.pptx");
auto firstShape = presentation->get_Slide(0)->get_Shape(0);
auto autoShape = System::ExplicitCast<IAutoShape>(firstShape);
autoShape->get_TextFrame()->get_TextFrameFormat()->set_AnchoringType(TextAnchorType::Bottom);
presentation->Save(u"text_anchor.pptx", SaveFormat::Pptx);
presentation->Dispose();
Establecer tabulación del texto
Utilice IParagraphFormat::set_DefaultTabSize y IParagraphFormat::get_Tabs para configurar los tabuladores en un párrafo. El siguiente ejemplo establece el intervalo de tabulación predeterminado en 100 puntos y añade un tabulador alineado a la izquierda en 30 puntos. Estas configuraciones afectan al texto que contiene caracteres de tabulación.
#include <DOM/IAutoShape.h>
#include <DOM/IParagraph.h>
#include <DOM/IParagraphFormat.h>
#include <DOM/ISlide.h>
#include <DOM/ITabCollection.h>
#include <DOM/ITextFrame.h>
#include <DOM/Presentation.h>
#include <DOM/TabAlignment.h>
#include <Export/SaveFormat.h>
using namespace Aspose::Slides;
using namespace Aspose::Slides::Export;
auto presentation = System::MakeObject<Presentation>(u"sample.pptx");
auto firstShape = presentation->get_Slide(0)->get_Shape(0);
auto autoShape = System::ExplicitCast<IAutoShape>(firstShape);
auto paragraph = autoShape->get_TextFrame()->get_Paragraph(0);
paragraph->get_ParagraphFormat()->set_DefaultTabSize(100.0f);
paragraph->get_ParagraphFormat()->get_Tabs()->Add(30.0f, TabAlignment::Left);
presentation->Save(u"paragraph_tabs.pptx", SaveFormat::Pptx);
presentation->Dispose();
El resultado:

Establecer idioma de revisión
Aspose.Slides proporciona IBasePortionFormat::set_LanguageId, que permite establecer el idioma de revisión para una porción de texto. El idioma de revisión determina el idioma utilizado para la ortografía y la gramática en PowerPoint.
El siguiente ejemplo requiere “presentation.pptx” con un cuadro de texto como primera forma en la primera diapositiva y al menos un párrafo. Reemplaza el contenido del primer párrafo con “1。”, establece SimSun como su fuente y asigna el idioma de revisión chino simplificado (zh-CN). Guarda el resultado en “proofing_language.pptx”:
#include <DOM/Fonts/FontData.h>
#include <DOM/IAutoShape.h>
#include <DOM/IParagraph.h>
#include <DOM/IPortionCollection.h>
#include <DOM/IPortionFormat.h>
#include <DOM/ISlide.h>
#include <DOM/ITextFrame.h>
#include <DOM/Portion.h>
#include <DOM/Presentation.h>
#include <Export/SaveFormat.h>
using namespace Aspose::Slides;
using namespace Aspose::Slides::Export;
auto presentation = System::MakeObject<Presentation>(u"presentation.pptx");
auto firstShape = presentation->get_Slide(0)->get_Shape(0);
auto autoShape = System::ExplicitCast<IAutoShape>(firstShape);
auto paragraph = autoShape->get_TextFrame()->get_Paragraph(0);
paragraph->get_Portions()->Clear();
auto font = System::MakeObject<FontData>(u"SimSun");
auto textPortion = System::MakeObject<Portion>();
auto portionFormat = textPortion->get_PortionFormat();
portionFormat->set_ComplexScriptFont(font);
portionFormat->set_EastAsianFont(font);
portionFormat->set_LatinFont(font);
// Establecer el idioma de revisión a chino simplificado.
portionFormat->set_LanguageId(u"zh-CN");
textPortion->set_Text(u"1。");
paragraph->get_Portions()->Add(textPortion);
presentation->Save(u"proofing_language.pptx", SaveFormat::Pptx);
presentation->Dispose();
Establecer idioma predeterminado
Utilice LoadOptions::set_DefaultTextLanguage para definir el idioma predeterminado del texto creado al cargar o crear una presentación. El siguiente ejemplo crea una presentación con inglés de EE. UU como idioma predeterminado del texto, añade un cuadro de texto y muestra en-US para su primera porción de texto.
#include <DOM/IAutoShape.h>
#include <DOM/IParagraph.h>
#include <DOM/IPortion.h>
#include <DOM/IPortionFormat.h>
#include <DOM/IShapeCollection.h>
#include <DOM/ISlide.h>
#include <DOM/ITextFrame.h>
#include <DOM/LoadOptions.h>
#include <DOM/Presentation.h>
#include <DOM/ShapeType.h>
#include <system/console.h>
using namespace Aspose::Slides;
auto loadOptions = System::MakeObject<LoadOptions>();
loadOptions->set_DefaultTextLanguage(u"en-US");
auto presentation = System::MakeObject<Presentation>(loadOptions);
auto slide = presentation->get_Slide(0);
// Add a new rectangle shape with text.
auto shape = slide->get_Shapes()->AddAutoShape(ShapeType::Rectangle, 20.0f, 20.0f, 150.0f, 50.0f);
shape->get_TextFrame()->set_Text(u"Sample text");
// Check the first portion language.
auto portion = shape->get_TextFrame()->get_Paragraph(0)->get_Portion(0);
auto languageId = portion->get_PortionFormat()->get_LanguageId();
System::Console::WriteLine(languageId);
presentation->Dispose();
Establecer estilo de texto predeterminado
Para aplicar el formato de texto predeterminado a nivel de presentación, utilice IPresentation::get_DefaultTextStyle.
El siguiente ejemplo establece una fuente en negrita de 14 puntos como predeterminada para los párrafos de nivel superior en una nueva presentación y la guarda en “default_text_style.pptx”. El texto puede heredar estos valores predeterminados a menos que un formato más específico los sobrescriba.
#include <DOM/IParagraphFormat.h>
#include <DOM/IPortionFormat.h>
#include <DOM/ITextStyle.h>
#include <DOM/NullableBool.h>
#include <DOM/Presentation.h>
#include <Export/SaveFormat.h>
using namespace Aspose::Slides;
using namespace Aspose::Slides::Export;
auto presentation = System::MakeObject<Presentation>();
// Obtener el formato de párrafo de nivel superior.
auto paragraphFormat = presentation->get_DefaultTextStyle()->GetLevel(0);
if (paragraphFormat != nullptr)
{
auto defaultPortionFormat = paragraphFormat->get_DefaultPortionFormat();
defaultPortionFormat->set_FontHeight(14.0f);
defaultPortionFormat->set_FontBold(NullableBool::True);
}
presentation->Save(u"default_text_style.pptx", SaveFormat::Pptx);
presentation->Dispose();
Extraer texto con el efecto de mayúsculas
En PowerPoint, aplicar el efecto de fuente All Caps hace que el texto aparezca en mayúsculas en la diapositiva aunque originalmente se haya escrito en minúsculas. Cuando se recupera dicha porción de texto con Aspose.Slides, la biblioteca devuelve el texto exactamente como se ingresó. Para que coincida con el texto mostrado, verifique TextCapType y convierta la cadena devuelta a mayúsculas cuando el valor sea TextCapType::All.
Este ejemplo requiere “sample2.pptx” con un cuadro de texto como primera forma en la primera diapositiva. La primera porción del primer párrafo contiene “Hello, Aspose!” con el efecto All Caps aplicado, como se muestra a continuación.

El siguiente ejemplo de código muestra cómo extraer el texto con el efecto All Caps aplicado:
#include <DOM/IAutoShape.h>
#include <DOM/IParagraph.h>
#include <DOM/IPortion.h>
#include <DOM/IPortionFormat.h>
#include <DOM/IPortionFormatEffectiveData.h>
#include <DOM/ISlide.h>
#include <DOM/ITextFrame.h>
#include <DOM/Presentation.h>
#include <DOM/TextCapType.h>
#include <system/console.h>
using namespace Aspose::Slides;
auto presentation = System::MakeObject<Presentation>(u"sample2.pptx");
auto firstShape = presentation->get_Slide(0)->get_Shape(0);
auto autoShape = System::ExplicitCast<IAutoShape>(firstShape);
auto textPortion = autoShape->get_TextFrame()->get_Paragraph(0)->get_Portion(0);
auto originalText = textPortion->get_Text();
System::Console::WriteLine(u"Original text: " + originalText);
auto textFormat = textPortion->get_PortionFormat()->GetEffective();
if (textFormat->get_TextCapType() == TextCapType::All)
{
auto uppercaseText = originalText.ToUpper();
System::Console::WriteLine(u"All-Caps effect: " + uppercaseText);
}
presentation->Dispose();
Salida:
Original text: Hello, Aspose!
All-Caps effect: HELLO, ASPOSE!
FAQ
¿Cómo modifico el texto en una tabla de una diapositiva?
Para modificar el texto en una tabla de una diapositiva, utilice ITable. Recorra las celdas y actualice cada celda mediante ICell::get_TextFrame y el formato de párrafo mediante IParagraph::get_ParagraphFormat.
¿Cómo aplico un color degradado al texto en una diapositiva de PowerPoint?
Para aplicar un color degradado al texto, utilice IBasePortionFormat::get_FillFormat. Establezca IFillFormat::set_FillType a FillType::Gradient y configure los puntos de degradado, la dirección y la transparencia.