1
votes

What I am trying to do is:

  • On page 1, insert table 1
  • Move to page 2, insert table 2

I am able to insert two tables one after the other but unable to break to a new page before inserting table 2.

  docId = "YOUR_DOC_ID";
  var doc = DocumentApp.openById(docId);
  var body = doc.getBody();

  var table1 = body.insertTable(2, data[0]);
  formatTable(table1);

  // insert page break here

  var table2 = body.insertTable(3, data[1]);
  formatTable(table2);

  doc.saveAndClose();

The insertPageBreak() is what I am struggling with.

What I have tried till now:

  • The only appendPageBreak I could find is on body. So I tried body.appendPageBreak(). This inserts a new page at the "very" end. BUT I require it right after table 1.
  • I read THIS documentation but could not implement it due to lack of examples I guess.
  • For THIS answer, I get NULL for getCursor() command. Also theElement.insertPageBreak(0) failed for me since element did not show any insertPageBreak() method.
  • For THIS answer, as mentioned above, appends at the end.

Any help will be appreciated.

1

1 Answers

1
votes

Although I'm not sure about your actual Document, if new Document is used, how about this modification? The flow of this modified script is as follows.

  1. Insert a table 1.
  2. Insert a page break.
  3. Insert a table 2 to the new page created by the page break.

Modified script 1:

In this script, the table 1, the page break and the table 2 are put in order to the new Document.

docId = "###";
var body = DocumentApp.openById(docId).getBody();
var table1 = body.insertTable(1, [["table1"]]);
body.insertPageBreak(2);
var table2 = body.insertTable(3, [["table2"]]);

Modified script 2:

In this script, by giving the insert index, the table 1, the page break and the table 2 are put from the insert index in order to the Document.

var insertIndex = 1; // Please set this
docId = "###";
var body = DocumentApp.openById(docId).getBody();
var table1 = body.insertTable(insertIndex, [["table1"]]);
var pageBreak = body.insertPageBreak(body.getChildIndex(table1) + 1);
var table2 = body.insertTable(body.getChildIndex(pageBreak.getParent()) + 1, [["table2"]]);

Note:

  • I couldn't understand about _insertPageBreak().

References:

If I misunderstood your question and this was not the result you want, I apologize.