텍스트 수정 및 스타일 지정

TextRange 유형으로 표시되는 텍스트 범위를 사용하여 텍스트를 수정하고 스타일을 지정할 수 있습니다. TextRange는 도형 또는 표 셀 내의 텍스트 세그먼트를 나타냅니다. 도형 또는 표 셀에서 getText()를 호출하면 전체 텍스트를 포함하는 텍스트 범위가 반환됩니다.

텍스트가 도형에 들어맞는 방식을 수정하는 메서드를 사용하면 도형에 적용된 자동 맞춤 설정이 비활성화됩니다.

텍스트 범위 사용

텍스트 범위에는 텍스트 범위로 포함되는 텍스트 세그먼트를 구분하는 색인 2개(시작 색인종료 색인)가 있습니다. 이러한 색인은 getStartIndex() 함수와 getEndIndex() 함수를 사용하여 확인할 수 있습니다.

텍스트 범위의 콘텐츠를 읽으려면 asString() 또는 asRenderedString() 함수를 사용합니다.

텍스트 범위 내에서 하위 범위를 검색하려면 getRange() 함수를 사용합니다.

다음 스크립트는 첫 번째 슬라이드에 텍스트 상자를 만들고 텍스트 콘텐츠를 'Hello world!'로 설정합니다. 그런 다음 'Hello'만 포함하는 하위 범위를 검색합니다.

slides/style/style.gs
try {
  // Get the first slide of active presentation
  const slide = SlidesApp.getActivePresentation().getSlides()[0];
  // Insert shape in the slide with dimensions
  const shape = slide.insertShape(SlidesApp.ShapeType.TEXT_BOX, 100, 200, 300, 60);
  const textRange = shape.getText();
  // Set text in TEXT_BOX
  textRange.setText('Hello world!');
  console.log('Start: ' + textRange.getStartIndex() + '; End: ' +
    textRange.getEndIndex() + '; Content: ' + textRange.asString());
  const subRange = textRange.getRange(0, 5);
  console.log('Sub-range Start: ' + subRange.getStartIndex() + '; Sub-range End: ' +
    subRange.getEndIndex() + '; Sub-range Content: ' + subRange.asString());
} catch (err) {
  // TODO (developer) - Handle exception
  console.log('Failed with an error %s ', err.message);
}

도형 또는 표 셀이 반환하는 텍스트 범위는 텍스트를 삽입하고 삭제하더라도 항상 전체 텍스트를 포함합니다. 따라서 위의 예시는 다음과 같은 로그 구문을 생성합니다.

Start: 0; End: 13; Content: Hello world!
Start: 0; End: 5; Content: Hello

텍스트 삽입 및 삭제

텍스트 범위를 사용하여 텍스트 도형 및 표 셀을 삽입하고 삭제할 수도 있습니다.

  • insertText()appendText()를 사용하면 텍스트를 삽입할 수 있습니다.
  • setText()은 텍스트 범위의 텍스트를 제공된 텍스트로 바꿉니다.
  • clear()는 텍스트 범위 내에서 텍스트를 삭제합니다.

다음 스크립트는 이러한 함수의 사용법을 보여줍니다.

slides/style/style.gs
try {
  // Get the first slide of active presentation
  const slide = SlidesApp.getActivePresentation().getSlides()[0];
  // Insert shape in the slide with dimensions
  const shape = slide.insertShape(SlidesApp.ShapeType.TEXT_BOX, 100, 200, 300, 60);
  const textRange = shape.getText();
  textRange.setText('Hello world!');
  textRange.clear(6, 11);
  // Insert text in TEXT_BOX
  textRange.insertText(6, 'galaxy');
  console.log('Start: ' + textRange.getStartIndex() + '; End: ' +
    textRange.getEndIndex() + '; Content: ' + textRange.asString());
} catch (err) {
  // TODO (developer) - Handle exception
  console.log('Failed with an error %s ', err.message);
}

이 스크립트는 첫 번째 슬라이드에 텍스트 상자를 만들고 텍스트 콘텐츠를 'Hello world!'로 설정합니다. 그런 다음 6~11 ('world')을 삭제하고 색인 6에 'galaxy'라는 텍스트를 대신 삽입합니다. 위의 예시는 다음과 같은 로그 구문을 생성합니다.

Start: 0; End: 14; Content: Hello galaxy!

찾기 및 바꾸기

프레젠테이션 또는 페이지에서 replaceAllText() 함수를 사용하여 전체 프레젠테이션 또는 특정 페이지에서 전체 찾기 및 바꾸기를 실행할 수 있습니다.

TextRange의 find() 함수는 범위 내의 문자열 인스턴스를 반환합니다. 도형 또는 표 셀 내에서 찾기 및 바꾸기를 실행하기 위해 setText()와 함께 사용할 수 있습니다.

단락, 목록 항목, 실행

TextRange는 유용한 텍스트 항목 컬렉션을 반환하는 함수를 제공합니다. 이러한 함수에는 다음이 포함됩니다.

  • getParagraphs(), - 텍스트 범위와 겹치는 모든 단락을 제공합니다. 단락은 줄바꿈 문자 '\n'으로 끝나는 텍스트 시퀀스입니다.
  • getListParagraphs(),: 현재 텍스트 범위에 있는 목록 항목을 반환합니다.
  • getRuns(), - 현재 텍스트 범위와 겹치는 텍스트 실행을 제공합니다. 텍스트 런은 모든 문자가 동일한 텍스트 스타일을 갖는 텍스트 세그먼트입니다.

텍스트 스타일 지정

텍스트 스타일은 프레젠테이션에서 글꼴, 색상, 하이퍼링크를 포함한 텍스트 문자의 렌더링을 결정합니다.

