高级幻灯片服务

借助高级幻灯片服务,您可以使用 Apps 脚本访问 Slides API。此服务允许脚本读取和编辑 Google 幻灯片中的内容。

参考

如需详细了解此服务,请参阅 Slides API 的参考文档。与 Apps 脚本中的所有高级服务一样,高级幻灯片服务使用与公共 API 相同的对象、方法和参数。如需了解详情,请参阅如何确定方法签名

如需报告问题和寻求其他支持,请参阅幻灯片支持指南

示例代码

以下示例代码使用的是 API 的版本 1

创建新演示文稿

以下示例演示了如何使用 Google 幻灯片高级服务创建新的演示文稿。这相当于创建新演示文稿食谱示例。

advanced/slides.gs
/**
 * Create a new presentation.
 * @return {string} presentation Id.
 * @see https://developers.google.com/slides/api/reference/rest/v1/presentations/create
 */
function createPresentation() {
  try {
    const presentation =
      Slides.Presentations.create({'title': 'MyNewPresentation'});
    console.log('Created presentation with ID: ' + presentation.presentationId);
    return presentation.presentationId;
  } catch (e) {
    // TODO (developer) - Handle exception
    console.log('Failed with error %s', e.message);
  }
}

创建新的幻灯片

以下示例演示了如何在特定索引下使用预定义布局在演示文稿中创建新幻灯片。这相当于创建新幻灯片食谱示例。

advanced/slides.gs
/**
 * Create a new slide.
 * @param {string} presentationId The presentation to add the slide to.
 * @return {Object} slide
 * @see https://developers.google.com/slides/api/reference/rest/v1/presentations/batchUpdate
 */
function createSlide(presentationId) {
  // You can specify the ID to use for the slide, as long as it's unique.
  const pageId = Utilities.getUuid();

  const requests = [{
    'createSlide': {
      'objectId': pageId,
      'insertionIndex': 1,
      'slideLayoutReference': {
        'predefinedLayout': 'TITLE_AND_TWO_COLUMNS'
      }
    }
  }];
  try {
    const slide =
      Slides.Presentations.batchUpdate({'requests': requests}, presentationId);
    console.log('Created Slide with ID: ' + slide.replies[0].createSlide.objectId);
    return slide;
  } catch (e) {
    // TODO (developer) - Handle Exception
    console.log('Failed with error %s', e.message);
  }
}

读取页面元素对象 ID

以下示例演示了如何使用字段掩码检索特定幻灯片上每个页面元素的对象 ID。这相当于从页面中读取元素对象 ID 配方示例。

advanced/slides.gs
/**
 * Read page element IDs.
 * @param {string} presentationId The presentation to read from.
 * @param {string} pageId The page to read from.
 * @return {Object} response
 * @see https://developers.google.com/slides/api/reference/rest/v1/presentations.pages/get
 */
function readPageElementIds(presentationId, pageId) {
  // You can use a field mask to limit the data the API retrieves
  // in a get request, or what fields are updated in an batchUpdate.
  try {
    const response = Slides.Presentations.Pages.get(
        presentationId, pageId, {'fields': 'pageElements.objectId'});
    console.log(response);
    return response;
  } catch (e) {
    // TODO (developer) - Handle Exception
    console.log('Failed with error %s', e.message);
  }
}

添加新的文本框

以下示例演示了如何在幻灯片中添加新文本框并向其中添加文本。这相当于 Add a text box to a slide 方法示例。

advanced/slides.gs
/**
 * Add a new text box with text to a page.
 * @param {string} presentationId The presentation ID.
 * @param {string} pageId The page ID.
 * @return {Object} response
 * @see https://developers.google.com/slides/api/reference/rest/v1/presentations/batchUpdate
 */
function addTextBox(presentationId, pageId) {
  // You can specify the ID to use for elements you create,
  // as long as the ID is unique.
  const pageElementId = Utilities.getUuid();

  const requests = [{
    'createShape': {
      'objectId': pageElementId,
      'shapeType': 'TEXT_BOX',
      'elementProperties': {
        'pageObjectId': pageId,
        'size': {
          'width': {
            'magnitude': 150,
            'unit': 'PT'
          },
          'height': {
            'magnitude': 50,
            'unit': 'PT'
          }
        },
        'transform': {
          'scaleX': 1,
          'scaleY': 1,
          'translateX': 200,
          'translateY': 100,
          'unit': 'PT'
        }
      }
    }
  }, {
    'insertText': {
      'objectId': pageElementId,
      'text': 'My Added Text Box',
      'insertionIndex': 0
    }
  }];
  try {
    const response =
      Slides.Presentations.batchUpdate({'requests': requests}, presentationId);
    console.log('Created Textbox with ID: ' +
      response.replies[0].createShape.objectId);
    return response;
  } catch (e) {
    // TODO (developer) - Handle Exception
    console.log('Failed with error %s', e.message);
  }
}

设置形状内文字的格式

以下示例演示了如何设置形状文本的格式,以及如何更新其颜色、字体和为文本添加下划线。这相当于在形状或文本框中设置文本格式食谱示例。

advanced/slides.gs
/**
 * Format the text in a shape.
 * @param {string} presentationId The presentation ID.
 * @param {string} shapeId The shape ID.
 * @return {Object} replies
 * @see https://developers.google.com/slides/api/reference/rest/v1/presentations/batchUpdate
 */
function formatShapeText(presentationId, shapeId) {
  const requests = [{
    'updateTextStyle': {
      'objectId': shapeId,
      'fields': 'foregroundColor,bold,italic,fontFamily,fontSize,underline',
      'style': {
        'foregroundColor': {
          'opaqueColor': {
            'themeColor': 'ACCENT5'
          }
        },
        'bold': true,
        'italic': true,
        'underline': true,
        'fontFamily': 'Corsiva',
        'fontSize': {
          'magnitude': 18,
          'unit': 'PT'
        }
      },
      'textRange': {
        'type': 'ALL'
      }
    }
  }];
  try {
    const response =
      Slides.Presentations.batchUpdate({'requests': requests}, presentationId);
    return response.replies;
  } catch (e) {
    // TODO (developer) - Handle Exception
    console.log('Failed with error %s', e.message);
  }
}

最佳实践

批量更新

使用幻灯片高级服务时,请将多个请求合并成一个数组,而不是在一个循环中调用 batchUpdate

错误做法 - 在循环中调用 batchUpdate

var titles = ["slide 1", "slide 2"];
for (var i = 0; i < titles.length; i++) {
  Slides.Presentations.batchUpdate(preso, {
    requests: [{
      createSlide: ...
    }]
  });
}

正确做法 - 使用更新数组调用 batchUpdate

var requests = [];
var titles = ["slide 1", "slide 2"];
for (var i = 0; i < titles.length; i++) {
  requests.push({ createSlide: ... });
}

Slides.Presentations.batchUpdate(preso, {
  requests: requests
});