I want to programmatically style a paragraph with a background color to make a "code area", just like when using a triple backquote around a paragraph in Stackoverflow, or like in this question. I tried tweaking the scripts and gists in this question, but although the background color changed, it only did around the selected portion of text and not the entire paragraph taking up the entire width of the page.
A suggested workaround is to create a Table
, but I do not want to do that.
I know it is possible because you can select a paragraph by hand, then go to Format > Paragraph styles > Borders and shading
, change the background color from there and it does exactly whant I want.
What I did that only applied the color to a limited portion is (checking that element
is an instance of Paragraph
):
const selection = DocumentApp.getActiveDocument().getSelection();
const rangeElements = selection.getRangeElements();
const element = rangeElements[0].getElement();
element.setBackgroundColor('#D0FAF0');
How do I do what I want to do ? Is it even possible ?
Best Answer
If my understanding is correct, how about this sample script? Unfortunately, in the current stage, there are no methods for modifying the shading color of a paragraph in Document Service, yet. I think that this might be achieved with Document Service by the future update. But as a current workaround, I thought that Google Docs API released recently might be able to be used for achieving this. So I challenged this.
In order to use the following sample script, before you run the script, please enable Google Docs API at API console as follows.
Enable Google Docs API at API console:
Flow:
The flow of sample script is as follows.
Sample script:
The sample script is for the container-bound script with Google Document. Please copy and paste the following script to the script editor, and please select a text on Google Document run
myFunction()
after Google Docs API was enabled.Result:
#39b966
was used as the color.References:
If I misunderstood your question and this workaround was not what you want, I apologize.