Skip to content

Instantly share code, notes, and snippets.

@tanaikech

tanaikech/submit.md

Created May 17, 2019
Embed
What would you like to do?
Deleting Pages of Google Document using Google Apps Script

Deleting Pages of Google Document using Google Apps Script

This is a sample script for deleting pages of Google Document from the last page using Google Apps Script. There are no methods for directly deleting pages of Google Document. This is one of several workarounds. In this workaround, the following flow is used.

Flow

  1. Retrieve paragraphs in the body of Document.
  2. Retrieve elements in each paragraph. The page break is included in the paragraph.
  3. Delete elements from last page in order.
  4. When the number of page breaks is the same with deletePages, the script is stopped.

By this flow, several pages can be deleted from the last page in order.

IMPORTANT

This sample script deletes pages using the page break as mentioned above. So, for example, when this script is used for Document with total page of 10 pages without the page break, the pages cannot be deleted. Please be careful this.

Sample script

var deletePages = 3;
var id = "### documentId ###";

var paragraph = DocumentApp.openById(id)
  .getBody()
  .getParagraphs();
var counter = 0;
for (var i = paragraph.length - 1; i >= 0; i--) {
  for (var j = 0; j < paragraph[i].getNumChildren(); j++)
    if (
      paragraph[i].getChild(j).getType() == DocumentApp.ElementType.PAGE_BREAK
    )
      counter++;
  paragraph[i].clear();
  if (counter == deletePages) break;
}
  • When you can delete the pages from the Document by changing the number of var deletePages = 3.
  • The pages are deleted from the last page.

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.