在 JavaScript 中管理 PowerPoint 文字段落

概觀

Aspose.Slides for Node.js via Java 以文字框、段落和文字片段的層次結構來表示文字:

  • TextFrame 代表形狀中的文字容器,並提供存取其段落集合的功能。
  • Paragraph 代表文字框中的一個段落,並提供存取其文字片段及段落層級格式設定的功能。
  • Portion 代表段落內的一段文字執行。每個文字片段可以擁有自己的文字與字元層級格式設定。

因此,一個段落可以透過使用多個文字片段,以不同的字型、顏色、大小與其他格式來呈現文字。

建立與格式化段落

在形狀的文字框中建立段落,並使用文字片段來格式化個別的文字執行。本節說明如何在每個段落內結合多個文字片段,並套用不同的顏色、字型大小與樣式。

建立含多個文字片段的段落

下列 JavaScript 範例建立三個段落,每個段落在由 Paragraph.getPortions 回傳的集合中包含三個文字執行。它重新使用預設段落及其空白文字片段,然後加入其餘的段落與文字片段。格式化透過 Portion.getPortionFormat 套用:每個段落的第一個文字片段為紅色、粗體、15 點;第二個為藍色、斜體、18 點;第三個保留預設格式:

var aspose = aspose || {};
aspose.slides = require("aspose.slides.via.java");
const java = require("java");

const presentation = new aspose.slides.Presentation();
try {
    const slide = presentation.getSlides().get_Item(0);

    const shape = slide.getShapes().addAutoShape(aspose.slides.ShapeType.Rectangle, 50, 150, 300, 150);
    const textFrame = shape.getTextFrame();

    const firstParagraph = textFrame.getParagraphs().get_Item(0);
    firstParagraph.getPortions().add(new aspose.slides.Portion());
    firstParagraph.getPortions().add(new aspose.slides.Portion());

    const secondParagraph = new aspose.slides.Paragraph();
    secondParagraph.getPortions().add(new aspose.slides.Portion());
    secondParagraph.getPortions().add(new aspose.slides.Portion());
    secondParagraph.getPortions().add(new aspose.slides.Portion());
    textFrame.getParagraphs().add(secondParagraph);

    const thirdParagraph = new aspose.slides.Paragraph();
    thirdParagraph.getPortions().add(new aspose.slides.Portion());
    thirdParagraph.getPortions().add(new aspose.slides.Portion());
    thirdParagraph.getPortions().add(new aspose.slides.Portion());
    textFrame.getParagraphs().add(thirdParagraph);

    const paragraphCount = textFrame.getParagraphs().getCount();
    for (let paragraphIndex = 0; paragraphIndex < paragraphCount; paragraphIndex++) {
        const paragraph = textFrame.getParagraphs().get_Item(paragraphIndex);
        const portionCount = paragraph.getPortions().getCount();
        for (let portionIndex = 0; portionIndex < portionCount; portionIndex++) {
            const portion = paragraph.getPortions().get_Item(portionIndex);
            portion.setText("Portion " + (paragraphIndex + 1) + "." + (portionIndex + 1));

            if (portionIndex === 0) {
                portion.getPortionFormat().getFillFormat().setFillType(java.newByte(aspose.slides.FillType.Solid));
                portion.getPortionFormat().getFillFormat().getSolidFillColor().setColor(java.getStaticFieldValue("java.awt.Color", "RED"));
                portion.getPortionFormat().setFontBold(java.newByte(aspose.slides.NullableBool.True));
                portion.getPortionFormat().setFontHeight(15);
            } else if (portionIndex === 1) {
                portion.getPortionFormat().getFillFormat().setFillType(java.newByte(aspose.slides.FillType.Solid));
                portion.getPortionFormat().getFillFormat().getSolidFillColor().setColor(java.getStaticFieldValue("java.awt.Color", "BLUE"));
                portion.getPortionFormat().setFontItalic(java.newByte(aspose.slides.NullableBool.True));
                portion.getPortionFormat().setFontHeight(18);
            }
        }
    }

    presentation.save("paragraphs_with_portions.pptx", aspose.slides.SaveFormat.Pptx);
} finally {
    presentation.dispose();
}

建立項目符號與編號清單

將段落文字組織成符號、編號或自訂圖片的清單。本節的範例涵蓋項目符號格式、多層清單與自訂起始編號。

建立項目符號或編號清單

項目符號與編號讓相關項目更易於掃描。在 Aspose.Slides 中,清單設定透過 BulletFormat 定義。

此 JavaScript 範例在同一文字框中加入符號項目符號與編號項目。BulletFormat.setType 用於選取項目類型,而 BulletFormat.setChar 提供符號,BulletFormat.setNumberedBulletStyle 選擇編號樣式。兩個項目皆使用黑色項目,高度為 100%,段落縮排為 25 點:

var aspose = aspose || {};
aspose.slides = require("aspose.slides.via.java");
const java = require("java");

