Search code examples
google-apps-scriptgoogle-docsgoogle-docs-api

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


I am attempting to change the margins of the first section of a Google Doc, however the code below is applying this to the whole document:

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

Is there a way to apply margin settings to a specific section of the document?


Solution

  • I believe your goal is as follows.

    • You want to change the margin of one of the multiple sections in a Google Document.
    • You want to achieve this using Google Apps Script.

    When I checked this, unfortunately, I couldn't find the built-in method of Document service (DocumentApp)for achieving your goal. But, fortunately, it seems that this can be achieved by Google Docs API. In this case, I would like to propose the sample script using Docs API.

    Sample script:

    Before you use this script, please enable Google Docs API at Advanced Google services.

    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);
    }
    
    • When this script is run, the margin of the 1st section is changed.
    • Please adjust the margen of sectionStyle to your actual situation.

    References: