Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to add text to new Google Doc via Docs API

My program is creating documents and each document has text that needs to go into it. Any attempt to call an InsertTextRequest invokes an error.

List<Request> requests = new ArrayList<>();

requests.add(new Request().setInsertText(new InsertTextRequest()
                .setText("Simple test.")
                .setLocation(new Location().setIndex(0))));

BatchUpdateDocumentRequest body = new BatchUpdateDocumentRequest()
                .setRequests(requests);

BatchUpdateDocumentResponse response = docService.documents()
                .batchUpdate(file.getId(), body).execute();
Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
  "code" : 400,
  "errors" : [ {
    "domain" : "global",
    "message" : "Invalid requests[0].insertText: The insertion index must be inside the bounds of an existing paragraph. You can still create new paragraphs by inserting newlines.",
    "reason" : "badRequest"
  } ],
  "message" : "Invalid requests[0].insertText: The insertion index must be inside the bounds of an existing paragraph. You can still create new paragraphs by inserting newlines.",
  "status" : "INVALID_ARGUMENT"
}

Even trying to add a newline character before adding the text does not fix this issue.

List<Request> requests = new ArrayList<>();

requests.add(new Request().setInsertText(new InsertTextRequest()
                .setText("\n")
                .setLocation(new Location().setIndex(0))));

requests.add(new Request().setInsertText(new InsertTextRequest()
                .setText("Simple test.")
                .setLocation(new Location().setIndex(0))));

BatchUpdateDocumentRequest body = new BatchUpdateDocumentRequest()
                .setRequests(requests);

BatchUpdateDocumentResponse response = docService.documents()
                .batchUpdate(file.getId(), body).execute();

This also invokes the same error. How can I properly add text?

like image 655
wyskoj Avatar asked Jan 01 '23 18:01

wyskoj


1 Answers

Set the index of the Location object to 1, since it's 1-indexed.

like image 151
wyskoj Avatar answered Jan 03 '23 08:01

wyskoj