Gerenciar parágrafos de texto do PowerPoint em PHP
Visão geral
Aspose.Slides for PHP via Java representa o texto como uma hierarquia de quadros de texto, parágrafos e porções:
- TextFrame representa o contêiner de texto em uma forma e fornece acesso à sua coleção de parágrafos.
- Paragraph representa um parágrafo em um quadro de texto e fornece acesso às suas porções e à formatação em nível de parágrafo.
- Portion representa uma sequência de texto dentro de um parágrafo. Cada porção pode ter seu próprio texto e formatação em nível de caractere.
Um parágrafo, portanto, pode conter texto com diferentes fontes, cores, tamanhos e outras formatações usando várias porções.
Criar e formatar parágrafos
Criar parágrafos com múltiplas porções
As etapas a seguir criam um quadro de texto com três parágrafos, cada um contendo três porções:
- Crie uma instância da classe Presentation.
- Acesse o slide relevante pelo seu índice.
- Adicione um AutoShape retangular ao slide.
- Acesse o TextFrame da forma.
- Utilize o parágrafo padrão e adicione mais dois objetos Paragraph ao quadro de texto.
- Adicione objetos Portion suficientes para que cada parágrafo contenha três porções. O parágrafo padrão já contém uma porção vazia.
- Defina o texto de cada porção.
- Aplique formatação em nível de caractere através de Portion::getPortionFormat.
- Salve a apresentação modificada.
Este exemplo em PHP implementa as etapas:
use aspose\slides\FillType;
use aspose\slides\NullableBool;
use aspose\slides\Paragraph;
use aspose\slides\Portion;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
use aspose\slides\ShapeType;
$presentation = new Presentation();
try {
$slide = $presentation->getSlides()->get_Item(0);
$shape = $slide->getShapes()->addAutoShape(ShapeType::Rectangle, 50, 150, 300, 150);
$textFrame = $shape->getTextFrame();
$firstParagraph = $textFrame->getParagraphs()->get_Item(0);
$firstParagraph->getPortions()->add(new Portion());
$firstParagraph->getPortions()->add(new Portion());
$secondParagraph = new Paragraph();
$secondParagraph->getPortions()->add(new Portion());
$secondParagraph->getPortions()->add(new Portion());
$secondParagraph->getPortions()->add(new Portion());
$textFrame->getParagraphs()->add($secondParagraph);
$thirdParagraph = new Paragraph();
$thirdParagraph->getPortions()->add(new Portion());
$thirdParagraph->getPortions()->add(new Portion());
$thirdParagraph->getPortions()->add(new Portion());
$textFrame->getParagraphs()->add($thirdParagraph);
$paragraphCount = java_values($textFrame->getParagraphs()->getCount());
for ($paragraphIndex = 0; $paragraphIndex < $paragraphCount; $paragraphIndex++) {
$paragraph = $textFrame->getParagraphs()->get_Item($paragraphIndex);
$portionCount = java_values($paragraph->getPortions()->getCount());
for ($portionIndex = 0; $portionIndex < $portionCount; $portionIndex++) {
$portion = $paragraph->getPortions()->get_Item($portionIndex);
$portion->setText("Portion " . ($paragraphIndex + 1) . "." . ($portionIndex + 1));
if ($portionIndex == 0) {
$portion->getPortionFormat()->getFillFormat()->setFillType(FillType::Solid);
$portion->getPortionFormat()->getFillFormat()->getSolidFillColor()->setColor(java("java.awt.Color")->RED);
$portion->getPortionFormat()->setFontBold(NullableBool::True);
$portion->getPortionFormat()->setFontHeight(15);
} else if ($portionIndex == 1) {
$portion->getPortionFormat()->getFillFormat()->setFillType(FillType::Solid);
$portion->getPortionFormat()->getFillFormat()->getSolidFillColor()->setColor(java("java.awt.Color")->BLUE);
$portion->getPortionFormat()->setFontItalic(NullableBool::True);
$portion->getPortionFormat()->setFontHeight(18);
}
}
}
$presentation->save("paragraphs_with_portions.pptx", SaveFormat::Pptx);
} finally {
$presentation->dispose();
}
Criar listas com marcadores e numeradas
Criar uma lista com marcadores ou numerada
Marcadores e numeração facilitam a visualização de itens relacionados. No Aspose.Slides, as configurações de lista são definidas através de BulletFormat.
- Crie uma instância da classe Presentation.
- Acesse o slide relevante pelo seu índice.
- Adicione um AutoShape ao slide selecionado.
- Acesse o TextFrame da forma.
- Remova o parágrafo padrão do quadro de texto.
- Crie um Paragraph para um marcador de símbolo.
- Defina BulletFormat::setType como BulletType::Symbol e especifique o caractere do marcador.
- Defina o texto do parágrafo, recuo, cor do marcador e altura do marcador.
- Adicione o parágrafo ao quadro de texto.
- Crie um segundo parágrafo e defina BulletFormat::setType como BulletType::Numbered.
- Configure o estilo do marcador numerado e adicione o parágrafo ao quadro de texto.
- Salve a apresentação.
Este exemplo em PHP cria um marcador de símbolo e um marcador numerado:
use aspose\slides\BulletType;
use aspose\slides\ColorType;
use aspose\slides\NullableBool;
use aspose\slides\NumberedBulletStyle;
use aspose\slides\Paragraph;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
use aspose\slides\ShapeType;
$presentation = new Presentation();
try {
$slide = $presentation->getSlides()->get_Item(0);
$shape = $slide->getShapes()->addAutoShape(ShapeType::Rectangle, 200, 200, 400, 200);
$textFrame = $shape->getTextFrame();
$textFrame->getParagraphs()->clear();
$symbolParagraph = new Paragraph();
$symbolParagraph->setText("Welcome to Aspose.Slides");
$symbolParagraph->getParagraphFormat()->getBullet()->setType(BulletType::Symbol);
$symbolParagraph->getParagraphFormat()->getBullet()->setChar("•");
$symbolParagraph->getParagraphFormat()->setIndent(25);
$symbolParagraph->getParagraphFormat()->getBullet()->getColor()->setColorType(ColorType::RGB);
$symbolParagraph->getParagraphFormat()->getBullet()->getColor()->setColor(java("java.awt.Color")->BLACK);
$symbolParagraph->getParagraphFormat()->getBullet()->setBulletHardColor(NullableBool::True);
$symbolParagraph->getParagraphFormat()->getBullet()->setHeight(100);
$textFrame->getParagraphs()->add($symbolParagraph);
$numberedParagraph = new Paragraph();
$numberedParagraph->setText("This is a numbered item");
$numberedParagraph->getParagraphFormat()->getBullet()->setType(BulletType::Numbered);
$numberedParagraph->getParagraphFormat()->getBullet()->setNumberedBulletStyle(NumberedBulletStyle::BulletCircleNumWDBlackPlain);
$numberedParagraph->getParagraphFormat()->setIndent(25);
$numberedParagraph->getParagraphFormat()->getBullet()->getColor()->setColorType(ColorType::RGB);
$numberedParagraph->getParagraphFormat()->getBullet()->getColor()->setColor(java("java.awt.Color")->BLACK);
$numberedParagraph->getParagraphFormat()->getBullet()->setBulletHardColor(NullableBool::True);
$numberedParagraph->getParagraphFormat()->getBullet()->setHeight(100);
$textFrame->getParagraphs()->add($numberedParagraph);
$presentation->save("bulleted_and_numbered_list.pptx", SaveFormat::Pptx);
} finally {
$presentation->dispose();
}
Usar marcadores de imagem
Marcadores de imagem permitem usar uma imagem personalizada em vez de um símbolo ou número.
- Crie uma instância da classe Presentation.
- Acesse o slide relevante pelo seu índice.
- Adicione um AutoShape e acesse seu TextFrame.
- Remova o parágrafo padrão do quadro de texto.
- Carregue a imagem do marcador e adicione-a à coleção de imagens da apresentação como PPImage.
- Crie um Paragraph e defina seu texto.
- Defina BulletFormat::setType como BulletType::Picture.
- Atribua a imagem através de BulletFormat::getPicture e defina a altura do marcador.
- Adicione o parágrafo ao quadro de texto.
- Salve a apresentação modificada.
Este exemplo em PHP cria um marcador de imagem:
use aspose\slides\BulletType;
use aspose\slides\Images;
use aspose\slides\Paragraph;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
use aspose\slides\ShapeType;
$presentation = new Presentation();
try {
$slide = $presentation->getSlides()->get_Item(0);
$bulletImage = Images::fromFile("bullets.png");
try {
$presentationImage = $presentation->getImages()->addImage($bulletImage);
} finally {
$bulletImage->dispose();
}
$shape = $slide->getShapes()->addAutoShape(ShapeType::Rectangle, 200, 200, 400, 200);
$textFrame = $shape->getTextFrame();
$textFrame->getParagraphs()->clear();
$paragraph = new Paragraph();
$paragraph->setText("Welcome to Aspose.Slides");
$paragraph->getParagraphFormat()->getBullet()->setType(BulletType::Picture);
$paragraph->getParagraphFormat()->getBullet()->getPicture()->setImage($presentationImage);
$paragraph->getParagraphFormat()->getBullet()->setHeight(100);
$textFrame->getParagraphs()->add($paragraph);
$presentation->save("picture_bullet.pptx", SaveFormat::Pptx);
$presentation->save("picture_bullet.ppt", SaveFormat::Ppt);
} finally {
$presentation->dispose();
}
Criar uma lista multinível
Defina ParagraphFormat::setDepth para posicionar parágrafos em diferentes níveis de uma lista. O nível superior tem profundidade 0.
- Crie uma Presentation e acesse um slide.
- Adicione um AutoShape e limpe o parágrafo padrão de seu quadro de texto.
- Crie quatro parágrafos e configure seus símbolos de marcador.
- Defina seus valores ParagraphFormat::setDepth para
0,1,2e3. - Adicione os parágrafos ao quadro de texto e salve a apresentação.
Este exemplo em PHP cria uma lista com quatro níveis de marcadores:
use aspose\slides\BulletType;
use aspose\slides\FillType;
use aspose\slides\Paragraph;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
use aspose\slides\ShapeType;
$presentation = new Presentation();
try {
$slide = $presentation->getSlides()->get_Item(0);
$shape = $slide->getShapes()->addAutoShape(ShapeType::Rectangle, 200, 200, 400, 200);
$textFrame = $shape->getTextFrame();
$textFrame->getParagraphs()->clear();
$firstParagraph = new Paragraph();
$firstParagraph->setText("Content");
$firstParagraph->getParagraphFormat()->getBullet()->setType(BulletType::Symbol);
$firstParagraph->getParagraphFormat()->getBullet()->setChar("•");
$firstParagraph->getParagraphFormat()->getDefaultPortionFormat()->getFillFormat()->setFillType(FillType::Solid);
$firstParagraph->getParagraphFormat()->getDefaultPortionFormat()->getFillFormat()->getSolidFillColor()->setColor(java("java.awt.Color")->BLACK);
$firstParagraph->getParagraphFormat()->setDepth(0);
$secondParagraph = new Paragraph();
$secondParagraph->setText("Second level");
$secondParagraph->getParagraphFormat()->getBullet()->setType(BulletType::Symbol);
$secondParagraph->getParagraphFormat()->getBullet()->setChar('-');
$secondParagraph->getParagraphFormat()->getDefaultPortionFormat()->getFillFormat()->setFillType(FillType::Solid);
$secondParagraph->getParagraphFormat()->getDefaultPortionFormat()->getFillFormat()->getSolidFillColor()->setColor(java("java.awt.Color")->BLACK);
$secondParagraph->getParagraphFormat()->setDepth(1);
$thirdParagraph = new Paragraph();
$thirdParagraph->setText("Third level");
$thirdParagraph->getParagraphFormat()->getBullet()->setType(BulletType::Symbol);
$thirdParagraph->getParagraphFormat()->getBullet()->setChar("•");
$thirdParagraph->getParagraphFormat()->getDefaultPortionFormat()->getFillFormat()->setFillType(FillType::Solid);
$thirdParagraph->getParagraphFormat()->getDefaultPortionFormat()->getFillFormat()->getSolidFillColor()->setColor(java("java.awt.Color")->BLACK);
$thirdParagraph->getParagraphFormat()->setDepth(2);
$fourthParagraph = new Paragraph();
$fourthParagraph->setText("Fourth level");
$fourthParagraph->getParagraphFormat()->getBullet()->setType(BulletType::Symbol);
$fourthParagraph->getParagraphFormat()->getBullet()->setChar('-');
$fourthParagraph->getParagraphFormat()->getDefaultPortionFormat()->getFillFormat()->setFillType(FillType::Solid);
$fourthParagraph->getParagraphFormat()->getDefaultPortionFormat()->getFillFormat()->getSolidFillColor()->setColor(java("java.awt.Color")->BLACK);
$fourthParagraph->getParagraphFormat()->setDepth(3);
$textFrame->getParagraphs()->add($firstParagraph);
$textFrame->getParagraphs()->add($secondParagraph);
$textFrame->getParagraphs()->add($thirdParagraph);
$textFrame->getParagraphs()->add($fourthParagraph);
$presentation->save("multilevel_list.pptx", SaveFormat::Pptx);
} finally {
$presentation->dispose();
}
Iniciar itens de lista numerada com valores personalizados
Use BulletFormat::setNumberedBulletStartWith para definir o número inicial exibido para um parágrafo numerado.
- Crie uma Presentation e adicione um AutoShape a um slide.
- Limpe o parágrafo padrão do quadro de texto da forma.
- Crie três parágrafos numerados.
- Defina BulletFormat::setNumberedBulletStartWith como
2,3e7para os respectivos parágrafos. - Adicione os parágrafos ao quadro de texto e salve a apresentação.
Este exemplo em PHP atribui um número inicial personalizado a cada parágrafo:
use aspose\slides\BulletType;
use aspose\slides\Paragraph;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
use aspose\slides\ShapeType;
$presentation = new Presentation();
try {
$shape = $presentation->getSlides()->get_Item(0)->getShapes()->addAutoShape(ShapeType::Rectangle, 200, 200, 400, 200);
$textFrame = $shape->getTextFrame();
$textFrame->getParagraphs()->clear();
$firstParagraph = new Paragraph();
$firstParagraph->setText("Start at 2");
$firstParagraph->getParagraphFormat()->getBullet()->setType(BulletType::Numbered);
$firstParagraph->getParagraphFormat()->getBullet()->setNumberedBulletStartWith(2);
$textFrame->getParagraphs()->add($firstParagraph);
$secondParagraph = new Paragraph();
$secondParagraph->setText("Start at 3");
$secondParagraph->getParagraphFormat()->getBullet()->setType(BulletType::Numbered);
$secondParagraph->getParagraphFormat()->getBullet()->setNumberedBulletStartWith(3);
$textFrame->getParagraphs()->add($secondParagraph);
$thirdParagraph = new Paragraph();
$thirdParagraph->setText("Start at 7");
$thirdParagraph->getParagraphFormat()->getBullet()->setType(BulletType::Numbered);
$thirdParagraph->getParagraphFormat()->getBullet()->setNumberedBulletStartWith(7);
$textFrame->getParagraphs()->add($thirdParagraph);
$presentation->save("custom_numbered_list.pptx", SaveFormat::Pptx);
} finally {
$presentation->dispose();
}
Controlar layout de parágrafo e propriedades de fim
Definir recuo da primeira linha
Use ParagraphFormat::setIndent para controlar o recuo da primeira linha de um parágrafo. Este método move apenas a primeira linha em relação à margem esquerda do parágrafo. Um valor positivo desloca a primeira linha para a direita, enquanto as linhas restantes permanecem alinhadas ao corpo do parágrafo.
Use ParagraphFormat::setMarginLeft quando precisar mover todo o parágrafo. Use ParagraphFormat::setIndent quando precisar mover apenas a primeira linha.
O exemplo abaixo cria vários parágrafos e define diferentes valores ParagraphFormat::setIndent para demonstrar como o recuo da primeira linha afeta o layout do parágrafo.
- Crie uma instância da classe Presentation.
- Acesse o slide de destino.
- Adicione um AutoShape retangular ao slide.
- Acesse o TextFrame da forma e remova o parágrafo padrão.
- Crie vários parágrafos e defina diferentes valores ParagraphFormat::setIndent para eles.
- Adicione os parágrafos ao quadro de texto.
- Salve a apresentação modificada.
Este código PHP mostra como definir um recuo de parágrafo:
use aspose\slides\FillType;
use aspose\slides\Paragraph;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
use aspose\slides\ShapeType;
use aspose\slides\TextAutofitType;
$presentation = new Presentation();
try {
$slide = $presentation->getSlides()->get_Item(0);
$shape = $slide->getShapes()->addAutoShape(ShapeType::Rectangle, 50, 50, 420, 220);
$shape->getFillFormat()->setFillType(FillType::NoFill);
$shape->getLineFormat()->getFillFormat()->setFillType(FillType::Solid);
$shape->getLineFormat()->getFillFormat()->getSolidFillColor()->setColor(java("java.awt.Color")->GRAY);
$textFrame = $shape->getTextFrame();
$textFrame->getTextFrameFormat()->setAutofitType(TextAutofitType::Shape);
$textFrame->getParagraphs()->clear();
$firstParagraph = new Paragraph();
$firstParagraph->setText("No first-line indent. Wrapped lines start at the same position as the first line.");
$firstParagraph->getParagraphFormat()->getDefaultPortionFormat()->getFillFormat()->setFillType(FillType::Solid);
$firstParagraph->getParagraphFormat()->getDefaultPortionFormat()->getFillFormat()->getSolidFillColor()->setColor(java("java.awt.Color")->BLACK);
$firstParagraph->getParagraphFormat()->setMarginLeft(20.0);
$firstParagraph->getParagraphFormat()->setIndent(0.0);
$secondParagraph = new Paragraph();
$secondParagraph->setText("First-line indent of 20 points. The first line moves to the right, while wrapped lines remain aligned to the paragraph body.");
$secondParagraph->getParagraphFormat()->getDefaultPortionFormat()->getFillFormat()->setFillType(FillType::Solid);
$secondParagraph->getParagraphFormat()->getDefaultPortionFormat()->getFillFormat()->getSolidFillColor()->setColor(java("java.awt.Color")->BLACK);
$secondParagraph->getParagraphFormat()->setMarginLeft(20.0);
$secondParagraph->getParagraphFormat()->setIndent(20.0);
$thirdParagraph = new Paragraph();
$thirdParagraph->setText("First-line indent of 40 points. This paragraph shows a larger first-line offset to make the effect easier to see.");
$thirdParagraph->getParagraphFormat()->getDefaultPortionFormat()->getFillFormat()->setFillType(FillType::Solid);
$thirdParagraph->getParagraphFormat()->getDefaultPortionFormat()->getFillFormat()->getSolidFillColor()->setColor(java("java.awt.Color")->BLACK);
$thirdParagraph->getParagraphFormat()->setMarginLeft(20.0);
$thirdParagraph->getParagraphFormat()->setIndent(40.0);
$textFrame->getParagraphs()->add($firstParagraph);
$textFrame->getParagraphs()->add($secondParagraph);
$textFrame->getParagraphs()->add($thirdParagraph);
$presentation->save("paragraph_indent.pptx", SaveFormat::Pptx);
} finally {
$presentation->dispose();
}
O resultado:

