سرویس اسناد پیشرفته

سرویس پیشرفته Docs به شما امکان می دهد از Google Docs API در Apps Script استفاده کنید. بسیار شبیه به سرویس اسناد داخلی Apps Script، این API به اسکریپت ها امکان خواندن، ویرایش و قالب بندی محتوا را در Google Docs می دهد. در بیشتر موارد استفاده از سرویس داخلی آسان تر است، اما این سرویس پیشرفته چند ویژگی اضافی را ارائه می دهد.

ارجاع

برای اطلاعات دقیق در مورد این سرویس، به مستندات مرجع برای Docs API مراجعه کنید. مانند همه سرویس‌های پیشرفته در Apps Script، سرویس پیشرفته Docs از همان اشیا، روش‌ها و پارامترهای API عمومی استفاده می‌کند. برای اطلاعات بیشتر، نحوه تعیین امضای روش را ببینید.

برای گزارش مشکلات و یافتن پشتیبانی دیگر، به راهنمای پشتیبانی Docs API مراجعه کنید.

کد نمونه

کد نمونه زیر از نسخه 1 API استفاده می کند.

سند ایجاد کنید

این نمونه یک سند جدید ایجاد می کند.

/**
 * 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);
  }
}

متن را پیدا و جایگزین کنید

این نمونه جفت متن را در یک سند پیدا کرده و جایگزین می کند. این می تواند هنگام جایگزینی متغیرهایی در یک کپی از یک سند الگو با مقادیر یک پایگاه داده مفید باشد.

/**
 * 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 برای کارایی دسته بندی کنید.

/**
 * 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، این شامل ترکیب متن چندین عنصر فرعی است.

/**
 * 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);