Reputation: 334
I am having a hard time. I have a document, which is a series of Paragraphs and Tables. Sometimes, I need to remove the last paragraph of the document and I would like to do so without leaving any empty whitespace.
Currently, I am getting this error:
Can't remove the last paragraph in a document section.
Does anyone know why this is happening? Is there a workaround?
Upvotes: 4
Views: 3699
Reputation: 11
Super late to the party, but it doesn't look like this issue is resolved yet. I used the clear and merge functions to remove any whitespace only paragraphs at the end.
var paragraphs = DocumentApp.getActiveDocument().getBody().getParagraphs();
for (var i=paragraphs.length-1; i>=0; i--){
var line = paragraphs[i];
if (line.getText().trim() ) {
break;
}
else {
line.clear();
line.merge();
}
}
Upvotes: 1
Reputation: 46802
Try this approach, it seems to work as expected, at least I didn't succeed to make it fail ;-)
function deleteAllParagraphs() {
var doc = DocumentApp.getActiveDocument().getBody();
doc.insertParagraph(0, '');// insert a dummy paragraph at the beginning of the doc that we are going to let there
doc.appendParagraph('');// append another dummy in case doc is empty
for(var p=doc.getNumChildren();p>=0;p--){
try{
doc.getChild(p).removeFromParent();
}catch(e){}
}
}
EDIT : from the issue tracker I found a better code suggested by #11 cyberaxe that I slightly modified :
function emptyDocument() {
var document = DocumentApp.getActiveDocument();
var body = document.getBody();
body.appendParagraph('');// to be sure to delete the last paragraph in case it doesn't end with a cr/lf
while (body.getNumChildren() > 1) body.removeChild( body.getChild( 0 ) );
}
Upvotes: 2