const presentation = new aspose.slides.Presentation();
try {
    const slide = presentation.getSlides().get_Item(0);

    const shape = slide.getShapes().addAutoShape(aspose.slides.ShapeType.Rectangle, 200, 200, 400, 200);
    const textFrame = shape.getTextFrame();
    textFrame.getParagraphs().clear();

    const symbolParagraph = new aspose.slides.Paragraph();
    symbolParagraph.setText("Welcome to Aspose.Slides");
    symbolParagraph.getParagraphFormat().getBullet().setType(java.newByte(aspose.slides.BulletType.Symbol));
    symbolParagraph.getParagraphFormat().getBullet().setChar(java.newChar(0x2022));
    symbolParagraph.getParagraphFormat().setIndent(25);
    symbolParagraph.getParagraphFormat().getBullet().getColor().setColorType(aspose.slides.ColorType.RGB);
    symbolParagraph.getParagraphFormat().getBullet().getColor().setColor(java.getStaticFieldValue("java.awt.Color", "BLACK"));
    symbolParagraph.getParagraphFormat().getBullet().setBulletHardColor(java.newByte(aspose.slides.NullableBool.True));
    symbolParagraph.getParagraphFormat().getBullet().setHeight(100);
    textFrame.getParagraphs().add(symbolParagraph);

    const numberedParagraph = new aspose.slides.Paragraph();
    numberedParagraph.setText("This is a numbered item");
    numberedParagraph.getParagraphFormat().getBullet().setType(java.newByte(aspose.slides.BulletType.Numbered));
    numberedParagraph.getParagraphFormat().getBullet().setNumberedBulletStyle(java.newByte(aspose.slides.NumberedBulletStyle.BulletCircleNumWDBlackPlain));
    numberedParagraph.getParagraphFormat().setIndent(25);
    numberedParagraph.getParagraphFormat().getBullet().getColor().setColorType(aspose.slides.ColorType.RGB);
    numberedParagraph.getParagraphFormat().getBullet().getColor().setColor(java.getStaticFieldValue("java.awt.Color", "BLACK"));
    numberedParagraph.getParagraphFormat().getBullet().setBulletHardColor(java.newByte(aspose.slides.NullableBool.True));
    numberedParagraph.getParagraphFormat().getBullet().setHeight(100);
    textFrame.getParagraphs().add(numberedParagraph);

    presentation.save("bulleted_and_numbered_list.pptx", aspose.slides.SaveFormat.Pptx);
} finally {
    presentation.dispose();
}

使用圖片項目符號

圖片項目符號讓您可以使用自訂圖片取代符號或編號。

此 JavaScript 範例從應用程式的工作目錄載入 image.png,將圖片以 PPImage 加入投影片的圖片集合,並將其用作段落的項目符號。它呼叫 BulletFormat.setType 設為圖片項目,並透過 BulletFormat.getPicture 指定圖片。BulletFormat.setHeight 設為 100% 以相對於段落文字調整項目大小:

var aspose = aspose || {};
aspose.slides = require("aspose.slides.via.java");
const java = require("java");

const presentation = new aspose.slides.Presentation();
try {
    const slide = presentation.getSlides().get_Item(0);

    const bulletImage = aspose.slides.Images.fromFile("image.png");
    let presentationImage;
    try {
        presentationImage = presentation.getImages().addImage(bulletImage);
    } finally {
        bulletImage.dispose();
    }

    const shape = slide.getShapes().addAutoShape(aspose.slides.ShapeType.Rectangle, 200, 200, 400, 200);
    const textFrame = shape.getTextFrame();
    textFrame.getParagraphs().clear();

    const paragraph = new aspose.slides.Paragraph();
    paragraph.setText("Welcome to Aspose.Slides");
    paragraph.getParagraphFormat().getBullet().setType(java.newByte(aspose.slides.BulletType.Picture));
    paragraph.getParagraphFormat().getBullet().getPicture().setImage(presentationImage);
    paragraph.getParagraphFormat().getBullet().setHeight(100);
    textFrame.getParagraphs().add(paragraph);

    presentation.save("picture_bullet.pptx", aspose.slides.SaveFormat.Pptx);
    presentation.save("picture_bullet.ppt", aspose.slides.SaveFormat.Ppt);
} finally {
    presentation.dispose();
}

建立多層清單

設定 ParagraphFormat.setDepth 以將段落放置在清單的不同層級。最高層的深度為 0。

此 JavaScript 範例將 ParagraphFormat.setDepth 的值從 0 到 3 指派給四個段落,於同一文字框內建立層級結構。每個段落使用符號項目符號,透過 BulletFormat.setChar 在圓形項目與破折號之間交替,以區分相鄰層級:

var aspose = aspose || {};
aspose.slides = require("aspose.slides.via.java");
const java = require("java");