텍스트 범위의 getTextStyle() 함수는 텍스트 스타일을 지정하는 데 사용되는 TextStyle 객체를 제공합니다. TextStyle 객체는 상위 TextRange와 동일한 텍스트를 다룹니다.

slides/style/style.gs
try {
  // Get the first slide of active presentation
  const slide = SlidesApp.getActivePresentation().getSlides()[0];
  // Insert shape in the slide with dimensions
  const shape = slide.insertShape(SlidesApp.ShapeType.TEXT_BOX, 100, 200, 300, 60);
  const textRange = shape.getText();
  // Set text in TEXT_BOX
  textRange.setText('Hello ');
  // Append text in TEXT_BOX
  const insertedText = textRange.appendText('world!');
  // Style the text with url,bold
  insertedText.getTextStyle()
      .setBold(true)
      .setLinkUrl('www.example.com')
      .setForegroundColor('#ff0000');
  const helloRange = textRange.getRange(0, 5);
  console.log('Text: ' + helloRange.asString() + '; Bold: ' + helloRange.getTextStyle().isBold());
  console.log('Text: ' + insertedText.asString() + '; Bold: ' +
    insertedText.getTextStyle().isBold());
  console.log('Text: ' + textRange.asString() + '; Bold: ' + textRange.getTextStyle().isBold());
} catch (err) {
  // TODO (developer) - Handle exception
  console.log('Failed with an error %s ', err.message);
}

위의 예에서는 먼저 첫 번째 슬라이드에 텍스트 상자를 만들고 내용을 'Hello '로 설정합니다. 그런 다음 텍스트 'world!'를 추가합니다. 새로 추가된 텍스트는 굵게 표시되고 www.example.com에 연결되며 색상은 빨간색으로 설정됩니다.

스타일을 읽을 때 범위에 스타일 값이 여러 개 있으면 이 함수는 null을 반환합니다. 따라서 위 샘플은 다음과 같은 로그 구문을 생성합니다.

Text: Hello; Bold: false
Text: world!; Bold: true
Text: Hello world!; Bold: null

텍스트에 적용할 수 있는 다른 스타일이 많이 있습니다. 자세한 내용은 TextStyle 참조 문서에서 확인할 수 있습니다.

단락 스타일 지정

단락 스타일은 전체 단락에 적용되며 텍스트 정렬 및 줄 간격 등을 포함합니다. TextRange의 getParagraphStyle() 함수는 상위 텍스트 범위와 겹치는 모든 단락의 스타일을 지정하는 ParagraphStyle 객체를 제공합니다.

다음 예에서는 네 개의 단락이 있는 첫 번째 슬라이드에 텍스트 상자를 만든 후 처음 세 단락을 가운데에 맞춥니다.

slides/style/style.gs
try {
  // Get the first slide of active presentation
  const slide = SlidesApp.getActivePresentation().getSlides()[0];
  // Insert shape in the slide with dimensions
  const shape = slide.insertShape(SlidesApp.ShapeType.TEXT_BOX, 50, 50, 300, 300);
  const textRange = shape.getText();
  // Set the text in the shape/TEXT_BOX
  textRange.setText('Paragraph 1\nParagraph2\nParagraph 3\nParagraph 4');
  const paragraphs = textRange.getParagraphs();
  // Style the paragraph alignment center.
  for (let i = 0; i <= 3; i++) {
    const paragraphStyle = paragraphs[i].getRange().getParagraphStyle();
    paragraphStyle.setParagraphAlignment(SlidesApp.ParagraphAlignment.CENTER);
  }
} catch (err) {
  // TODO (developer) - Handle exception
  console.log('Failed with an error %s ', err.message);
}

목록 스타일 지정

ParagraphStyle와 마찬가지로 ListStyle도 상위 텍스트 범위와 겹치는 모든 단락의 스타일을 지정하는 데 사용할 수 있습니다.

slides/style/style.gs
try {
  // Get the first slide of active presentation
  const slide = SlidesApp.getActivePresentation().getSlides()[0];
  // Insert shape in the slide with dimensions
  const shape = slide.insertShape(SlidesApp.ShapeType.TEXT_BOX, 50, 50, 300, 300);
  // Add and style the list
  const textRange = shape.getText();
  textRange.appendText('Item 1\n')
      .appendText('\tItem 2\n')
      .appendText('\t\tItem 3\n')
      .appendText('Item 4');
  // Preset patterns of glyphs for lists in text.
  textRange.getListStyle().applyListPreset(SlidesApp.ListPreset.DIGIT_ALPHA_ROMAN);
  const paragraphs = textRange.getParagraphs();
  for (let i = 0; i < paragraphs.length; i++) {
    const listStyle = paragraphs[i].getRange().getListStyle();
    console.log('Paragraph ' + (i + 1) + '\'s nesting level: ' + listStyle.getNestingLevel());
  }
} catch (err) {
  // TODO (developer) - Handle exception
  console.log('Failed with an error %s ', err.message);
}

위의 예에서는 첫 번째 슬라이드에 네 개의 단락을 포함하는 텍스트 상자를 만듭니다. 두 번째 단락은 한 번 들여쓰기하고 세 번째 단락은 두 번 들여쓰기합니다. 그런 다음 목록 사전 설정을 모든 단락에 적용합니다. 마지막으로 각 단락의 중첩 수준이 로깅됩니다. 단락의 중첩 수준은 단락 텍스트 앞에 있는 탭 수에서 가져옵니다. 따라서 위의 스크립트는 다음과 같은 로그 구문을 생성합니다.

Paragraph 1's nesting level: 0
Paragraph 2's nesting level: 1
Paragraph 3's nesting level: 2
Paragraph 4's nesting level: 0