getChartBlob(sheet, title) finds an embedded chart on the sheet whose title matches (trimmed, case-insensitive) and returns a PNG blob named after the chart. Use it to attach this week's chart to an email as an image, not as a link the recipient may not be able to open.
When to use
- A Monday digest that should include the chart itself
- Saving a snapshot of a named chart to Drive
- Any script that needs a PNG of a chart you can find by title
How to use this snippet
/**
* Return a named PNG blob for the first embedded chart on the sheet
* whose title matches (trimmed, case-insensitive). The blob is named
* from the chart's own title. Throws if no chart matches.
*
* @param {GoogleAppsScript.Spreadsheet.Sheet} sheet
* @param {string} title
* @return {GoogleAppsScript.Base.Blob}
*/
function getChartBlob(sheet, title) {
if (!sheet) throw new Error('getChartBlob: sheet required');
var want = String(title == null ? '' : title).trim();
if (!want) throw new Error('getChartBlob: title required');
var charts = sheet.getCharts();
var found = null;
for (var i = 0; i < charts.length; i++) {
var t = '';
try {
t = String(charts[i].getOptions().get('title') || '').trim();
} catch (e) {
t = '';
}
if (t.toLowerCase() === want.toLowerCase()) {
found = charts[i];
want = t;
break;
}
}
if (!found) {
throw new Error('getChartBlob: no embedded chart titled "' + want + '"');
}
var safe = want.replace(/[\\/:*?"<>|]+/g, ' ').replace(/\s+/g, ' ').trim() || 'chart';
return found.getAs('image/png').setName(safe + '.png');
}
Example
function emailWeeklyChart() {
var sheet = SpreadsheetApp.getActive().getSheetByName('Dashboard');
var blob = getChartBlob(sheet, 'This week');
GmailApp.sendEmail('ops@example.com', 'Weekly chart', 'This week is attached.', {
htmlBody: '<p>This week:</p><img src="cid:chart">',
inlineImages: { chart: blob }
});
}
Notes
- The chart has to have a title in the chart editor (Chart editor > Customize > Chart & axis titles).
getCharts()only sees embedded charts on that tab, not a chart in a separate Slides deck. - If two charts share a title, the first match is used. The blob name uses the chart's own title, even if you searched with different capitalization.
- The image is a snapshot at send time, not a live window into the spreadsheet. Recipients do not need access to the file to see it.
Happy Coding!