const presentation = new aspose.slides.Presentation();
try {
    const slide = presentation.getSlides().get_Item(0);

    const shape = slide.getShapes().addAutoShape(aspose.slides.ShapeType.Rectangle, 200, 200, 400, 200);
    const textFrame = shape.getTextFrame();
    textFrame.getParagraphs().clear();

    const firstParagraph = new aspose.slides.Paragraph();
    firstParagraph.setText("Content");
    firstParagraph.getParagraphFormat().getBullet().setType(java.newByte(aspose.slides.BulletType.Symbol));
    firstParagraph.getParagraphFormat().getBullet().setChar(java.newChar(0x2022));
    firstParagraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().setFillType(java.newByte(aspose.slides.FillType.Solid));
    firstParagraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().getSolidFillColor().setColor(java.getStaticFieldValue("java.awt.Color", "BLACK"));
    firstParagraph.getParagraphFormat().setDepth(java.newShort(0));

    const secondParagraph = new aspose.slides.Paragraph();
    secondParagraph.setText("Second level");
    secondParagraph.getParagraphFormat().getBullet().setType(java.newByte(aspose.slides.BulletType.Symbol));
    secondParagraph.getParagraphFormat().getBullet().setChar(java.newChar(45));
    secondParagraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().setFillType(java.newByte(aspose.slides.FillType.Solid));
    secondParagraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().getSolidFillColor().setColor(java.getStaticFieldValue("java.awt.Color", "BLACK"));
    secondParagraph.getParagraphFormat().setDepth(java.newShort(1));

    const thirdParagraph = new aspose.slides.Paragraph();
    thirdParagraph.setText("Third level");
    thirdParagraph.getParagraphFormat().getBullet().setType(java.newByte(aspose.slides.BulletType.Symbol));
    thirdParagraph.getParagraphFormat().getBullet().setChar(java.newChar(0x2022));
    thirdParagraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().setFillType(java.newByte(aspose.slides.FillType.Solid));
    thirdParagraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().getSolidFillColor().setColor(java.getStaticFieldValue("java.awt.Color", "BLACK"));
    thirdParagraph.getParagraphFormat().setDepth(java.newShort(2));

    const fourthParagraph = new aspose.slides.Paragraph();
    fourthParagraph.setText("Fourth level");
    fourthParagraph.getParagraphFormat().getBullet().setType(java.newByte(aspose.slides.BulletType.Symbol));
    fourthParagraph.getParagraphFormat().getBullet().setChar(java.newChar(45));
    fourthParagraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().setFillType(java.newByte(aspose.slides.FillType.Solid));
    fourthParagraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().getSolidFillColor().setColor(java.getStaticFieldValue("java.awt.Color", "BLACK"));
    fourthParagraph.getParagraphFormat().setDepth(java.newShort(3));

    textFrame.getParagraphs().add(firstParagraph);
    textFrame.getParagraphs().add(secondParagraph);
    textFrame.getParagraphs().add(thirdParagraph);
    textFrame.getParagraphs().add(fourthParagraph);

    presentation.save("multilevel_list.pptx", aspose.slides.SaveFormat.Pptx);
} finally {
    presentation.dispose();
}

以自訂值開始編號清單項目

使用 BulletFormat.setNumberedBulletStartWith 設定編號段落的起始編號。

此 JavaScript 範例將 BulletFormat.setType 設為編號,並分別為三個段落指定 BulletFormat.setNumberedBulletStartWith 為 2、3、7。每個段落的起始值獨立設定,使顯示的編號可以跳過數字:

var aspose = aspose || {};
aspose.slides = require("aspose.slides.via.java");
const java = require("java");

const presentation = new aspose.slides.Presentation();
try {
    const slide = presentation.getSlides().get_Item(0);

    const shape = slide.getShapes().addAutoShape(aspose.slides.ShapeType.Rectangle, 200, 200, 400, 200);
    const textFrame = shape.getTextFrame();
    textFrame.getParagraphs().clear();

    const firstParagraph = new aspose.slides.Paragraph();
    firstParagraph.setText("Start at 2");
    firstParagraph.getParagraphFormat().getBullet().setType(java.newByte(aspose.slides.BulletType.Numbered));
    firstParagraph.getParagraphFormat().getBullet().setNumberedBulletStartWith(java.newShort(2));
    textFrame.getParagraphs().add(firstParagraph);

    const secondParagraph = new aspose.slides.Paragraph();
    secondParagraph.setText("Start at 3");
    secondParagraph.getParagraphFormat().getBullet().setType(java.newByte(aspose.slides.BulletType.Numbered));
    secondParagraph.getParagraphFormat().getBullet().setNumberedBulletStartWith(java.newShort(3));
    textFrame.getParagraphs().add(secondParagraph);

    const thirdParagraph = new aspose.slides.Paragraph();
    thirdParagraph.setText("Start at 7");
    thirdParagraph.getParagraphFormat().getBullet().setType(java.newByte(aspose.slides.BulletType.Numbered));
    thirdParagraph.getParagraphFormat().getBullet().setNumberedBulletStartWith(java.newShort(7));
    textFrame.getParagraphs().add(thirdParagraph);

    presentation.save("custom_numbered_list.pptx", aspose.slides.SaveFormat.Pptx);
} finally {
    presentation.dispose();
}

