خدمة المستندات المتقدّمة

تتيح لك خدمة "مستندات Google" المتقدّمة استخدام واجهة برمجة تطبيقات "مستندات Google" في "برمجة التطبيقات". تسمح واجهة برمجة التطبيقات هذه للنصوص البرمجية بقراءة المحتوى وتعديله وتنسيقه في "مستندات Google"، كما هو الحال إلى حد كبير مع خدمة المستندات المضمّنة في "برمجة التطبيقات". في معظم الحالات، تكون الخدمة المضمّنة أسهل في الاستخدام، إلا أنّ هذه الخدمة المتقدمة توفّر بعض الميزات الإضافية.

مَراجع

للحصول على معلومات تفصيلية حول هذه الخدمة، راجِع المستندات المرجعية لواجهة برمجة تطبيقات Docs. مثل جميع الخدمات المتقدمة في لغة "برمجة تطبيقات Google"، تستخدم خدمة "مستندات Google" المتقدمة العناصر والطرق والمعلَمات نفسها التي تستخدمها واجهة برمجة التطبيقات العامة. لمزيد من المعلومات، يُرجى الاطّلاع على كيفية تحديد توقيعات الطرق.

للإبلاغ عن المشاكل والعثور على خدمات دعم أخرى، يُرجى الاطّلاع على دليل دعم واجهة برمجة تطبيقات "مستندات Google".

نموذج التعليمات البرمجية

يستخدم الرمز النموذجي أدناه الإصدار 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);
  }
}

قراءة الفقرة الأولى

يسجِّل هذا النموذج نص الفقرة الأولى في المستند. نظرًا للطبيعة المهيكلة للفقرات في واجهة برمجة التطبيقات للمستندات، فإن هذا يتضمن دمج نص العناصر الفرعية المتعددة.

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

أفضل الممارسات

التحديثات المجمّعة

عند استخدام خدمة "مستندات Google" المتقدّمة، يمكنك دمج طلبات متعددة في صفيف بدلاً من استدعاء 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);