I am trying to read Attributes of a Paragraph from a Google Document using Apps Script. When I read the attributes, some BOLD attributes are returned as null.
Here is my sample script to read the attributes.
// Reads the attributes of every paragraph in this Google Document and print all paragraph text that is BOLD
function readAttributes() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var paras = body.getParagraphs();
for (var i = 0; i < paras.length; i++){
var paragraph = paras[i];
var attribute = paragraph.getAttributes();
if (attribute.BOLD === true) {
Logger.log(paragraph.getText());
}
}
}
Here is a simulated sample document: The script is behind this Google document. File -> Make a copy.
https://docs.google.com/document/d/13FYg8AAk6PX9TEUdgfaT-60Vi5xoQlZ9Moink5guLH0/edit?usp=sharing
What is wrong with my document? Only the attribute of Question 18 is returned as BOLD and that of Question 17 is returned as null.
The returned Attribute object for any paragraph in Google Document looks like below.
{
FONT_SIZE=null,
ITALIC=null,
HORIZONTAL_ALIGNMENT=null,
INDENT_END=null,
INDENT_START=null,
LINE_SPACING=1.0,
LINK_URL=null,
UNDERLINE=null,
BACKGROUND_COLOR=null,
INDENT_FIRST_LINE=null,
LEFT_TO_RIGHT=true,
SPACING_BEFORE=null,
HEADING=Normal,
SPACING_AFTER=null,
STRIKETHROUGH=null,
FOREGROUND_COLOR=null,
BOLD=null,
FONT_FAMILY=Calibri
}
My Logger.log() Results:
Expected output :
- Which of the following is the most effective plan of action to take if your vehicle catches fire while you are driving?
- Before taking a trip, you need to inspect your tires. Which problems would require immediate action?
Resulted output:
- Before taking a trip, you need to inspect your tires. Which problems would require immediate action?
Image showing the problem
So clearly Question 17 in the document has a problem and so its BOLD attribute is null.
paragraph.editAsText().getAttribute(offset)? - TheMastersamplethat all characters except foraare BOLD attribute. Whenparagraph.editAsText().getAttributes(offset)is used to search BOLD attribute, when only one normal character (a) is included in there, it seems that the property ofBOLDbecomesnullfor all offset. This might be the specification. But whenisBold(offset)is used, even if one normal character is included in the paragraph, the characters except forashowtrue. - Tanaike