고급 문서 서비스

고급 문서 서비스를 사용하면 Apps Script에서 Google Docs API를 사용할 수 있습니다. Apps Script의 기본 제공 문서 서비스와 마찬가지로 이 API를 사용하면 스크립트를 통해 Google Docs에서 콘텐츠를 읽고 수정하고 서식을 지정할 수 있습니다. 대부분의 경우 기본 제공 서비스가 사용하기 더 쉽지만 이 고급 서비스는 몇 가지 추가 기능을 제공합니다.

참조

이 서비스에 대한 자세한 내용은 Docs API의 참조 문서를 확인하세요. Apps Script의 모든 고급 서비스와 마찬가지로 고급 Docs 서비스는 공개 API와 동일한 객체, 메서드, 매개변수를 사용합니다. 자세한 내용은 메서드 서명 확인 방법을 참조하세요.

문제를 신고하고 다른 지원을 받으려면 Docs API 지원 가이드를 참조하세요.

샘플 코드

아래 샘플 코드는 API의 버전 1을 사용합니다.

문서 만들기

이 샘플은 새 문서를 만듭니다.

advanced/docs.gs
/**
 * Create a new document.
 * @see https://developers.google.com/docs/api/reference/rest/v1/documents/create
 * @return {string} documentId
 */
function createDocument() {
  try {
    // Create document with title
    const document = Docs.Documents.create({'title': 'My New Document'});
    console.log('Created document with ID: ' + document.documentId);
    return document.documentId;
  } catch (e) {
    // TODO (developer) - Handle exception
    console.log('Failed with error %s', e.message);
  }
}

텍스트 찾기 및 바꾸기

이 샘플은 문서에서 텍스트 쌍을 찾아 바꿉니다. 이 방법은 템플릿 문서 사본의 자리표시자를 데이터베이스의 값으로 바꿀 때 유용합니다.

advanced/docs.gs
/**
 * Performs "replace all".
 * @param {string} documentId The document to perform the replace text operations on.
 * @param {Object} findTextToReplacementMap A map from the "find text" to the "replace text".
 * @return {Object} replies
 * @see https://developers.google.com/docs/api/reference/rest/v1/documents/batchUpdate
 */
function findAndReplace(documentId, findTextToReplacementMap) {
  const requests = [];
  for (const findText in findTextToReplacementMap) {
    const replaceText = findTextToReplacementMap[findText];
    const request = {
      replaceAllText: {
        containsText: {
          text: findText,
          matchCase: true
        },
        replaceText: replaceText
      }
    };
    requests.push(request);
  }
  try {
    const response = Docs.Documents.batchUpdate({'requests': requests}, documentId);
    const replies = response.replies;
    for (const [index] of replies.entries()) {
      const numReplacements = replies[index].replaceAllText.occurrencesChanged || 0;
      console.log('Request %s performed %s replacements.', index, numReplacements);
    }
    return replies;
  } catch (e) {
    // TODO (developer) - Handle exception
    console.log('Failed with error : %s', e.message);
  }
}

텍스트 삽입 및 스타일 지정

이 샘플은 문서의 시작 부분에 새 텍스트를 삽입하고 특정 글꼴과 크기가 있는 경우 스타일을 삽입합니다. 가능한 경우 효율성을 위해 여러 작업을 단일 batchUpdate 호출로 일괄 처리해야 합니다.

advanced/docs.gs
/**
 * Insert text at the beginning of the document and then style the inserted
 * text.
 * @param {string} documentId The document the text is inserted into.
 * @param {string} text The text to insert into the document.
 * @return {Object} replies
 * @see https://developers.google.com/docs/api/reference/rest/v1/documents/batchUpdate
 */
function insertAndStyleText(documentId, text) {
  const requests = [{
    insertText: {
      location: {
        index: 1
      },
      text: text
    }
  },
  {
    updateTextStyle: {
      range: {
        startIndex: 1,
        endIndex: text.length + 1
      },
      textStyle: {
        fontSize: {
          magnitude: 12,
          unit: 'PT'
        },
        weightedFontFamily: {
          fontFamily: 'Calibri'
        }
      },
      fields: 'weightedFontFamily, fontSize'
    }
  }];
  try {
    const response =Docs.Documents.batchUpdate({'requests': requests}, documentId);
    return response.replies;
  } catch (e) {
    // TODO (developer) - Handle exception
    console.log('Failed with an error %s', e.message);
  }
}

첫 번째 단락 읽기

이 샘플은 문서의 첫 번째 단락의 텍스트를 기록합니다. Docs API에서는 단락의 구조적 특성으로 인해 여기에는 여러 하위 요소의 텍스트를 결합하는 작업이 포함됩니다.

advanced/docs.gs
/**
 * Read the first paragraph of the body of a document.
 * @param {string} documentId The ID of the document to read.
 * @return {Object} paragraphText
 * @see https://developers.google.com/docs/api/reference/rest/v1/documents/get
 */
function readFirstParagraph(documentId) {
  try {
    // Get the document using document ID
    const document = Docs.Documents.get(documentId);
    const bodyElements = document.body.content;
    for (let i = 0; i < bodyElements.length; i++) {
      const structuralElement = bodyElements[i];
      // Print the first paragraph text present in document
      if (structuralElement.paragraph) {
        const paragraphElements = structuralElement.paragraph.elements;
        let paragraphText = '';

        for (let j = 0; j < paragraphElements.length; j++) {
          const paragraphElement = paragraphElements[j];
          if (paragraphElement.textRun !== null) {
            paragraphText += paragraphElement.textRun.content;
          }
        }
        console.log(paragraphText);
        return paragraphText;
      }
    }
  } catch (e) {
    // TODO (developer) - Handle exception
    console.log('Failed with error %s', e.message);
  }
}

권장사항

일괄 업데이트

고급 Docs 서비스를 사용하는 경우 루프에서 batchUpdate를 호출하는 대신 여러 요청을 배열로 결합합니다.

금지: batchUpdate를 루프로 호출합니다.

var textToReplace = ['foo', 'bar'];
for (var i = 0; i < textToReplace.length; i++) {
  Docs.Documents.batchUpdate({
    requests: [{
      replaceAllText: ...
    }]
  }, docId);
}

실행 - 업데이트 배열과 함께 batchUpdate를 호출합니다.

var requests = [];
var textToReplace = ['foo', 'bar'];
for (var i = 0; i < textToReplace.length; i++) {
  requests.push({ replaceAllText: ... });
}

Docs.Documents.batchUpdate({
  requests: requests
}, docId);