Deleting Last Empty Page of Google Document using Google Apps Script



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.


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


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


var body = DocumentApp.getActiveDocument().getBody();

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"
    requests: [
        deleteContentRange: {
          range: { startIndex: c.startIndex - 1, endIndex: c.endIndex - 1 }

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


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