How to change Google Docs specific section margins using Google Apps Script?

问题描述 投票:0回答:1

我正在尝试更改 Google 文档第一部分的边距,但是下面的代码将其应用于整个文档:

    // Insert section break at the beginning of the document
    const resource = {requests: [{insertSectionBreak: {sectionType: "NEXT_PAGE", location: {index: 1}}}]};
    Docs.Documents.batchUpdate(resource, docId);
    
    var body = doc.getBody();
    body.setMarginTop(0);
    body.setMarginLeft(0);
    body.setMarginRight(0);
    body.setMarginBottom(0);

有没有办法将边距设置应用于文档的特定部分?

google-apps-script google-docs google-docs-api
1个回答
0
投票

我相信你的目标如下。

  • 您想更改 Google 文档中多个部分之一的边距。
  • 您想使用 Google Apps 脚本实现此目标。

当我检查这个时,不幸的是,我找不到文档服务(DocumentApp)的内置方法来实现你的目标。但是,幸运的是,这似乎可以通过 Google Docs API 来实现。在这种情况下,我想建议使用 Docs API 的示例脚本。

示例脚本:

在使用此脚本之前,请在 Advanced Google services 中启用 Google Docs API。

function myFunction() {
  const sectionNumber = 1; // 1 is the first section.

  const doc = DocumentApp.getActiveDocument();
  const docId = doc.getId();
  const obj = Docs.Documents.get(docId, { fields: "body(content(sectionBreak,startIndex,endIndex))" }).body.content.filter(e => e.sectionBreak);
  const section = obj[sectionNumber - 1];
  if (!section) {
    throw new Error(`No section of ${sectionNumber} is not found.`);
  }
  const { startIndex, endIndex } = section;
  const requests = [{
    updateSectionStyle: {
      range: { startIndex: startIndex || 0, endIndex },
      sectionStyle: {
        marginLeft: { unit: "PT", magnitude: 0 },
        marginRight: { unit: "PT", magnitude: 0 },
        marginTop: { unit: "PT", magnitude: 0 },
        marginBottom: { unit: "PT", magnitude: 0 }
      },
      fields: "marginLeft,marginRight,marginTop,marginBottom"
    }
  }];
  Docs.Documents.batchUpdate({ requests }, docId);
}
  • 运行此脚本时,第一部分的边距会发生变化。
  • 请根据您的实际情况调整
    sectionStyle
    的保证金。

参考资料:

© www.soinside.com 2019 - 2024. All rights reserved.