Append text with a different style to the end

49 views
Skip to first unread message

Miss Adorable

unread,
Mar 11, 2024, 8:46:51 PM3/11/24
to Google Apps Script Community
Hello! I want to programmatically insert these two consecutive words in TextBox in Google Slides colored differently. I know how to append paragraphs with different styles (I use the code below to do this task):

const firstSlide = presentation.getSlides()[0]
const textBox = firstSlide.insertTextBox("first")
textBox.getText().appendParagraph("second")
textBox.getText().getParagraphs()[0].getRange().getTextStyle().setBackgroundColor(100, 100, 0)

But how to do the same with text? I don't want two words to be on different lines.

DME

unread,
Mar 14, 2024, 4:42:39 AM3/14/24
to google-apps-sc...@googlegroups.com

To insert two consecutive words in a TextBox in Google Slides with different text styles (such as different colors), you can use the insertText method along with the TextRange class to apply different styles to different parts of the text. Here's how you can do it:

javascript
function insertColoredWords() { // Get the presentation const presentation = SlidesApp.getActivePresentation(); // Get the first slide const firstSlide = presentation.getSlides()[0]; // Insert a TextBox const textBox = firstSlide.insertTextBox("first"); // Get the text range of the TextBox const textRange = textBox.getText(); // Insert the first word with the desired style textRange.insertText("first", 0); textRange.getRange(0, 5).getTextStyle().setForegroundColor(255, 0, 0); // Set color to red // Insert the second word with a different style textRange.insertText("second", 5); // Insert after the first word textRange.getRange(5, 11).getTextStyle().setForegroundColor(0, 0, 255); // Set color to blue }

In this code:

  • We insert the first word ("first") at index 0.
  • Then, we set the text color of the first word to red using the getTextStyle() method on the range from index 0 to 5 (exclusive).
  • Next, we insert the second word ("second") at index 5 (after the first word).
  • Finally, we set the text color of the second word to blue using the getTextStyle() method on the range from index 5 to 11 (exclusive).

This way, both words will appear consecutively in the TextBox with different text colors. Adjust the colors and other styles as needed.


--
You received this message because you are subscribed to the Google Groups "Google Apps Script Community" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-apps-script-c...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-apps-script-community/9f093f3f-d8c4-40a9-b433-973aa2978fd0n%40googlegroups.com.


--

Miss Adorable

unread,
Mar 15, 2024, 6:31:08 PM3/15/24
to Google Apps Script Community
Problem has been solved, thanks. :)
Reply all
Reply to author
Forward
0 new messages