控制段落版面與結尾屬性

調整段落的邊距與縮排,以控制第一行與換行後的行位置。您亦可將段落結尾標記的格式與可見文字片段分開設定。

設定首行縮排

使用 ParagraphFormat.setIndent 方法控制段落的首行縮排。此設定僅移動第一行相對於段落左邊距的位置。正值會將第一行向右移,而其餘行保持與段落本體對齊。

需要移動整個段落時,使用 ParagraphFormat.setMarginLeft;只要移動首行時,使用 ParagraphFormat.setIndent。

以下範例為三個段落設定相同的 ParagraphFormat.setMarginLeft 為 20 點,並分別給予 ParagraphFormat.setIndent 0、20、40 點。首行的起始位置逐漸向右偏移,而換行後的行仍使用相同的左邊距:

var aspose = aspose || {};
aspose.slides = require("aspose.slides.via.java");
const java = require("java");

const presentation = new aspose.slides.Presentation();
try {
    const slide = presentation.getSlides().get_Item(0);

    const shape = slide.getShapes().addAutoShape(aspose.slides.ShapeType.Rectangle, 50, 50, 420, 220);
    shape.getFillFormat().setFillType(java.newByte(aspose.slides.FillType.NoFill));
    shape.getLineFormat().getFillFormat().setFillType(java.newByte(aspose.slides.FillType.Solid));
    shape.getLineFormat().getFillFormat().getSolidFillColor().setColor(java.getStaticFieldValue("java.awt.Color", "GRAY"));

    const textFrame = shape.getTextFrame();
    textFrame.getTextFrameFormat().setAutofitType(java.newByte(aspose.slides.TextAutofitType.Shape));
    textFrame.getParagraphs().clear();

    const firstParagraph = new aspose.slides.Paragraph();
    firstParagraph.setText("No first-line indent. Wrapped lines start at the same position as the first line.");
    firstParagraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().setFillType(java.newByte(aspose.slides.FillType.Solid));
    firstParagraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().getSolidFillColor().setColor(java.getStaticFieldValue("java.awt.Color", "BLACK"));
    firstParagraph.getParagraphFormat().setMarginLeft(20);
    firstParagraph.getParagraphFormat().setIndent(0);

    const secondParagraph = new aspose.slides.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(java.newByte(aspose.slides.FillType.Solid));
    secondParagraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().getSolidFillColor().setColor(java.getStaticFieldValue("java.awt.Color", "BLACK"));
    secondParagraph.getParagraphFormat().setMarginLeft(20);
    secondParagraph.getParagraphFormat().setIndent(20);

    const thirdParagraph = new aspose.slides.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(java.newByte(aspose.slides.FillType.Solid));
    thirdParagraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().getSolidFillColor().setColor(java.getStaticFieldValue("java.awt.Color", "BLACK"));
    thirdParagraph.getParagraphFormat().setMarginLeft(20);
    thirdParagraph.getParagraphFormat().setIndent(40);

    textFrame.getParagraphs().add(firstParagraph);
    textFrame.getParagraphs().add(secondParagraph);
    textFrame.getParagraphs().add(thirdParagraph);

    presentation.save("paragraph_indent.pptx", aspose.slides.SaveFormat.Pptx);
} finally {
    presentation.dispose();
}

結果:

段落的首行縮排

設定懸掛縮排

懸掛縮排是一種段落版面配置,讓第一行位於其餘行的左側。於 Aspose.Slides 中,可透過 ParagraphFormat.setIndent 設為負值,將第一行向左移動。

實務上,ParagraphFormat.setMarginLeft 定義段落本體的左側位置,而 ParagraphFormat.setIndent 定義第一行相對於該邊距的位置。要產生懸掛縮排,請設定正的左邊距與負的縮排值。

此格式特別適用於書目、參考文獻、術語表條目等段落,因為換行後的行必須對齊於段落本體,而非第一行的第一個字元。

以下 JavaScript 範例將 ParagraphFormat.setMarginLeft 設為 40 與 60 點,並分別將 ParagraphFormat.setIndent 設為 -20 與 -30 點。每個段落的第一行皆位於換行行的左側;第二個段落的懸掛縮排較深:

var aspose = aspose || {};
aspose.slides = require("aspose.slides.via.java");
const java = require("java");

