Deleting Last Empty Page of Google Document using Google Apps Script

Gists

Overview

This is a sample script for deleting the last empty page which has only one paragraph including no values which is "" in the Google Document using Google Apps Script.

Description

As a sample situation, it supposes that there is the following Google Document.

In this sample, the last page of Google Document has only one paragraph including no values which is "". When I try to delete only last page without modifying the previous page, I noticed that this cannot be achieved with only Google Document service. For example, it try to delete the paragraph of the last page using the following scripts,

var body = DocumentApp.getActiveDocument().getBody();
body.getChild(body.getNumChildren() - 1).removeFromParent();

and

var body = DocumentApp.getActiveDocument().getBody();
body.removeChild(body.getChild(body.getNumChildren() - 1));

and

var body = DocumentApp.getActiveDocument().getBody();
body
  .getParagraphs()
  .pop()
  .removeFromParent();

An error like “the last paragraph cannot be removed.” occurs. Although I had looked for the method for deleting this last page using the Google Document service, unfortunately, I couldn’t find it. So I used Google Docs API. When Google Docs API is used, the content can be deleted with one character unit. By this, above situation can be achieved.

Sample script

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

var docId = "###"; // Please set the Google Document ID here.
var c = Docs.Documents.get(docId, {
  fields: "body.content"
}).body.content.pop();
Docs.Documents.batchUpdate(
  {
    requests: [
      {
        deleteContentRange: {
          range: { startIndex: c.startIndex - 1, endIndex: c.endIndex - 1 }
        }
      }
    ]
  },
  docId
);

When this script is run, the last page of above sample image can be deleted.

References

If you can find the method for achieving above with only Google Document service and when you propose the sample script, I’m glad.

 Share!