그리드를 PNG 그림으로 저장하기Save the grid as a PNG image
화면 또는 전체 행을 배율과 배경색을 정해서 PNG로 만들고 내려받아요.Create and download a PNG of the visible area or all rows, with a chosen scale and background.
코드Code
탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.
이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)
이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i maxgrid @maxgrid/export로 설치하세요.
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<div id="app">
<div class="toolbar">
<select aria-label="범위" id="scope">
<option value="view" selected>화면</option>
<option value="all">전체</option>
</select>
<select aria-label="배율" id="scale">
<option value="1">1배</option>
<option value="2" selected>2배</option>
<option value="3">3배</option>
</select>
<select aria-label="배경" id="background">
<option value="grid" selected>그리드 배경</option>
<option value="white">흰색</option>
<option value="gray">연한 회색</option>
<option value="cream">연한 노랑</option>
</select>
<button type="button" id="size">크기 확인</button>
<button type="button" id="download">내려받기</button>
</div>
<div id="grid" style="height: 300px"></div>
</div>
<script type="module" src="./main.js"></script>import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('scope').addEventListener('change', (event) => actions.scope(api, event.target.value));
document.getElementById('scale').addEventListener('change', (event) => actions.scale(api, event.target.value));
document.getElementById('background').addEventListener('change', (event) => actions.background(api, event.target.value));
document.getElementById('size').addEventListener('click', () => actions.size(api));
document.getElementById('download').addEventListener('click', () => actions.download(api));import { withExport } from '@maxgrid/export';
const names = ['김하늘', '이도윤', '박서연', '최민재', '정유나', '한지우'];
const teams = ['개발', '디자인', '영업', '인사'];
const rows = Array.from({ length: 30 }, (_, i) => ({
id: i + 1,
name: names[i % names.length],
team: teams[i % teams.length],
sales: 1200 + ((i * 370) % 4100),
}));
export const options = {
columns: [
{ id: 'name', title: '이름', width: 110 },
{ id: 'team', title: '팀', width: 90 },
{
id: 'sales',
title: '매출(만원)',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
],
rows,
rowKey: 'id',
};
const backgrounds = {
grid: undefined,
white: '#ffffff',
gray: '#e4e8ef',
cream: '#fff4d6',
};
let scope = 'view';
let scale = 2;
let bg = 'grid';
let say = () => { };
const png = () => ({ scope, scale, background: backgrounds[bg] });
// background는 그리드 뒤·아래만 칠해요. 글자색은 테마 색 그대로라서, 어두운 화면에서 밝은 배경을 고르면 글자가 안 보여요.
// 그래서 배경을 직접 고르면 내보내는 동안만 이 표를 밝은 테마(data-mxg-theme="light")로 바꿔요. 'grid'는 지금 화면 그대로예요.
async function withBackgroundTheme(api, run) {
const root = api.getGridElement();
const before = root.getAttribute('data-mxg-theme');
if (bg !== 'grid')
root.setAttribute('data-mxg-theme', 'light');
try {
return await run();
}
finally {
if (before === null)
root.removeAttribute('data-mxg-theme');
else
root.setAttribute('data-mxg-theme', before);
}
}
export const actions = {
scope: (_api, v) => void (scope = v === 'all' ? 'all' : 'view'),
scale: (_api, v) => void (scale = Number(v) === 1 ? 1 : Number(v) === 3 ? 3 : 2),
background: (_api, v) => void (bg = v ?? 'grid'),
size: async (api) => {
try {
const blob = await withBackgroundTheme(api, () => withExport(api).exportPng(png()));
say({
ko: `PNG를 만들었어요: ${blob.size.toLocaleString('ko-KR')}바이트 (${blob.type}) · 범위 ${scope} · 배율 ${scale}`,
en: `PNG created: ${blob.size.toLocaleString('en-US')} bytes (${blob.type}) · scope ${scope} · scale ${scale}`,
});
}
catch (e) {
say({
ko: `만들지 못했어요: ${e.message}`,
en: `Could not create: ${e.message}`,
});
}
},
download: async (api) => {
try {
await withBackgroundTheme(api, () => withExport(api).downloadPng('매출.png', png()));
say({
ko: `내려받았어요 (범위 ${scope} · 배율 ${scale})`,
en: `Downloaded (scope ${scope} · scale ${scale})`,
});
}
catch (e) {
say({
ko: `내려받지 못했어요: ${e.message}`,
en: `Could not download: ${e.message}`,
});
}
},
};
export function setup(api, log) {
say = log;
withExport(api);
log({
ko: '범위 "화면"은 지금 보이는 부분만, "전체"는 30행 모두를 그림으로 저장해요.',
en: 'Scope "view" saves what is visible now; "all" saves all 30 rows as an image.',
});
} 이 HTML은 추가 번들(위 script 태그)도 함께 불러오고 전역 변수로 써요. 별도 설치는 필요 없어요.
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>그리드를 PNG 그림으로 저장하기</title>
</head>
<body>
<div class="toolbar">
<select aria-label="범위" id="scope">
<option value="view" selected>화면</option>
<option value="all">전체</option>
</select>
<select aria-label="배율" id="scale">
<option value="1">1배</option>
<option value="2" selected>2배</option>
<option value="3">3배</option>
</select>
<select aria-label="배경" id="background">
<option value="grid" selected>그리드 배경</option>
<option value="white">흰색</option>
<option value="gray">연한 회색</option>
<option value="cream">연한 노랑</option>
</select>
<button type="button" id="size">크기 확인</button>
<button type="button" id="download">내려받기</button>
</div>
<div id="grid" style="height: 300px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.export.min.js"></script>
<script>
const { withExport } = MaxGridExport;
const names = ['김하늘', '이도윤', '박서연', '최민재', '정유나', '한지우'];
const teams = ['개발', '디자인', '영업', '인사'];
const rows = Array.from({ length: 30 }, (_, i) => ({
id: i + 1,
name: names[i % names.length],
team: teams[i % teams.length],
sales: 1200 + ((i * 370) % 4100),
}));
const options = {
columns: [
{ id: 'name', title: '이름', width: 110 },
{ id: 'team', title: '팀', width: 90 },
{
id: 'sales',
title: '매출(만원)',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
],
rows,
rowKey: 'id',
};
const backgrounds = {
grid: undefined,
white: '#ffffff',
gray: '#e4e8ef',
cream: '#fff4d6',
};
let scope = 'view';
let scale = 2;
let bg = 'grid';
let say = () => { };
const png = () => ({ scope, scale, background: backgrounds[bg] });
// background는 그리드 뒤·아래만 칠해요. 글자색은 테마 색 그대로라서, 어두운 화면에서 밝은 배경을 고르면 글자가 안 보여요.
// 그래서 배경을 직접 고르면 내보내는 동안만 이 표를 밝은 테마(data-mxg-theme="light")로 바꿔요. 'grid'는 지금 화면 그대로예요.
async function withBackgroundTheme(api, run) {
const root = api.getGridElement();
const before = root.getAttribute('data-mxg-theme');
if (bg !== 'grid')
root.setAttribute('data-mxg-theme', 'light');
try {
return await run();
}
finally {
if (before === null)
root.removeAttribute('data-mxg-theme');
else
root.setAttribute('data-mxg-theme', before);
}
}
const actions = {
scope: (_api, v) => void (scope = v === 'all' ? 'all' : 'view'),
scale: (_api, v) => void (scale = Number(v) === 1 ? 1 : Number(v) === 3 ? 3 : 2),
background: (_api, v) => void (bg = v ?? 'grid'),
size: async (api) => {
try {
const blob = await withBackgroundTheme(api, () => withExport(api).exportPng(png()));
say({
ko: `PNG를 만들었어요: ${blob.size.toLocaleString('ko-KR')}바이트 (${blob.type}) · 범위 ${scope} · 배율 ${scale}`,
en: `PNG created: ${blob.size.toLocaleString('en-US')} bytes (${blob.type}) · scope ${scope} · scale ${scale}`,
});
}
catch (e) {
say({
ko: `만들지 못했어요: ${e.message}`,
en: `Could not create: ${e.message}`,
});
}
},
download: async (api) => {
try {
await withBackgroundTheme(api, () => withExport(api).downloadPng('매출.png', png()));
say({
ko: `내려받았어요 (범위 ${scope} · 배율 ${scale})`,
en: `Downloaded (scope ${scope} · scale ${scale})`,
});
}
catch (e) {
say({
ko: `내려받지 못했어요: ${e.message}`,
en: `Could not download: ${e.message}`,
});
}
},
};
function setup(api, log) {
say = log;
withExport(api);
log({
ko: '범위 "화면"은 지금 보이는 부분만, "전체"는 30행 모두를 그림으로 저장해요.',
en: 'Scope "view" saves what is visible now; "all" saves all 30 rows as an image.',
});
}
options.ariaLabel = "그리드를 PNG 그림으로 저장하기";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('scope').addEventListener('change', (event) => actions.scope(api, event.target.value));
document.getElementById('scale').addEventListener('change', (event) => actions.scale(api, event.target.value));
document.getElementById('background').addEventListener('change', (event) => actions.background(api, event.target.value));
document.getElementById('size').addEventListener('click', () => actions.size(api));
document.getElementById('download').addEventListener('click', () => actions.download(api));
</script>
</body>
</html> 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i @maxgrid/react @maxgrid/export로 설치하세요.
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<select
aria-label="범위"
disabled={!api}
onChange={(event) => api && actions.scope(api, event.target.value)}
>
<option value="view">화면</option>
<option value="all">전체</option>
</select>
<select defaultValue="view"
aria-label="배율"
disabled={!api}
onChange={(event) => api && actions.scale(api, event.target.value)}
>
<option value="1">1배</option>
<option value="2">2배</option>
<option value="3">3배</option>
</select>
<select defaultValue="2"
aria-label="배경"
disabled={!api}
onChange={(event) => api && actions.background(api, event.target.value)}
>
<option value="grid">그리드 배경</option>
<option value="white">흰색</option>
<option value="gray">연한 회색</option>
<option value="cream">연한 노랑</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.size(api)}
>크기 확인</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.download(api)}
>내려받기</button>
</div>
<Grid style={{ height: 300 }} ref={gridRef} options={options} />
</>
);
}import { withExport } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
team: string;
sales: number;
}
const names = ['김하늘', '이도윤', '박서연', '최민재', '정유나', '한지우'];
const teams = ['개발', '디자인', '영업', '인사'];
const rows: Row[] = Array.from({ length: 30 }, (_, i) => ({
id: i + 1,
name: names[i % names.length] as string,
team: teams[i % teams.length] as string,
sales: 1200 + ((i * 370) % 4100),
}));
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 110 },
{ id: 'team', title: '팀', width: 90 },
{
id: 'sales',
title: '매출(만원)',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
],
rows,
rowKey: 'id',
};
const backgrounds: Record<string, string | undefined> = {
grid: undefined,
white: '#ffffff',
gray: '#e4e8ef',
cream: '#fff4d6',
};
let scope: 'view' | 'all' = 'view';
let scale: 1 | 2 | 3 = 2;
let bg = 'grid';
let say: (message: LogText) => void = () => {};
const png = () => ({ scope, scale, background: backgrounds[bg] });
// background는 그리드 뒤·아래만 칠해요. 글자색은 테마 색 그대로라서, 어두운 화면에서 밝은 배경을 고르면 글자가 안 보여요.
// 그래서 배경을 직접 고르면 내보내는 동안만 이 표를 밝은 테마(data-mxg-theme="light")로 바꿔요. 'grid'는 지금 화면 그대로예요.
async function withBackgroundTheme<T>(api: GridApi<Row>, run: () => Promise<T>): Promise<T> {
const root = api.getGridElement();
const before = root.getAttribute('data-mxg-theme');
if (bg !== 'grid') root.setAttribute('data-mxg-theme', 'light');
try {
return await run();
} finally {
if (before === null) root.removeAttribute('data-mxg-theme');
else root.setAttribute('data-mxg-theme', before);
}
}
export const actions = {
scope: (_api: GridApi<Row>, v?: string) => void (scope = v === 'all' ? 'all' : 'view'),
scale: (_api: GridApi<Row>, v?: string) =>
void (scale = Number(v) === 1 ? 1 : Number(v) === 3 ? 3 : 2),
background: (_api: GridApi<Row>, v?: string) => void (bg = v ?? 'grid'),
size: async (api: GridApi<Row>) => {
try {
const blob = await withBackgroundTheme(api, () => withExport(api).exportPng(png()));
say({
ko: `PNG를 만들었어요: ${blob.size.toLocaleString('ko-KR')}바이트 (${blob.type}) · 범위 ${scope} · 배율 ${scale}`,
en: `PNG created: ${blob.size.toLocaleString('en-US')} bytes (${blob.type}) · scope ${scope} · scale ${scale}`,
});
} catch (e) {
say({
ko: `만들지 못했어요: ${(e as Error).message}`,
en: `Could not create: ${(e as Error).message}`,
});
}
},
download: async (api: GridApi<Row>) => {
try {
await withBackgroundTheme(api, () => withExport(api).downloadPng('매출.png', png()));
say({
ko: `내려받았어요 (범위 ${scope} · 배율 ${scale})`,
en: `Downloaded (scope ${scope} · scale ${scale})`,
});
} catch (e) {
say({
ko: `내려받지 못했어요: ${(e as Error).message}`,
en: `Could not download: ${(e as Error).message}`,
});
}
},
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
withExport(api);
log({
ko: '범위 "화면"은 지금 보이는 부분만, "전체"는 30행 모두를 그림으로 저장해요.',
en: 'Scope "view" saves what is visible now; "all" saves all 30 rows as an image.',
});
} 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i @maxgrid/vue @maxgrid/export로 설치하세요.
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<select
aria-label="범위"
:disabled="!api"
@change="api && actions.scope(api, ($event.target as HTMLSelectElement).value)"
>
<option value="view" selected>화면</option>
<option value="all">전체</option>
</select>
<select
aria-label="배율"
:disabled="!api"
@change="api && actions.scale(api, ($event.target as HTMLSelectElement).value)"
>
<option value="1">1배</option>
<option value="2" selected>2배</option>
<option value="3">3배</option>
</select>
<select
aria-label="배경"
:disabled="!api"
@change="api && actions.background(api, ($event.target as HTMLSelectElement).value)"
>
<option value="grid" selected>그리드 배경</option>
<option value="white">흰색</option>
<option value="gray">연한 회색</option>
<option value="cream">연한 노랑</option>
</select>
<button type="button" :disabled="!api" @click="api && actions.size(api)">크기 확인</button>
<button
type="button"
:disabled="!api"
@click="api && actions.download(api)"
>내려받기</button>
</div>
<Grid style="height: 300px" :options="options" @ready="onReady" />
</template>import { withExport } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
team: string;
sales: number;
}
const names = ['김하늘', '이도윤', '박서연', '최민재', '정유나', '한지우'];
const teams = ['개발', '디자인', '영업', '인사'];
const rows: Row[] = Array.from({ length: 30 }, (_, i) => ({
id: i + 1,
name: names[i % names.length] as string,
team: teams[i % teams.length] as string,
sales: 1200 + ((i * 370) % 4100),
}));
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 110 },
{ id: 'team', title: '팀', width: 90 },
{
id: 'sales',
title: '매출(만원)',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
],
rows,
rowKey: 'id',
};
const backgrounds: Record<string, string | undefined> = {
grid: undefined,
white: '#ffffff',
gray: '#e4e8ef',
cream: '#fff4d6',
};
let scope: 'view' | 'all' = 'view';
let scale: 1 | 2 | 3 = 2;
let bg = 'grid';
let say: (message: LogText) => void = () => {};
const png = () => ({ scope, scale, background: backgrounds[bg] });
// background는 그리드 뒤·아래만 칠해요. 글자색은 테마 색 그대로라서, 어두운 화면에서 밝은 배경을 고르면 글자가 안 보여요.
// 그래서 배경을 직접 고르면 내보내는 동안만 이 표를 밝은 테마(data-mxg-theme="light")로 바꿔요. 'grid'는 지금 화면 그대로예요.
async function withBackgroundTheme<T>(api: GridApi<Row>, run: () => Promise<T>): Promise<T> {
const root = api.getGridElement();
const before = root.getAttribute('data-mxg-theme');
if (bg !== 'grid') root.setAttribute('data-mxg-theme', 'light');
try {
return await run();
} finally {
if (before === null) root.removeAttribute('data-mxg-theme');
else root.setAttribute('data-mxg-theme', before);
}
}
export const actions = {
scope: (_api: GridApi<Row>, v?: string) => void (scope = v === 'all' ? 'all' : 'view'),
scale: (_api: GridApi<Row>, v?: string) =>
void (scale = Number(v) === 1 ? 1 : Number(v) === 3 ? 3 : 2),
background: (_api: GridApi<Row>, v?: string) => void (bg = v ?? 'grid'),
size: async (api: GridApi<Row>) => {
try {
const blob = await withBackgroundTheme(api, () => withExport(api).exportPng(png()));
say({
ko: `PNG를 만들었어요: ${blob.size.toLocaleString('ko-KR')}바이트 (${blob.type}) · 범위 ${scope} · 배율 ${scale}`,
en: `PNG created: ${blob.size.toLocaleString('en-US')} bytes (${blob.type}) · scope ${scope} · scale ${scale}`,
});
} catch (e) {
say({
ko: `만들지 못했어요: ${(e as Error).message}`,
en: `Could not create: ${(e as Error).message}`,
});
}
},
download: async (api: GridApi<Row>) => {
try {
await withBackgroundTheme(api, () => withExport(api).downloadPng('매출.png', png()));
say({
ko: `내려받았어요 (범위 ${scope} · 배율 ${scale})`,
en: `Downloaded (scope ${scope} · scale ${scale})`,
});
} catch (e) {
say({
ko: `내려받지 못했어요: ${(e as Error).message}`,
en: `Could not download: ${(e as Error).message}`,
});
}
},
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
withExport(api);
log({
ko: '범위 "화면"은 지금 보이는 부분만, "전체"는 30행 모두를 그림으로 저장해요.',
en: 'Scope "view" saves what is visible now; "all" saves all 30 rows as an image.',
});
} 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i @maxgrid/angular @maxgrid/export로 설치하세요.
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<select
aria-label="범위"
[disabled]="!api"
(change)="api && actions.scope(api, $any($event.target).value)"
>
<option value="view" selected>화면</option>
<option value="all">전체</option>
</select>
<select
aria-label="배율"
[disabled]="!api"
(change)="api && actions.scale(api, $any($event.target).value)"
>
<option value="1">1배</option>
<option value="2" selected>2배</option>
<option value="3">3배</option>
</select>
<select
aria-label="배경"
[disabled]="!api"
(change)="api && actions.background(api, $any($event.target).value)"
>
<option value="grid" selected>그리드 배경</option>
<option value="white">흰색</option>
<option value="gray">연한 회색</option>
<option value="cream">연한 노랑</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.size(api)"
>크기 확인</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.download(api)"
>내려받기</button>
</div>
<mx-grid style="height: 300px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import { withExport } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
team: string;
sales: number;
}
const names = ['김하늘', '이도윤', '박서연', '최민재', '정유나', '한지우'];
const teams = ['개발', '디자인', '영업', '인사'];
const rows: Row[] = Array.from({ length: 30 }, (_, i) => ({
id: i + 1,
name: names[i % names.length] as string,
team: teams[i % teams.length] as string,
sales: 1200 + ((i * 370) % 4100),
}));
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 110 },
{ id: 'team', title: '팀', width: 90 },
{
id: 'sales',
title: '매출(만원)',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
],
rows,
rowKey: 'id',
};
const backgrounds: Record<string, string | undefined> = {
grid: undefined,
white: '#ffffff',
gray: '#e4e8ef',
cream: '#fff4d6',
};
let scope: 'view' | 'all' = 'view';
let scale: 1 | 2 | 3 = 2;
let bg = 'grid';
let say: (message: LogText) => void = () => {};
const png = () => ({ scope, scale, background: backgrounds[bg] });
// background는 그리드 뒤·아래만 칠해요. 글자색은 테마 색 그대로라서, 어두운 화면에서 밝은 배경을 고르면 글자가 안 보여요.
// 그래서 배경을 직접 고르면 내보내는 동안만 이 표를 밝은 테마(data-mxg-theme="light")로 바꿔요. 'grid'는 지금 화면 그대로예요.
async function withBackgroundTheme<T>(api: GridApi<Row>, run: () => Promise<T>): Promise<T> {
const root = api.getGridElement();
const before = root.getAttribute('data-mxg-theme');
if (bg !== 'grid') root.setAttribute('data-mxg-theme', 'light');
try {
return await run();
} finally {
if (before === null) root.removeAttribute('data-mxg-theme');
else root.setAttribute('data-mxg-theme', before);
}
}
export const actions = {
scope: (_api: GridApi<Row>, v?: string) => void (scope = v === 'all' ? 'all' : 'view'),
scale: (_api: GridApi<Row>, v?: string) =>
void (scale = Number(v) === 1 ? 1 : Number(v) === 3 ? 3 : 2),
background: (_api: GridApi<Row>, v?: string) => void (bg = v ?? 'grid'),
size: async (api: GridApi<Row>) => {
try {
const blob = await withBackgroundTheme(api, () => withExport(api).exportPng(png()));
say({
ko: `PNG를 만들었어요: ${blob.size.toLocaleString('ko-KR')}바이트 (${blob.type}) · 범위 ${scope} · 배율 ${scale}`,
en: `PNG created: ${blob.size.toLocaleString('en-US')} bytes (${blob.type}) · scope ${scope} · scale ${scale}`,
});
} catch (e) {
say({
ko: `만들지 못했어요: ${(e as Error).message}`,
en: `Could not create: ${(e as Error).message}`,
});
}
},
download: async (api: GridApi<Row>) => {
try {
await withBackgroundTheme(api, () => withExport(api).downloadPng('매출.png', png()));
say({
ko: `내려받았어요 (범위 ${scope} · 배율 ${scale})`,
en: `Downloaded (scope ${scope} · scale ${scale})`,
});
} catch (e) {
say({
ko: `내려받지 못했어요: ${(e as Error).message}`,
en: `Could not download: ${(e as Error).message}`,
});
}
},
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
withExport(api);
log({
ko: '범위 "화면"은 지금 보이는 부분만, "전체"는 30행 모두를 그림으로 저장해요.',
en: 'Scope "view" saves what is visible now; "all" saves all 30 rows as an image.',
});
} This example needs an extra package. To run it locally, install with npm i maxgrid @maxgrid/export.
When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<div id="app">
<div class="toolbar">
<select aria-label="Scope" id="scope">
<option value="view" selected>View</option>
<option value="all">All rows</option>
</select>
<select aria-label="Scale" id="scale">
<option value="1">1x</option>
<option value="2" selected>2x</option>
<option value="3">3x</option>
</select>
<select aria-label="Background" id="background">
<option value="grid" selected>Grid background</option>
<option value="white">White</option>
<option value="gray">Light gray</option>
<option value="cream">Light cream</option>
</select>
<button type="button" id="size">Check size</button>
<button type="button" id="download">Download</button>
</div>
<div id="grid" style="height: 300px"></div>
</div>
<script type="module" src="./main.js"></script>import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('scope').addEventListener('change', (event) => actions.scope(api, event.target.value));
document.getElementById('scale').addEventListener('change', (event) => actions.scale(api, event.target.value));
document.getElementById('background').addEventListener('change', (event) => actions.background(api, event.target.value));
document.getElementById('size').addEventListener('click', () => actions.size(api));
document.getElementById('download').addEventListener('click', () => actions.download(api));import { withExport } from '@maxgrid/export';
const names = [
'Liam Carter',
'Emma Stone',
'Noah Reed',
'Olivia Hart',
'Mason Clark',
'Ava Brooks',
];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
const rows = Array.from({ length: 30 }, (_, i) => ({
id: i + 1,
name: names[i % names.length],
team: teams[i % teams.length],
sales: 1200 + ((i * 370) % 4100),
}));
export const options = {
columns: [
{ id: 'name', title: 'Name', width: 110 },
{ id: 'team', title: 'Team', width: 90 },
{
id: 'sales',
title: 'Sales ($K)',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('en-US'),
},
],
rows,
rowKey: 'id',
};
const backgrounds = {
grid: undefined,
white: '#ffffff',
gray: '#e4e8ef',
cream: '#fff4d6',
};
let scope = 'view';
let scale = 2;
let bg = 'grid';
let say = () => { };
const png = () => ({ scope, scale, background: backgrounds[bg] });
// background only paints behind and under the grid. Text keeps the theme colours, so a light background on a dark page would hide the text.
// So when a background is chosen, the grid switches to the light theme (data-mxg-theme="light") only while exporting. 'grid' keeps what is on screen.
async function withBackgroundTheme(api, run) {
const root = api.getGridElement();
const before = root.getAttribute('data-mxg-theme');
if (bg !== 'grid')
root.setAttribute('data-mxg-theme', 'light');
try {
return await run();
}
finally {
if (before === null)
root.removeAttribute('data-mxg-theme');
else
root.setAttribute('data-mxg-theme', before);
}
}
export const actions = {
scope: (_api, v) => void (scope = v === 'all' ? 'all' : 'view'),
scale: (_api, v) => void (scale = Number(v) === 1 ? 1 : Number(v) === 3 ? 3 : 2),
background: (_api, v) => void (bg = v ?? 'grid'),
size: async (api) => {
try {
const blob = await withBackgroundTheme(api, () => withExport(api).exportPng(png()));
say(`PNG created: ${blob.size.toLocaleString('en-US')} bytes (${blob.type}) · scope ${scope} · scale ${scale}`);
}
catch (e) {
say(`Could not create: ${e.message}`);
}
},
download: async (api) => {
try {
await withBackgroundTheme(api, () => withExport(api).downloadPng('sales.png', png()));
say(`Downloaded (scope ${scope} · scale ${scale})`);
}
catch (e) {
say(`Could not download: ${e.message}`);
}
},
};
export function setup(api, log) {
say = log;
withExport(api);
log('Scope "view" saves what is visible now; "all" saves all 30 rows as an image.');
}This HTML also loads an extra bundle (the extra script tag above) and uses it as a global. No install is needed.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Save the grid as a PNG image</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Scope" id="scope">
<option value="view" selected>View</option>
<option value="all">All rows</option>
</select>
<select aria-label="Scale" id="scale">
<option value="1">1x</option>
<option value="2" selected>2x</option>
<option value="3">3x</option>
</select>
<select aria-label="Background" id="background">
<option value="grid" selected>Grid background</option>
<option value="white">White</option>
<option value="gray">Light gray</option>
<option value="cream">Light cream</option>
</select>
<button type="button" id="size">Check size</button>
<button type="button" id="download">Download</button>
</div>
<div id="grid" style="height: 300px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.export.min.js"></script>
<script>
const { withExport } = MaxGridExport;
const names = [
'Liam Carter',
'Emma Stone',
'Noah Reed',
'Olivia Hart',
'Mason Clark',
'Ava Brooks',
];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
const rows = Array.from({ length: 30 }, (_, i) => ({
id: i + 1,
name: names[i % names.length],
team: teams[i % teams.length],
sales: 1200 + ((i * 370) % 4100),
}));
const options = {
columns: [
{ id: 'name', title: 'Name', width: 110 },
{ id: 'team', title: 'Team', width: 90 },
{
id: 'sales',
title: 'Sales ($K)',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('en-US'),
},
],
rows,
rowKey: 'id',
};
const backgrounds = {
grid: undefined,
white: '#ffffff',
gray: '#e4e8ef',
cream: '#fff4d6',
};
let scope = 'view';
let scale = 2;
let bg = 'grid';
let say = () => { };
const png = () => ({ scope, scale, background: backgrounds[bg] });
// background only paints behind and under the grid. Text keeps the theme colours, so a light background on a dark page would hide the text.
// So when a background is chosen, the grid switches to the light theme (data-mxg-theme="light") only while exporting. 'grid' keeps what is on screen.
async function withBackgroundTheme(api, run) {
const root = api.getGridElement();
const before = root.getAttribute('data-mxg-theme');
if (bg !== 'grid')
root.setAttribute('data-mxg-theme', 'light');
try {
return await run();
}
finally {
if (before === null)
root.removeAttribute('data-mxg-theme');
else
root.setAttribute('data-mxg-theme', before);
}
}
const actions = {
scope: (_api, v) => void (scope = v === 'all' ? 'all' : 'view'),
scale: (_api, v) => void (scale = Number(v) === 1 ? 1 : Number(v) === 3 ? 3 : 2),
background: (_api, v) => void (bg = v ?? 'grid'),
size: async (api) => {
try {
const blob = await withBackgroundTheme(api, () => withExport(api).exportPng(png()));
say(`PNG created: ${blob.size.toLocaleString('en-US')} bytes (${blob.type}) · scope ${scope} · scale ${scale}`);
}
catch (e) {
say(`Could not create: ${e.message}`);
}
},
download: async (api) => {
try {
await withBackgroundTheme(api, () => withExport(api).downloadPng('sales.png', png()));
say(`Downloaded (scope ${scope} · scale ${scale})`);
}
catch (e) {
say(`Could not download: ${e.message}`);
}
},
};
function setup(api, log) {
say = log;
withExport(api);
log('Scope "view" saves what is visible now; "all" saves all 30 rows as an image.');
}
options.ariaLabel = "Save the grid as a PNG image";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('scope').addEventListener('change', (event) => actions.scope(api, event.target.value));
document.getElementById('scale').addEventListener('change', (event) => actions.scale(api, event.target.value));
document.getElementById('background').addEventListener('change', (event) => actions.background(api, event.target.value));
document.getElementById('size').addEventListener('click', () => actions.size(api));
document.getElementById('download').addEventListener('click', () => actions.download(api));
</script>
</body>
</html> This example needs an extra package. To run it locally, install with npm i @maxgrid/react @maxgrid/export.
When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<select
aria-label="Scope"
disabled={!api}
onChange={(event) => api && actions.scope(api, event.target.value)}
>
<option value="view">View</option>
<option value="all">All rows</option>
</select>
<select defaultValue="view"
aria-label="Scale"
disabled={!api}
onChange={(event) => api && actions.scale(api, event.target.value)}
>
<option value="1">1x</option>
<option value="2">2x</option>
<option value="3">3x</option>
</select>
<select defaultValue="2"
aria-label="Background"
disabled={!api}
onChange={(event) => api && actions.background(api, event.target.value)}
>
<option value="grid">Grid background</option>
<option value="white">White</option>
<option value="gray">Light gray</option>
<option value="cream">Light cream</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.size(api)}
>Check size</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.download(api)}
>Download</button>
</div>
<Grid style={{ height: 300 }} ref={gridRef} options={options} />
</>
);
}import { withExport } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
name: string;
team: string;
sales: number;
}
const names = [
'Liam Carter',
'Emma Stone',
'Noah Reed',
'Olivia Hart',
'Mason Clark',
'Ava Brooks',
];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
const rows: Row[] = Array.from({ length: 30 }, (_, i) => ({
id: i + 1,
name: names[i % names.length] as string,
team: teams[i % teams.length] as string,
sales: 1200 + ((i * 370) % 4100),
}));
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 110 },
{ id: 'team', title: 'Team', width: 90 },
{
id: 'sales',
title: 'Sales ($K)',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('en-US'),
},
],
rows,
rowKey: 'id',
};
const backgrounds: Record<string, string | undefined> = {
grid: undefined,
white: '#ffffff',
gray: '#e4e8ef',
cream: '#fff4d6',
};
let scope: 'view' | 'all' = 'view';
let scale: 1 | 2 | 3 = 2;
let bg = 'grid';
let say: (message: LogText) => void = () => {};
const png = () => ({ scope, scale, background: backgrounds[bg] });
// background only paints behind and under the grid. Text keeps the theme colours, so a light background on a dark page would hide the text.
// So when a background is chosen, the grid switches to the light theme (data-mxg-theme="light") only while exporting. 'grid' keeps what is on screen.
async function withBackgroundTheme<T>(api: GridApi<Row>, run: () => Promise<T>): Promise<T> {
const root = api.getGridElement();
const before = root.getAttribute('data-mxg-theme');
if (bg !== 'grid') root.setAttribute('data-mxg-theme', 'light');
try {
return await run();
} finally {
if (before === null) root.removeAttribute('data-mxg-theme');
else root.setAttribute('data-mxg-theme', before);
}
}
export const actions = {
scope: (_api: GridApi<Row>, v?: string) => void (scope = v === 'all' ? 'all' : 'view'),
scale: (_api: GridApi<Row>, v?: string) =>
void (scale = Number(v) === 1 ? 1 : Number(v) === 3 ? 3 : 2),
background: (_api: GridApi<Row>, v?: string) => void (bg = v ?? 'grid'),
size: async (api: GridApi<Row>) => {
try {
const blob = await withBackgroundTheme(api, () => withExport(api).exportPng(png()));
say(
`PNG created: ${blob.size.toLocaleString('en-US')} bytes (${blob.type}) · scope ${scope} · scale ${scale}`,
);
} catch (e) {
say(`Could not create: ${(e as Error).message}`);
}
},
download: async (api: GridApi<Row>) => {
try {
await withBackgroundTheme(api, () => withExport(api).downloadPng('sales.png', png()));
say(`Downloaded (scope ${scope} · scale ${scale})`);
} catch (e) {
say(`Could not download: ${(e as Error).message}`);
}
},
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
withExport(api);
log('Scope "view" saves what is visible now; "all" saves all 30 rows as an image.');
} This example needs an extra package. To run it locally, install with npm i @maxgrid/vue @maxgrid/export.
When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<select
aria-label="Scope"
:disabled="!api"
@change="api && actions.scope(api, ($event.target as HTMLSelectElement).value)"
>
<option value="view" selected>View</option>
<option value="all">All rows</option>
</select>
<select
aria-label="Scale"
:disabled="!api"
@change="api && actions.scale(api, ($event.target as HTMLSelectElement).value)"
>
<option value="1">1x</option>
<option value="2" selected>2x</option>
<option value="3">3x</option>
</select>
<select
aria-label="Background"
:disabled="!api"
@change="api && actions.background(api, ($event.target as HTMLSelectElement).value)"
>
<option value="grid" selected>Grid background</option>
<option value="white">White</option>
<option value="gray">Light gray</option>
<option value="cream">Light cream</option>
</select>
<button type="button" :disabled="!api" @click="api && actions.size(api)">Check size</button>
<button
type="button"
:disabled="!api"
@click="api && actions.download(api)"
>Download</button>
</div>
<Grid style="height: 300px" :options="options" @ready="onReady" />
</template>import { withExport } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
name: string;
team: string;
sales: number;
}
const names = [
'Liam Carter',
'Emma Stone',
'Noah Reed',
'Olivia Hart',
'Mason Clark',
'Ava Brooks',
];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
const rows: Row[] = Array.from({ length: 30 }, (_, i) => ({
id: i + 1,
name: names[i % names.length] as string,
team: teams[i % teams.length] as string,
sales: 1200 + ((i * 370) % 4100),
}));
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 110 },
{ id: 'team', title: 'Team', width: 90 },
{
id: 'sales',
title: 'Sales ($K)',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('en-US'),
},
],
rows,
rowKey: 'id',
};
const backgrounds: Record<string, string | undefined> = {
grid: undefined,
white: '#ffffff',
gray: '#e4e8ef',
cream: '#fff4d6',
};
let scope: 'view' | 'all' = 'view';
let scale: 1 | 2 | 3 = 2;
let bg = 'grid';
let say: (message: LogText) => void = () => {};
const png = () => ({ scope, scale, background: backgrounds[bg] });
// background only paints behind and under the grid. Text keeps the theme colours, so a light background on a dark page would hide the text.
// So when a background is chosen, the grid switches to the light theme (data-mxg-theme="light") only while exporting. 'grid' keeps what is on screen.
async function withBackgroundTheme<T>(api: GridApi<Row>, run: () => Promise<T>): Promise<T> {
const root = api.getGridElement();
const before = root.getAttribute('data-mxg-theme');
if (bg !== 'grid') root.setAttribute('data-mxg-theme', 'light');
try {
return await run();
} finally {
if (before === null) root.removeAttribute('data-mxg-theme');
else root.setAttribute('data-mxg-theme', before);
}
}
export const actions = {
scope: (_api: GridApi<Row>, v?: string) => void (scope = v === 'all' ? 'all' : 'view'),
scale: (_api: GridApi<Row>, v?: string) =>
void (scale = Number(v) === 1 ? 1 : Number(v) === 3 ? 3 : 2),
background: (_api: GridApi<Row>, v?: string) => void (bg = v ?? 'grid'),
size: async (api: GridApi<Row>) => {
try {
const blob = await withBackgroundTheme(api, () => withExport(api).exportPng(png()));
say(
`PNG created: ${blob.size.toLocaleString('en-US')} bytes (${blob.type}) · scope ${scope} · scale ${scale}`,
);
} catch (e) {
say(`Could not create: ${(e as Error).message}`);
}
},
download: async (api: GridApi<Row>) => {
try {
await withBackgroundTheme(api, () => withExport(api).downloadPng('sales.png', png()));
say(`Downloaded (scope ${scope} · scale ${scale})`);
} catch (e) {
say(`Could not download: ${(e as Error).message}`);
}
},
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
withExport(api);
log('Scope "view" saves what is visible now; "all" saves all 30 rows as an image.');
} This example needs an extra package. To run it locally, install with npm i @maxgrid/angular @maxgrid/export.
When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<select
aria-label="Scope"
[disabled]="!api"
(change)="api && actions.scope(api, $any($event.target).value)"
>
<option value="view" selected>View</option>
<option value="all">All rows</option>
</select>
<select
aria-label="Scale"
[disabled]="!api"
(change)="api && actions.scale(api, $any($event.target).value)"
>
<option value="1">1x</option>
<option value="2" selected>2x</option>
<option value="3">3x</option>
</select>
<select
aria-label="Background"
[disabled]="!api"
(change)="api && actions.background(api, $any($event.target).value)"
>
<option value="grid" selected>Grid background</option>
<option value="white">White</option>
<option value="gray">Light gray</option>
<option value="cream">Light cream</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.size(api)"
>Check size</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.download(api)"
>Download</button>
</div>
<mx-grid style="height: 300px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import { withExport } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
name: string;
team: string;
sales: number;
}
const names = [
'Liam Carter',
'Emma Stone',
'Noah Reed',
'Olivia Hart',
'Mason Clark',
'Ava Brooks',
];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
const rows: Row[] = Array.from({ length: 30 }, (_, i) => ({
id: i + 1,
name: names[i % names.length] as string,
team: teams[i % teams.length] as string,
sales: 1200 + ((i * 370) % 4100),
}));
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 110 },
{ id: 'team', title: 'Team', width: 90 },
{
id: 'sales',
title: 'Sales ($K)',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('en-US'),
},
],
rows,
rowKey: 'id',
};
const backgrounds: Record<string, string | undefined> = {
grid: undefined,
white: '#ffffff',
gray: '#e4e8ef',
cream: '#fff4d6',
};
let scope: 'view' | 'all' = 'view';
let scale: 1 | 2 | 3 = 2;
let bg = 'grid';
let say: (message: LogText) => void = () => {};
const png = () => ({ scope, scale, background: backgrounds[bg] });
// background only paints behind and under the grid. Text keeps the theme colours, so a light background on a dark page would hide the text.
// So when a background is chosen, the grid switches to the light theme (data-mxg-theme="light") only while exporting. 'grid' keeps what is on screen.
async function withBackgroundTheme<T>(api: GridApi<Row>, run: () => Promise<T>): Promise<T> {
const root = api.getGridElement();
const before = root.getAttribute('data-mxg-theme');
if (bg !== 'grid') root.setAttribute('data-mxg-theme', 'light');
try {
return await run();
} finally {
if (before === null) root.removeAttribute('data-mxg-theme');
else root.setAttribute('data-mxg-theme', before);
}
}
export const actions = {
scope: (_api: GridApi<Row>, v?: string) => void (scope = v === 'all' ? 'all' : 'view'),
scale: (_api: GridApi<Row>, v?: string) =>
void (scale = Number(v) === 1 ? 1 : Number(v) === 3 ? 3 : 2),
background: (_api: GridApi<Row>, v?: string) => void (bg = v ?? 'grid'),
size: async (api: GridApi<Row>) => {
try {
const blob = await withBackgroundTheme(api, () => withExport(api).exportPng(png()));
say(
`PNG created: ${blob.size.toLocaleString('en-US')} bytes (${blob.type}) · scope ${scope} · scale ${scale}`,
);
} catch (e) {
say(`Could not create: ${(e as Error).message}`);
}
},
download: async (api: GridApi<Row>) => {
try {
await withBackgroundTheme(api, () => withExport(api).downloadPng('sales.png', png()));
say(`Downloaded (scope ${scope} · scale ${scale})`);
} catch (e) {
say(`Could not download: ${(e as Error).message}`);
}
},
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
withExport(api);
log('Scope "view" saves what is visible now; "all" saves all 30 rows as an image.');
}