const presentation = new aspose.slides.Presentation();
try {
    const slide = presentation.getSlides().get_Item(0);

    const shape = slide.getShapes().addAutoShape(aspose.slides.ShapeType.Rectangle, 50, 50, 420, 220);
    shape.getFillFormat().setFillType(java.newByte(aspose.slides.FillType.NoFill));
    shape.getLineFormat().getFillFormat().setFillType(java.newByte(aspose.slides.FillType.Solid));
    shape.getLineFormat().getFillFormat().getSolidFillColor().setColor(java.getStaticFieldValue("java.awt.Color", "GRAY"));

    const textFrame = shape.getTextFrame();
    textFrame.getTextFrameFormat().setAutofitType(java.newByte(aspose.slides.TextAutofitType.Shape));
    textFrame.getParagraphs().clear();

    const firstParagraph = new aspose.slides.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(java.newByte(aspose.slides.FillType.Solid));
    firstParagraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().getSolidFillColor().setColor(java.getStaticFieldValue("java.awt.Color", "BLACK"));
    firstParagraph.getParagraphFormat().setMarginLeft(40);
    firstParagraph.getParagraphFormat().setIndent(-20);

    const secondParagraph = new aspose.slides.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(java.newByte(aspose.slides.FillType.Solid));
    secondParagraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().getSolidFillColor().setColor(java.getStaticFieldValue("java.awt.Color", "BLACK"));
    secondParagraph.getParagraphFormat().setMarginLeft(60);
    secondParagraph.getParagraphFormat().setIndent(-30);

    textFrame.getParagraphs().add(firstParagraph);
    textFrame.getParagraphs().add(secondParagraph);

    presentation.save("hanging_indent.pptx", aspose.slides.SaveFormat.Pptx);
} finally {
    presentation.dispose();
}

結果:

段落的懸掛縮排

設定段落結尾執行屬性

Paragraph.setEndParagraphPortionFormat 方法控制段落結尾標記的格式。以下範例建立一個 PortionFormat ,將 BasePortionFormat.setFontHeight 設為 48 點,且將 BasePortionFormat.setLatinFont 設為 Times New Roman。然後將此格式指派給第二段落的結尾標記,保持可見文字片段不變:

var aspose = aspose || {};
aspose.slides = require("aspose.slides.via.java");

const presentation = new aspose.slides.Presentation();
try {
    const slide = presentation.getSlides().get_Item(0);

    const shape = slide.getShapes().addAutoShape(aspose.slides.ShapeType.Rectangle, 10, 10, 200, 250);
    const textFrame = shape.getTextFrame();
    textFrame.getParagraphs().clear();

    const firstParagraph = new aspose.slides.Paragraph();
    firstParagraph.getPortions().add(new aspose.slides.Portion("Sample text"));

    const secondParagraph = new aspose.slides.Paragraph();
    secondParagraph.getPortions().add(new aspose.slides.Portion("Sample text 2"));

    const endParagraphFormat = new aspose.slides.PortionFormat();
    endParagraphFormat.setFontHeight(48);
    endParagraphFormat.setLatinFont(new aspose.slides.FontData("Times New Roman"));
    secondParagraph.setEndParagraphPortionFormat(endParagraphFormat);

    textFrame.getParagraphs().add(firstParagraph);
    textFrame.getParagraphs().add(secondParagraph);

    presentation.save("end_paragraph_format.pptx", aspose.slides.SaveFormat.Pptx);
} finally {
    presentation.dispose();
}

計算已呈現的行數

有關影響自動換行與行尾標點的段落規則,請參閱 Control Line Breaking 與 Control Hanging Punctuation。

使用 Paragraph.getLinesCount 可計算段落在文字版面配置後佔用的行數,包括自動換行。這在檢查投影片範本中文本長度與版面配置時相當有用。

段落是 TextFrame.getParagraphs 中的一項目,可能佔用多行已呈現的行。段落內的顯式換行會強制產生新行,但不會建立新段落。自動換行則根據可用寬度產生行,而不會在文字中插入顯式換行字元。因此,僅計算段落或換行字元並無法得到已呈現的行數。

以下範例建立文字形狀、計算其行數、縮小形狀,然後將文字換成較短的字串。範例透過 TextFrameFormat.setWrapText 啟用換行,並使用 TextFrameFormat.setAutofitType 停用自動適應,讓形狀寬度控制換行而不會自動縮小文字或調整形狀大小。每次測量皆使用 Paragraph.getLinesCount。形狀尺寸以點為單位。最後,範例再加入另一段落,並將文字框內所有段落的行數相加。

var aspose = aspose || {};
aspose.slides = require("aspose.slides.via.java");
const java = require("java");

