Reputation: 381
I have been trying to deal with the set of images in a document using google apps script. I manage to do what I want, which is to take the images from my document and place them inside a table with two lines and a column, where the first line contains a space for the image description and the second contains the image itself. However, I am having difficulties when going through the paragraphs of my document, my script finds a paragraph without children. This has generated a runtime exception as follows: Exception: The child index (0) must be less than the number of child elements (0). I tried to handle this with an if (), but when I reach the empty paragraph, the same exception is thrown. The code of my script follows below:
function manipuleImage(){
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var paragraphs = body.getParagraphs();
var imagens = body.getImages();
var image = imagens[0];
var typeImage = image.getType();
for(var i = 0; i < paragraphs.length; i++){
var paragraph = paragraphs[i];
if(paragraph.getChild(0) != 0){
var child = paragraph.getChild(0);
var typeChild = child.getType();
if(typeChild == "INLINE_IMAGE"){
var cells = [
[''],['']
];
var styleCell = {};
styleCell[DocumentApp.Attribute.FONT_SIZE] = 11;
styleCell[DocumentApp.Attribute.BOLD] = true;
styleCell[DocumentApp.Attribute.FOREGROUND_COLOR] = '#ffffff';
styleCell[DocumentApp.Attribute.FONT_FAMILY]='Roboto';
styleCell[DocumentApp.Attribute.VERTICAL_ALIGNMENT] = DocumentApp.VerticalAlignment.CENTER;
styleCell[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;
var tableImage = body.insertTable(i, cells)
tableImage.getRow(0).getCell(0).setBackgroundColor("#ef5350");
tableImage.setBorderColor("#ef5350");
tableImage.setBorderWidth(1);
tableImage.getRow(0).getCell(0).setAttributes(styleCell);
tableImage.getRow(1).getCell(0).setAttributes(styleCell);
tableImage.getRow(0).getCell(0).setTextAlignment(DocumentApp.TextAlignment.NORMAL);
tableImage.getRow(1).getCell(0).setTextAlignment(DocumentApp.TextAlignment.NORMAL);
var appendImage = tableImage.getRow(1).getCell(0).clear().appendImage(child.getBlob());
var index = i + 1;
body.removeChild(body.getChild(index));
var imageH = appendImage.getHeight() / 2;
var imageW = appendImage.getWidth() / 2;
appendImage.setHeight(imageH).setWidth(imageW);
}
}
}
}
Upvotes: 1
Views: 835
Reputation: 201513
How about this modification?
getChild(childIndex)
returns Element object. Please be careful this.If you want to skip the paragraph which has only the line break, how about ths following modification?
When your script is modified, please modify as follows.
From:if(paragraph.getChild(0) != 0){
To:
if(paragraph.getNumChildren() != 0){
Upvotes: 1