Definir recuo suspenso
Um recuo suspenso é um layout de parágrafo no qual a primeira linha começa à esquerda das linhas restantes. No Aspose.Slides, você cria esse efeito com ParagraphFormat::setIndent. Passe um valor negativo para mover a primeira linha para a esquerda em relação ao corpo do parágrafo.
Na prática, ParagraphFormat::setMarginLeft define a posição esquerda do corpo do parágrafo, e ParagraphFormat::setIndent define a posição da primeira linha em relação a essa margem. Para criar um recuo suspenso, passe um valor positivo para setMarginLeft e um valor negativo para setIndent.
Essa formatação é útil para bibliografias, referências, entradas de glossário e outros parágrafos onde as linhas com quebra devem se alinhar sob o corpo do parágrafo em vez de sob o primeiro caractere da primeira linha.
- Crie uma instância da classe Presentation.
- Acesse o slide de destino.
- Adicione um AutoShape retangular ao slide.
- Acesse o TextFrame da forma e remova o parágrafo padrão.
- Crie parágrafos e passe um valor positivo para ParagraphFormat::setMarginLeft para cada parágrafo.
- Passe um valor negativo para ParagraphFormat::setIndent para criar o efeito de recuo suspenso.
- Adicione os parágrafos ao quadro de texto.
- Salve a apresentação modificada.
Este código PHP mostra como definir um recuo suspenso para um parágrafo:
use aspose\slides\FillType;
use aspose\slides\Paragraph;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
use aspose\slides\ShapeType;
use aspose\slides\TextAutofitType;
$presentation = new Presentation();
try {
$slide = $presentation->getSlides()->get_Item(0);
$shape = $slide->getShapes()->addAutoShape(ShapeType::Rectangle, 50, 50, 420, 220);
$shape->getFillFormat()->setFillType(FillType::NoFill);
$shape->getLineFormat()->getFillFormat()->setFillType(FillType::Solid);
$shape->getLineFormat()->getFillFormat()->getSolidFillColor()->setColor(java("java.awt.Color")->GRAY);
$textFrame = $shape->getTextFrame();
$textFrame->getTextFrameFormat()->setAutofitType(TextAutofitType::Shape);
$textFrame->getParagraphs()->clear();
$firstParagraph = new Paragraph();
$firstParagraph->setText("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->getParagraphFormat()->getDefaultPortionFormat()->getFillFormat()->setFillType(FillType::Solid);
$firstParagraph->getParagraphFormat()->getDefaultPortionFormat()->getFillFormat()->getSolidFillColor()->setColor(java("java.awt.Color")->BLACK);
$firstParagraph->getParagraphFormat()->setMarginLeft(40.0);
$firstParagraph->getParagraphFormat()->setIndent(-20.0);
$secondParagraph = new Paragraph();
$secondParagraph->setText("This second example uses a deeper hanging indent so the difference between the first line and the wrapped lines is easier to compare.");
$secondParagraph->getParagraphFormat()->getDefaultPortionFormat()->getFillFormat()->setFillType(FillType::Solid);
$secondParagraph->getParagraphFormat()->getDefaultPortionFormat()->getFillFormat()->getSolidFillColor()->setColor(java("java.awt.Color")->BLACK);
$secondParagraph->getParagraphFormat()->setMarginLeft(60.0);
$secondParagraph->getParagraphFormat()->setIndent(-30.0);
$textFrame->getParagraphs()->add($firstParagraph);
$textFrame->getParagraphs()->add($secondParagraph);
$presentation->save("hanging_indent.pptx", SaveFormat::Pptx);
} finally {
$presentation->dispose();
}
O resultado:

Definir propriedades de execução do final do parágrafo
Paragraph::setEndParagraphPortionFormat controla a formatação da marca de final de parágrafo. O exemplo em PHP a seguir atribui um tamanho de fonte e uma fonte latina à marca de final do segundo parágrafo:
- Carregue uma Presentation e acesse um slide.
- Adicione um AutoShape e limpe seu parágrafo padrão.
- Crie dois parágrafos e adicione porções de texto a eles.
- Crie um PortionFormat para a marca de final do segundo parágrafo.
- Defina BasePortionFormat::setFontHeight e BasePortionFormat::setLatinFont.
- Atribua o formato com Paragraph::setEndParagraphPortionFormat e salve a apresentação.
use aspose\slides\FontData;
use aspose\slides\Paragraph;
use aspose\slides\Portion;
use aspose\slides\PortionFormat;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
use aspose\slides\ShapeType;
$presentation = new Presentation("Test.pptx");
try {
$slide = $presentation->getSlides()->get_Item(0);
$shape = $slide->getShapes()->addAutoShape(ShapeType::Rectangle, 10, 10, 200, 250);
$textFrame = $shape->getTextFrame();
$textFrame->getParagraphs()->clear();
$firstParagraph = new Paragraph();
$firstParagraph->getPortions()->add(new Portion("Sample text"));
$secondParagraph = new Paragraph();
$secondParagraph->getPortions()->add(new Portion("Sample text 2"));
$endParagraphFormat = new PortionFormat();
$endParagraphFormat->setFontHeight(48);
$endParagraphFormat->setLatinFont(new FontData("Times New Roman"));
$secondParagraph->setEndParagraphPortionFormat($endParagraphFormat);
$textFrame->getParagraphs()->add($firstParagraph);
$textFrame->getParagraphs()->add($secondParagraph);
$presentation->save("end_paragraph_format.pptx", SaveFormat::Pptx);
} finally {
$presentation->dispose();
}
Contar linhas renderizadas
Para regras de parágrafo que afetam a quebra automática e a pontuação no fim das linhas, veja Control Line Breaking e Control Hanging Punctuation.
Use Paragraph::getLinesCount para contar as linhas ocupadas por um parágrafo após o layout do texto, incluindo a quebra automática. Isso é útil ao verificar o comprimento do texto e o layout em modelos de apresentação.
Um parágrafo é um item em TextFrame::getParagraphs, e pode ocupar várias linhas renderizadas. Uma quebra de linha explícita dentro de um parágrafo força uma nova linha sem criar outro parágrafo. A quebra automática cria linhas com base na largura disponível sem inserir quebras explícitas no texto. Contar parágrafos ou caracteres de quebra de linha, portanto, não fornece a contagem de linhas renderizadas.
O exemplo a seguir cria uma forma de texto, conta suas linhas, estreita a forma e, em seguida, substitui o texto por uma cadeia mais curta. A quebra automática está ativada e o ajuste automático está desativado para que a largura da forma controle a quebra sem reduzir automaticamente o texto ou redimensionar a forma. As dimensões da forma são em pontos. Por fim, o exemplo adiciona outro parágrafo e soma as contagens de linhas em todo o quadro de texto.
use aspose\slides\NullableBool;
use aspose\slides\Paragraph;
use aspose\slides\Presentation;
use aspose\slides\ShapeType;
use aspose\slides\TextAutofitType;
$presentation = new Presentation();
try {
$slide = $presentation->getSlides()->get_Item(0);
$shape = $slide->getShapes()->addAutoShape(ShapeType::Rectangle, 50, 50, 400, 200);
$textFrame = $shape->getTextFrame();
$textFrame->getTextFrameFormat()->setWrapText(NullableBool::True);
$textFrame->getTextFrameFormat()->setAutofitType(TextAutofitType::None);
$paragraph = $textFrame->getParagraphs()->get_Item(0);
$paragraph->getParagraphFormat()->getDefaultPortionFormat()->setFontHeight(20);
$paragraph->setText("This text demonstrates how automatic wrapping changes the number of rendered lines.");
echo "Original width: " . java_values($paragraph->getLinesCount()) . PHP_EOL;
$shape->setWidth(150);
echo "Narrower shape: " . java_values($paragraph->getLinesCount()) . PHP_EOL;
$paragraph->setText("Short text.");
echo "Shorter text: " . java_values($paragraph->getLinesCount()) . PHP_EOL;
$secondParagraph = new Paragraph();
$secondParagraph->setText("Another paragraph.");
$secondParagraph->getParagraphFormat()->getDefaultPortionFormat()->setFontHeight(20);
$textFrame->getParagraphs()->add($secondParagraph);
$totalLineCount = 0;
for ($i = 0; $i < java_values($textFrame->getParagraphs()->getCount()); $i++) {
$currentParagraph = $textFrame->getParagraphs()->get_Item($i);
$totalLineCount += java_values($currentParagraph->getLinesCount());
}
echo "Total lines in the text frame: " . $totalLineCount . PHP_EOL;
} finally {
$presentation->dispose();
}
Com este texto e estas dimensões, estreitar a forma aumenta a contagem de linhas, enquanto substituir o texto pela cadeia curta a reduz. Contagens exatas podem variar conforme a disponibilidade e substituição de fontes, tamanho da fonte, margens, recuo, quebra automática e configurações de ajuste automático. Use as fontes e as configurações de layout previstas para o ambiente de destino ao verificar um modelo.
A apenas a contagem de linhas não determina se o texto transborda seu contêiner. A altura disponível, as alturas das linhas, o espaçamento entre parágrafos e linhas e o comportamento de ajuste automático também são importantes; até uma única linha pode exceder a largura disponível quando a quebra automática está desativada.
Importar e exportar conteúdo de parágrafo
Importar texto HTML para parágrafos
Use ParagraphCollection::addFromHtml para converter marcação HTML em parágrafos e porções em um quadro de texto.
- Crie uma instância da classe Presentation.
- Acesse um slide e adicione um AutoShape.
- Acesse o TextFrame da forma e limpe seu parágrafo padrão.
- Leia o arquivo HTML de origem.
- Passe a string HTML para ParagraphCollection::addFromHtml.
- Salve a apresentação modificada.
Este exemplo em PHP importa HTML para um quadro de texto:
use aspose\slides\FillType;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
use aspose\slides\ShapeType;
$presentation = new Presentation();
try {
$slide = $presentation->getSlides()->get_Item(0);
$shapeWidth = java_values($presentation->getSlideSize()->getSize()->getWidth()) - 20;
$shapeHeight = java_values($presentation->getSlideSize()->getSize()->getHeight()) - 20;
$shape = $slide->getShapes()->addAutoShape(ShapeType::Rectangle, 10, 10, $shapeWidth, $shapeHeight);
$shape->getFillFormat()->setFillType(FillType::NoFill);
$shape->getTextFrame()->getParagraphs()->clear();
$html = file_get_contents("file.html");
if ($html !== false) {
$shape->getTextFrame()->getParagraphs()->addFromHtml($html);
$presentation->save("html_text.pptx", SaveFormat::Pptx);
} else {
echo "The HTML file could not be read.";
}
} finally {
$presentation->dispose();
}
Exportar texto de parágrafo para HTML
Use ParagraphCollection::exportToHtml para exportar um intervalo selecionado de parágrafos como HTML.
- Crie uma instância da Presentation e carregue a apresentação desejada.
- Acesse o slide e encontre o AutoShape que contém o texto.
- Acesse o TextFrame.
- Chame ParagraphCollection::exportToHtml com o índice de parágrafo inicial e o número de parágrafos a exportar.
- Grave a string HTML retornada em um arquivo.
Este exemplo em PHP exporta todos os parágrafos do primeiro quadro de texto:
use aspose\slides\Presentation;
$presentation = new Presentation("ExportingHTMLText.pptx");
try {
$shape = $presentation->getSlides()->get_Item(0)->getShapes()->get_Item(0);
if (java_instanceof($shape, new JavaClass("com.aspose.slides.AutoShape"))) {
$textFrame = $shape->getTextFrame();
if (!java_is_null($textFrame)) {
$paragraphs = $textFrame->getParagraphs();
$html = $paragraphs->exportToHtml(0, $paragraphs->getCount(), null);
if (file_put_contents("paragraphs.html", $html) === false) {
echo "The HTML file could not be written.";
}
} else {
echo "The first shape does not contain a text frame.";
}
} else {
echo "The first shape is not a text shape.";
}
} finally {
$presentation->dispose();
}
Renderizar um parágrafo como imagem
Paragraph::getImage renderiza diretamente um parágrafo individual e retorna um IImage. Salve o resultado em um arquivo ou fluxo com IImage::save. Você não precisa renderizar a forma que contém o texto nem recortar um bitmap manualmente.
Paragraph::getImage pode retornar null se o parágrafo não for encontrado na coleção pai, não possuir limites de renderização válidos ou não puder ser renderizado. Verifique o resultado antes de salvá‑lo e libere a imagem retornada após o uso.
Renderizar um parágrafo na escala padrão
Vamos supor que temos um arquivo de apresentação chamado sample.pptx com um slide, onde a primeira forma é uma caixa de texto contendo três parágrafos.

O exemplo PHP a seguir renderiza o segundo parágrafo em uma forma de texto regular na escala padrão e salva a imagem retornada em formato PNG. O bloco finally garante que a imagem seja liberada corretamente.
use aspose\slides\ImageFormat;
use aspose\slides\Presentation;
$presentation = new Presentation("sample.pptx");
try {
$shape = $presentation->getSlides()->get_Item(0)->getShapes()->get_Item(0);
if (java_instanceof($shape, new JavaClass("com.aspose.slides.AutoShape"))) {
$textFrame = $shape->getTextFrame();
if (!java_is_null($textFrame) && java_values($textFrame->getParagraphs()->getCount()) > 1) {
$paragraph = $textFrame->getParagraphs()->get_Item(1);
$paragraphImage = $paragraph->getImage();
if (!java_is_null($paragraphImage)) {
try {
$paragraphImage->save("paragraph.png", ImageFormat::Png);
} finally {
$paragraphImage->dispose();
}
} else {
echo "The paragraph could not be rendered.";
}
} else {
echo "The expected paragraph was not found.";
}
} else {
echo "The first shape is not a text shape.";
}
} finally {
$presentation->dispose();
}
O resultado:

Renderizar um parágrafo em uma célula de tabela com escala
Use a sobrecarga Paragraph::getImage que aceita os parâmetros $scaleX e $scaleY para definir os fatores de escala horizontal e vertical. O exemplo PHP a seguir cria uma tabela, renderiza o parágrafo em sua primeira célula com o dobro da largura e altura padrão e salva o resultado como uma imagem PNG.
use aspose\slides\ImageFormat;
use aspose\slides\Presentation;
$scaleX = 2;
$scaleY = 2;
$presentation = new Presentation();
try {
$slide = $presentation->getSlides()->get_Item(0);
$table = $slide->getShapes()->addTable(50, 50, array(300), array(80));
$paragraph = $table->get_Item(0, 0)->getTextFrame()->getParagraphs()->get_Item(0);
$paragraph->setText("Text in a table cell");
$paragraphImage = $paragraph->getImage($scaleX, $scaleY);
if (!java_is_null($paragraphImage)) {
try {
$paragraphImage->save("table_paragraph.png", ImageFormat::Png);
} finally {
$paragraphImage->dispose();
}
} else {
echo "The paragraph could not be rendered.";
}
} finally {
$presentation->dispose();
}
Um fator de escala 1 mantém esse eixo em seu tamanho de pixel padrão. Por exemplo, 2 para ambos os fatores produz uma imagem cuja largura e altura são aproximadamente o dobro das dimensões padrão, resultando em quatro vezes mais pixels. Fatores maiores geralmente produzem texto mais nítido para zoom ou saída de alta resolução, mas também aumentam o uso de memória e o tamanho do arquivo. Fatores abaixo de 1 produzem imagens menores com menos detalhe. Use fatores iguais para preservar a proporção do parágrafo; fatores diferentes horizontal e vertical esticam a saída independentemente.
Renderizar uma forma inteira com Shape::getImage continua útil quando a saída deve incluir o preenchimento, a borda ou outro contexto visual da forma. Para uma imagem contendo apenas o parágrafo, use Paragraph::getImage.
FAQ
Posso desativar completamente a quebra automática de linhas dentro de um quadro de texto?
Sim. Defina TextFrameFormat::setWrapText para desativar a quebra, de modo que as linhas não se interrompam nas bordas do quadro de texto.
Como posso obter as dimensões exatas na lâmina de um parágrafo específico?
Use Paragraph::getRect para recuperar o retângulo delimitador do parágrafo. Portion::getRect fornece os limites de uma porção individual.
Onde o alinhamento de parágrafo (esquerda, direita, centralizado ou justificado) é controlado?
ParagraphFormat::setAlignment é uma configuração em nível de parágrafo e se aplica a todo o parágrafo independentemente da formatação de porções individuais.
Para alinhar verticalmente porções com tamanhos de fonte diferentes dentro de cada linha, veja Align Fonts Within a Line.
Posso definir o idioma de revisão para parte de um parágrafo?
Sim. Defina BasePortionFormat::setLanguageId para porções individuais, de modo que um parágrafo possa conter texto em vários idiomas.