Grouping text labels with images on a single page in Google Docs using Apps Script

I’m working on a project that involves transferring data from Google Forms to a Google Doc. I’ve managed to add images from the form to the doc, but I’m having trouble with the text labels. Here’s what I’m trying to do:

function addImageAndLabel(body, index, label, imageUrl) {
  body.insertParagraph(index, label + ': ');
  body.insertImage(index + 1, fetchImage(imageUrl));
}

The problem is that sometimes the image and its label end up on different pages. It looks messy and confusing. Is there a way to make sure they always stay together on the same page? I’ve tried a few things, but nothing seems to work. Any ideas on how to fix this?

I’ve encountered a similar issue in my projects. One effective approach is to use a table structure to group the label and image together. Here’s a modified version of your function that might help:

function addImageAndLabel(body, index, label, imageUrl) {
  var table = body.insertTable(index, [[label, '']]);
  var cell = table.getCell(0, 1);
  var image = fetchImage(imageUrl);
  cell.insertImage(0, image);
  table.setBorderWidth(0);
}

This creates a single-row, two-column table with no visible borders. The label goes in the first cell and the image in the second. Tables typically stay together across page breaks, solving your issue. You might need to adjust cell padding or image size for optimal layout. Hope this helps!

hey, maybe try wrapping the label and image in a div or something? like this:

function addImageAndLabel(body, index, label, imageUrl) {
  var div = body.appendParagraph('').setHeading(DocumentApp.ParagraphHeading.NORMAL);
  div.appendText(label + ': ');
  div.appendInlineImage(fetchImage(imageUrl));
}

this keeps em together and you can style the div however u want. worked for me on a similar project

Having worked on similar projects, I can relate to your frustration. One approach that’s worked well for me is using text boxes instead of paragraphs. Here’s a modified version of your function:

function addImageAndLabel(body, index, label, imageUrl) {
  var textBox = body.insertTextBox(index);
  textBox.setText(label + ': ');
  textBox.insertImage(0, fetchImage(imageUrl));
  textBox.setWidth(450); // Adjust as needed
}

This method keeps the label and image together in a single text box, which tends to stay intact across page breaks. You might need to tweak the text box width and positioning to fit your document layout. Also, consider adding some padding between the label and image for better readability. This approach has saved me countless hours of formatting headaches in my projects.