const presentation = new aspose.slides.Presentation();
try {
    const slide = presentation.getSlides().get_Item(0);

    const shape = slide.getShapes().addAutoShape(aspose.slides.ShapeType.Rectangle, 50, 50, 400, 200);
    const textFrame = shape.getTextFrame();
    textFrame.getTextFrameFormat().setWrapText(java.newByte(aspose.slides.NullableBool.True));
    textFrame.getTextFrameFormat().setAutofitType(java.newByte(aspose.slides.TextAutofitType.None));

    const 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.");
    console.log("Original width: " + paragraph.getLinesCount());

    shape.setWidth(150);
    console.log("Narrower shape: " + paragraph.getLinesCount());

    paragraph.setText("Short text.");
    console.log("Shorter text: " + paragraph.getLinesCount());

    const secondParagraph = new aspose.slides.Paragraph();
    secondParagraph.setText("Another paragraph.");
    secondParagraph.getParagraphFormat().getDefaultPortionFormat().setFontHeight(20);
    textFrame.getParagraphs().add(secondParagraph);

    let totalLineCount = 0;
    for (let i = 0; i < textFrame.getParagraphs().getCount(); i++) {
        const currentParagraph = textFrame.getParagraphs().get_Item(i);
        totalLineCount += currentParagraph.getLinesCount();
    }
    console.log("Total lines in the text frame: " + totalLineCount);
} finally {
    presentation.dispose();
}

依照此文字與這些尺寸,縮小形狀會增加行數,而將文字換成較短的字串則會減少行數。精確的行數會因字型可用性與替代、字型大小、邊距、縮排、換行與自動適應設定而有所不同;請在檢查範本時使用目標環境的字型與版面設定。

單單行數並不能判斷文字是否超出容器。可用的高度、行高、段落與行間距以及自動適應行為同樣重要;即使只有一行,若未啟用換行,也可能超出可用寬度。

匯入與匯出段落內容

使用 HTML 可將文字匯入投影片,或將既有段落匯出以供外部使用。本節亦說明如何將單一段落渲染為影像,包括表格儲存格中的段落。

將 HTML 文字匯入段落

使用 ParagraphCollection.addFromHtml 將 HTML 標記轉換為文字框中的段落與文字片段。

此 JavaScript 範例從應用程式工作目錄的 file.html 讀取 HTML,並將其傳遞給 ParagraphCollection.addFromHtml。它會清除文字框的預設段落,使框中僅保留匯入的內容。矩形形狀在投影片每側保留 10 點的邊距:

var aspose = aspose || {};
aspose.slides = require("aspose.slides.via.java");
const java = require("java");
const fs = require("fs");

const presentation = new aspose.slides.Presentation();
try {
    const slide = presentation.getSlides().get_Item(0);

    const shapeWidth = presentation.getSlideSize().getSize().getWidth() - 20;
    const shapeHeight = presentation.getSlideSize().getSize().getHeight() - 20;
    const shape = slide.getShapes().addAutoShape(aspose.slides.ShapeType.Rectangle, 10, 10, shapeWidth, shapeHeight);
    shape.getFillFormat().setFillType(java.newByte(aspose.slides.FillType.NoFill));
    shape.getTextFrame().getParagraphs().clear();

    const html = fs.readFileSync("file.html", "utf8");
    shape.getTextFrame().getParagraphs().addFromHtml(html);
    presentation.save("html_text.pptx", aspose.slides.SaveFormat.Pptx);
} finally {
    presentation.dispose();
}

將段落文字匯出為 HTML

使用 ParagraphCollection.exportToHtml 將選取的段落範圍匯出為 HTML。當在網站上重複使用投影片文字時,您可能只想保留局部強調,而不攜帶投影片的字型、大小或文字框樣式。請設定 TextToHtmlConversionOptions.setTextInheritanceLimit 以控制匯出器追蹤格式繼承的深度。

下載 範例投影片 並放置於應用程式工作目錄。其第一張投影片包含一個文字形狀,文字內容為「Inherited text; explicit red 18pt」。輸入故意使用多層格式:

  • 投影片的預設文字樣式提供 Calibri 與 28 pt 大小。
  • 文字框的第一層文字樣式提供藍色文字與斜體。
  • 段落明確設定為粗體。
  • 第二個文字片段「explicit red 18pt」明確設定為紅色文字與 18 pt 大小。

以下完整範例將相同段落匯出三次。它將 TextToHtmlConversionOptions 傳遞給匯出方法,並將每個結果寫入獨立的 UTF-8 HTML 檔案:

var aspose = aspose || {};
aspose.slides = require("aspose.slides.via.java");
const java = require("java");
const fs = require("fs");

const presentation = new aspose.slides.Presentation("text-inheritance.pptx");
try {
    const shape = presentation.getSlides().get_Item(0).getShapes().get_Item(0);

    if (java.instanceOf(shape, "com.aspose.slides.IAutoShape")) {
        const textFrame = shape.getTextFrame();
        if (textFrame !== null) {
            const paragraphs = textFrame.getParagraphs();

            const modes = [aspose.slides.TextInheritanceLimit.All, aspose.slides.TextInheritanceLimit.TextBox, aspose.slides.TextInheritanceLimit.ParagraphOnly];
            const fileNames = ["All.html", "TextBox.html", "ParagraphOnly.html"];

            for (let i = 0; i < modes.length; i++) {
                const options = new aspose.slides.TextToHtmlConversionOptions();
                options.setTextInheritanceLimit(modes[i]);

                const html = paragraphs.exportToHtml(0, paragraphs.getCount(), options);
                fs.writeFileSync(fileNames[i], html, "utf8");
            }
        } else {
            console.log("The first shape does not contain a text frame.");
        }
    } else {
        console.log("The first shape is not a text shape.");
    }
} finally {
    presentation.dispose();
}

