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

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

مرجع

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

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

کد نمونه

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

ایجاد سند

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

پیشرفته/docs.gs
/**
 * Create a new document.
 * @see https://developers.google.com/docs/api/reference/rest/v1/documents/create
 * @return {string} documentId
 */
function createDocument() {
  // Create document with title
  const document = Docs.Documents.create({ title: "My New Document" });
  console.log(`Created document with ID: ${document.documentId}`);
  return document.documentId;
}

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

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

پیشرفته/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];

    // Replace all text across all tabs.
    const replaceAllTextRequest = {
      replaceAllText: {
        containsText: {
          text: findText,
          matchCase: true,
        },
        replaceText: replaceText,
      },
    };

    // Replace all text across specific tabs.
    const _replaceAllTextWithTabsCriteria = {
      replaceAllText: {
        ...replaceAllTextRequest.replaceAllText,
        tabsCriteria: {
          tabIds: [TAB_ID_1, TAB_ID_2, TAB_ID_3],
        },
      },
    };
    requests.push(replaceAllTextRequest);
  }
  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;
}

متن را وارد کنید و سبک دهید

این نمونه متن جدید را در ابتدای اولین تب در سند وارد می‌کند و آن را با فونت و اندازه خاصی استایل‌بندی می‌کند. توجه داشته باشید که در صورت امکان، برای افزایش کارایی، باید چندین عملیات را در یک فراخوانی batchUpdate دسته‌بندی کنید.

پیشرفته/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",
      },
    },
  ];
  const response = Docs.Documents.batchUpdate(
    { requests: requests },
    documentId,
  );
  return response.replies;
}

پاراگراف اول را بخوانید

این نمونه متن پاراگراف اول از اولین تب سند را ثبت می‌کند. به دلیل ماهیت ساختاریافته پاراگراف‌ها در API اسناد، این شامل ترکیب متن چندین زیرعنصر است.

پیشرفته/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) {
  // 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;
    }
  }
}

بهترین شیوه‌ها

به‌روزرسانی‌های دسته‌ای

هنگام استفاده از سرویس پیشرفته 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);