Search code examples
google-apps-scriptformattinggoogle-slides

Apps script to format selected text on a Google Slide


I'm trying to create a script to format selected text (selected by the user using a mouse) on a Google Slide. For example, the script might change the selected text to Arial Font, size 11, left aligned.

I know how to create a new menu item to run the script within slides - so I've got that part of the puzzle.

I've tried converting a similar script created for Google Sheets ... but it doesn't seem to work with slides.

This is what I have so far:

function onOpen() {
let ui = SlidesApp.getUi();
ui.createMenu('Macros').addItem('ParagraphFormat', 
'ParagraphFormat').addToUi();  
};

function ParagraphFormat() {
var slide = SlidesApp.getActivePresentation();
slide.getSelection()
.setFontSize(11)
.setFontFamily('Arial');
};

Solution

  • I believe your goal is as follows.

    • You want to change the text style of the selected text in the text box of Google Slides.

    getSelection() returns Class Selection. In this case, there are no methods of setFontSize and setFontFamily. I think that this is the reason for your current issue. When you want to use setFontSize and setFontFamily to the selected text, how about the following modification?

    From:

    slide.getSelection()
    .setFontSize(11)
    .setFontFamily('Arial');
    

    To:

    var textRange = slide.getSelection().getTextRange();
    if (textRange) {
      textRange.getTextStyle().setFontSize(11).setFontFamily('Arial');
    }
    
    • When you use this modification, please select a text in the text box and run the script. By this, setFontSize and setFontFamily are reflected in the selected text.

    References:

    Added:

    About your new question of One more cheeky question: how would I add one more property to align the text to the left? (eg. adding .setTextAlignment('left') ... but this doesn't work), in the current stage, only a part of the text the text in the text box cannot be aligned. So, in this case, the paragraph of the selected text can be aligned. If you want to do this, how about the following sample script?

    var textRange = slide.getSelection().getTextRange();
    if (textRange) {
      textRange.getTextStyle().setFontSize(11).setFontFamily('Arial');
      textRange.getParagraphStyle().setParagraphAlignment(SlidesApp.ParagraphAlignment.START);
    }