Report: Inserting Multiple Paragraphs to Google Document in Order using Google Docs API

Gists

This is a report for inserting the multiple paragraphs to Google Document in order using Google Docs API.

When the multiple paragraphs are inserted to Google Document using Google Docs API, it is required to pay attention to the index for inserting the texts. In this report, I would like to introduce the points for achieving this with a simple method.

Although this report uses Google Apps Script, the logic of this method can be used for other language.

In the following sample scripts, 3 paragraphs of sample paragraph 1, sample paragraph 2 and sample paragraph 3 are tried to be inserted to the Document. Before you use these scripts, please enable Google Docs API at Advanced Google services.

Sample script 1

function sample1() {
const requests = [
{ insertText: { text: "sample paragraph 1\n", location: { index: 1 } } },
{ insertText: { text: "sample paragraph 2\n", location: { index: 1 } } },
{ insertText: { text: "sample paragraph 3\n", location: { index: 1 } } },
];
Docs.Documents.batchUpdate({ requests }, documentId);
}


When this script is run, the following result is obtained. Unfortunately, in this case, the texts in the request body are inserted to the Document in the reverse order.

Sample script 2

function sample2() {
const requests = [
{ insertText: { text: "sample paragraph 1\n", location: { index: 1 } } },
{ insertText: { text: "sample paragraph 2\n", location: { index: 1 } } },
{ insertText: { text: "sample paragraph 3\n", location: { index: 1 } } },
];
requests.reverse();
Docs.Documents.batchUpdate({ requests }, documentId);
}


When this script is run, the following result is obtained. From the above sample script 1, it is found that by reversing the request body, the paragraphs are inserted to Document in order.

Sample script 3

function sample3() {
const requests = [
{
insertText: {
text: "sample paragraph 1\n",
endOfSegmentLocation: { segmentId: "" },
},
},
{
insertText: {
text: "sample paragraph 2\n",
endOfSegmentLocation: { segmentId: "" },
},
},
{
insertText: {
text: "sample paragraph 3\n",
endOfSegmentLocation: { segmentId: "" },
},
},
];
Docs.Documents.batchUpdate({ requests }, documentId);
}


When this script is run, the following result is obtained. It is found that by using endOfSegmentLocation: { segmentId: "" } instead of location: { index: 1 }, the paragraphs are inserted to Document in order. This situation is the append method.