How to prevent image and caption from splitting across pages in Google Docs with Apps Script

I’m working on a script that takes responses from Google Forms and puts them into a Google document. Some of the form responses include pictures that I need to add to the doc.

I can successfully insert the images, but I also want to add descriptive text above each image. Here’s the code I’m using in my loop:

document.appendParagraph(imageLabel + ": ");
document.appendImage(fetchImageBlob(formData[imageLabel][0]));

The problem I’m running into is that sometimes the text description ends up at the bottom of one page and the image starts on the next page. This makes the document look messy and hard to read.

Is there a way to make sure the text and image stay together on the same page? I’ve tried different approaches but can’t figure out how to control the page breaks properly.

You could also use the keepWithNext property on the paragraph right before your image. Set the paragraph style so it stays attached to whatever comes next. Try paragraph.getAttributes().SPACING_AFTER = 0 and play around with the paragraph formatting. But honestly, the table method I mentioned earlier is probably way easier.

Had this exact problem with automated reports from form data. The trick is wrapping your text and image in a table - keeps them stuck together. Instead of separate appendParagraph and appendImage calls, create a single-cell table with no borders.

var table = document.appendTable();
var row = table.appendTableRow();
var cell = row.appendTableCell();
cell.appendParagraph(imageLabel + ": ");
cell.appendImage(fetchImageBlob(formData[imageLabel][0]));
table.setBorderWidth(0);

This makes Google Docs treat the caption and image as one unit that won’t split across pages. I’ve used this for months - zero splitting issues since. The table’s invisible to readers but keeps everything where it should be.

I’ve had good luck with paragraph spacing controls. Before adding your image, tweak the paragraph settings to prevent page breaks. Set AVOID_WIDOW_AND_ORPHAN and adjust KEEP_WITH_NEXT on the text paragraph:

var textPara = document.appendParagraph(imageLabel + ": ");
var style = {};
style[DocumentApp.Attribute.KEEP_WITH_NEXT] = true;
textPara.setAttributes(style);
document.appendImage(fetchImageBlob(formData[imageLabel][0]));

This keeps the document flow more natural than tables when you’ve got mixed content. It doesn’t work perfectly with huge images, but it’s been solid for standard form images in my weekly reports.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.