שירות Docs מתקדם

השירות המתקדם של Docs מאפשר לכם להשתמש ב-Google Docs API ב-Apps Script. בדומה לשירות המובנה של Docs ב-Apps Script,‏ ה-API הזה מאפשר לסקריפטים לקרוא, לערוך ולעצב תוכן ב-Google Docs. ברוב המקרים, קל יותר להשתמש בשירות המובנה, אבל השירות המתקדם הזה מספק כמה תכונות נוספות.

חומרי עזר

מידע מפורט על השירות הזה מופיע במסמכי העזרה של Docs API. בדומה לכל השירותים המתקדמים ב-Apps Script, שירות Docs המתקדם משתמש באותם אובייקטים, שיטות ופרמטרים כמו בממשק ה-API הציבורי. מידע נוסף זמין במאמר איך נקבעות חתימות של שיטות.

כדי לדווח על בעיות ולמצוא תמיכה נוספת, אפשר לעיין במדריך התמיכה של Docs API.

קוד לדוגמה

בדוגמת הקוד שבהמשך נעשה שימוש בגרסה 1 של ה-API.

יצירת מסמך

בדוגמה הזו נוצר מסמך חדש.

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];
    // One option for replacing all text is to specify all tab IDs.
    const request = {
      replaceAllText: {
        containsText: {
          text: findText,
          matchCase: true
        },
        replaceText: replaceText,
        tabsCriteria: {
          tabIds: [TAB_ID_1, TAB_ID_2, TAB_ID_3],
        }
      }
    };
    // Another option is to omit TabsCriteria if you are replacing across all tabs.
    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 first tab in 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,
        // A tab can be specified using its ID. When omitted, the request is
        // applied to the first tab.
        // tabId: TAB_ID
      },
      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 first tab in 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, {'includeTabsContent': true});
    const firstTab = document.tabs[0];
    const bodyElements = firstTab.documentTab.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);