How add styled paragraphs in Google Document by API
i have a functional PHP script to add plain text into Google Document, but I'm struggling to insert paragraphs with styles. What I want to achieve is
- append heading paragraph with text
- append paragraph with hyperlink
There is insertText
request but it's not possible to style this text directly in request. And there is not insertParagraph, so everytime when i insert text i cant even make a new line. https://developers.google.com/docs/api/reference/rest/v1/documents/request
It's frustrating how difficult is to work with Google Docs API, it should be much easier to do such basic tasks, please help.
Solution 1:
I believe your goal is as follows.
- You want to put the texts with the paragraph style and the text style.
- You want to achieve this using Google Docs API.
In this case, how about the following sample request body?
Flow:
In order to achieve your goal, when the batchUpdate method is used, as a sample flow, the following flow is used.
- Insert Texts.
- In this sample, the texts of
Sample1\n
andSample2\n
are inserted.
- In this sample, the texts of
- Set paragraph style.
- In this case, "HEADING_1" and "NORMAL_TEXT" are reflected in the text of
Sample1\n
andSample2\n
, respectively.
- In this case, "HEADING_1" and "NORMAL_TEXT" are reflected in the text of
- Set text style.
- In this case, a hyperlink of
https://www.google.com
is set to the text ofSample2\n
.
- In this case, a hyperlink of
When this flow is reflected in a request body, it becomes as follows. Of course, for example, you can change this flow like "1. Insert Sample1\n
. 2. Set paragraph style. 3. Insert Sample2\n
. 4. Set paragraph style. 5. Set text style.".
Sample request body:
{
"requests": [
{
"insertText": {
"text": "Sample1\n",
"location": {
"index": 1
}
}
},
{
"insertText": {
"text": "sample2\n",
"location": {
"index": 9
}
}
},
{
"updateParagraphStyle": {
"range": {
"startIndex": 1,
"endIndex": 8
},
"paragraphStyle": {
"namedStyleType": "HEADING_1"
},
"fields": "namedStyleType"
}
},
{
"updateParagraphStyle": {
"range": {
"startIndex": 9,
"endIndex": 17
},
"paragraphStyle": {
"namedStyleType": "NORMAL_TEXT"
},
"fields": "namedStyleType"
}
},
{
"updateTextStyle": {
"range": {
"startIndex": 9,
"endIndex": 16
},
"textStyle": {
"link": {
"url": "https://www.google.com"
}
},
"fields": "link"
}
}
]
}
Testing:
When you test this request body with "Try this API" of batchUpdate method of Docs API, you can do it at this link. In this link, the request body has already been set. Please prepare a sample Google Document and set your Google Document ID.
Result:
When this request body is used for a Google Document, the following result is obtained.
References:
- InsertTextRequest
- UpdateParagraphStyleRequest
- UpdateTextStyleRequest