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.
- Retrieve paragraphs in the body of Document.
- Retrieve elements in each paragraph. The page break is included in the paragraph.
- Delete elements from last page in order.
- 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.
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.
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++;
if (counter < deletePages)
paragraph[i].clear();
else if (counter == deletePages){
paragraph[i].getChild(paragraph[i].getNumChildren() - 1).removeFromParent();
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.
- From @derekantrican's suggestion, I updated the sample script.
@derekantrican Thank you for your comment.