產生的 HTML 包含以下 CSS(針對第一個文字片段「Inherited text; 」),表格僅列出相關宣告,為了清晰起見省略其他產生的屬性。

輸出 首段的相關 CSS 外觀
All.html font-family:'Calibri'; font-size:28pt; color:#0000ff; font-style:italic; font-weight:bold 藍色、粗體、斜體文字,28 pt,使用 Calibri(若該字型可用)。
TextBox.html color:#0000ff; font-style:italic; font-weight:bold 藍色、粗體、斜體文字;字型與大小由頁面或瀏覽器提供。
ParagraphOnly.html font-weight:bold 粗體文字;字型、大小、顏色與斜體樣式由頁面或瀏覽器提供。

第二個文字片段在所有三個輸出中都保留 color:#ff0000、font-size:18pt 與 font-weight:bold。它在 All 與 TextBox 中也保留斜體,但在 ParagraphOnly 中不保留。限制繼承因此不會移除明確指派給段落或文字片段的格式。

在同一瀏覽器中開啟檔案以比較。於受限制的兩種模式下,被省略的 CSS 屬性會由目標頁面的樣式或瀏覽器預設決定,最終外觀取決於 HTML 的使用情境。

將匯出的段落儲存為 UTF-8 HTML

TextToHtmlConversionOptions.setEncodingName 設定由 ParagraphCollection.exportToHtml 回傳的 HTML 字串中宣告的字元集。傳遞給 fs.writeFileSync 的編碼決定寫入磁碟的位元組。請同時使用 UTF-8,以確保瀏覽器正確解碼多語言文字。

const slides = require("aspose.slides.via.java");
const fs = require("fs");

const presentation = new slides.Presentation();
try {
    const slide = presentation.getSlides().get_Item(0);
    
    const shape = slide.getShapes().addAutoShape(slides.ShapeType.Rectangle, 0, 0, 400, 100);
    const textFrame = shape.getTextFrame();
    textFrame.setText("Café | Ωω | 日本語 | 😀");

    const options = new slides.TextToHtmlConversionOptions();
    options.setEncodingName("utf-8");
    options.setAddClipboardFragmentHeader(false);

    const paragraphs = textFrame.getParagraphs();
    const html = paragraphs.exportToHtml(0, paragraphs.getCount(), options);
    fs.writeFileSync("paragraphs.html", html, "utf8");
} finally {
    presentation.dispose();
}

儲存的檔案宣告 charset=utf-8,且內容為 UTF-8 位元組。於瀏覽器開啟 paragraphs.html 時會顯示 “Café | Ωω | 日本語 | 😀”。

產生 HTML 剪貼簿片段

使用 TextToHtmlConversionOptions.setAddClipboardFragmentHeader 來選擇 ParagraphCollection.exportToHtml 的輸出。設定為 false 時,方法回傳普通 HTML;設定為 true 時,回傳的字串會以 Windows 剪貼簿標頭開頭。其 StartHTML 與 EndHTML 欄位提供 HTML 的 UTF-8 位元組偏移;StartFragment 與 EndFragment 標示要貼上的內容。

此範例將兩個格式化段落分別以普通 HTML (html) 與 HTML 剪貼簿片段 (clipboardHtml) 匯出。應用程式可將片段寫入系統剪貼簿。若剪貼簿 API 期待原始位元組,請以 UTF-8(不含 BOM)編碼片段。

const slides = require("aspose.slides.via.java");

const presentation = new slides.Presentation();
try {
    const slide = presentation.getSlides().get_Item(0);

    const shape = slide.getShapes().addAutoShape(slides.ShapeType.Rectangle, 0, 0, 400, 100);
    const paragraphs = shape.getTextFrame().getParagraphs();
    paragraphs.clear();
    paragraphs.addFromHtml("<p>Status: <b>Ready</b></p><p><i>Next steps</i></p>");

    const options = new slides.TextToHtmlConversionOptions();
    options.setAddClipboardFragmentHeader(false);
    const html = paragraphs.exportToHtml(0, paragraphs.getCount(), options);

    options.setAddClipboardFragmentHeader(true);
    const clipboardHtml = paragraphs.exportToHtml(0, paragraphs.getCount(), options);
} finally {
    presentation.dispose();
}

將段落渲染為影像

Paragraph.getImage 可直接渲染單一段落,並回傳一個 IImage。使用 IImage.save 將結果儲存至檔案或串流。不需要先渲染包含的形狀或手動裁切位圖。

若段落在父集合中找不到、沒有有效的渲染邊界,或無法渲染,則 Paragraph.getImage 會回傳 null。請在儲存前檢查結果,使用完畢後釋放回傳的影像。

以預設比例渲染段落

此範例建立一個投影片,第一個形狀為包含三個段落的文字方塊。

包含三個段落的文字方塊

以下範例選取索引為 1 的第二段落,呼叫不帶比例參數的 Paragraph.getImage。它先檢查形狀是否包含目標段落,且渲染返回影像後才呼叫 IImage.save 以 PNG 格式儲存。finally 區塊會在使用完畢後釋放影像。

var aspose = aspose || {};
aspose.slides = require("aspose.slides.via.java");
const java = require("java");

const presentation = new aspose.slides.Presentation();
try {
    const slide = presentation.getSlides().get_Item(0);

    const sourceShape = slide.getShapes().addAutoShape(aspose.slides.ShapeType.Rectangle, 20, 20, 400, 100);
    const sourceTextFrame = sourceShape.getTextFrame();
    sourceTextFrame.getParagraphs().clear();
    for (const text of ["First paragraph", "Second paragraph", "Third paragraph"]) {
        const sourceParagraph = new aspose.slides.Paragraph();
        sourceParagraph.setText(text);
        sourceTextFrame.getParagraphs().add(sourceParagraph);
    }
    const shape = slide.getShapes().get_Item(0);

    if (java.instanceOf(shape, "com.aspose.slides.IAutoShape")) {
        const textFrame = shape.getTextFrame();
        if (textFrame !== null && textFrame.getParagraphs().getCount() > 1) {
            const paragraph = textFrame.getParagraphs().get_Item(1);
            const paragraphImage = paragraph.getImage();

            if (paragraphImage !== null) {
                try {
                    paragraphImage.save("paragraph.png", aspose.slides.ImageFormat.Png);
                } finally {
                    paragraphImage.dispose();
                }
            } else {
                console.log("The paragraph could not be rendered.");
            }
        } else {
            console.log("The expected paragraph was not found.");
        }
    } else {
        console.log("The first shape is not a text shape.");
    }
} finally {
    presentation.dispose();
}

結果:

段落影像

在表格儲存格中以縮放比例渲染段落

使用接受 scaleX 與 scaleY 參數的 Paragraph.getImage 重載,以設定水平與垂直的縮放係數。以下範例建立一個表格,於第一個儲存格內將段落渲染為預設寬高的兩倍,並以 PNG 影像儲存。

var aspose = aspose || {};
aspose.slides = require("aspose.slides.via.java");
const java = require("java");

const scaleX = 2;
const scaleY = 2;

const presentation = new aspose.slides.Presentation();
try {
    const slide = presentation.getSlides().get_Item(0);
    
    const columnWidths = java.newArray("double", [300]);
    const rowHeights = java.newArray("double", [80]);
    const table = slide.getShapes().addTable(50, 50, columnWidths, rowHeights);
    const paragraph = table.get_Item(0, 0).getTextFrame().getParagraphs().get_Item(0);
    paragraph.setText("Text in a table cell");

    const paragraphImage = paragraph.getImage(scaleX, scaleY);
    if (paragraphImage !== null) {
        try {
            paragraphImage.save("table_paragraph.png", aspose.slides.ImageFormat.Png);
        } finally {
            paragraphImage.dispose();
        }
    } else {
        console.log("The paragraph could not be rendered.");
    }
} finally {
    presentation.dispose();
}

縮放係數為 1 時,該軸保持預設像素大小。例如,兩個係數皆為 2 時,產生的影像寬度與高度約為預設的兩倍,像素數為原來的四倍。較大的係數通常能在放大或高解析度輸出時提供更銳利的文字,但也會增加記憶體使用與檔案大小。小於 1 的係數會產生較小且細節較少的影像。使用相同係數可維持段落的比例;不同的水平與垂直係數則會分別拉伸輸出。

若需包含形狀的填色、邊框或其他視覺上下文,仍可使用 Shape.getImage 來渲染整個形狀。若僅需段落影像,請使用 Paragraph.getImage。

常見問題

我可以完全停用文字框內的換行嗎?

可以。將 TextFrameFormat.setWrapText 設為停用,即可關閉換行,使行不會在文字框邊緣斷開。

如何取得特定段落在投影片上的精確邊界?

使用 Paragraph.getRect 取得段落的外接矩形。Portion.getRect 則提供單一文字片段的邊界。

段落對齊(左、右、置中或兩端對齊)在哪裡控制?

ParagraphFormat.setAlignment 為段落層級的設定,會套用至整個段落,與個別文字片段的格式無關。

若要在每行內垂直對齊不同字型大小的文字片段,請參閱 Align Fonts Within a Line。

我可以為段落的一部分設定拼寫檢查語言嗎?

可以。為個別文字片段設定 BasePortionFormat.setLanguageId,如此同一段落即可包含多種語言的文字。