본문으로 건너뛰기Skip to content
예제 첫화면Examples home

그리드를 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.

활용Intermediate
직접 써 보기Live preview그리드를 PNG 그림으로 저장하기Save the grid as a PNG image

코드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)

빌드 도구(Vite 등)를 쓰는 프로젝트용 모듈 파일이에요. 설치 없이 바로 돌려 보려면 HTML 탭이나 직접 해보기를 쓰세요.

이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i maxgrid @maxgrid/export로 설치하세요.

버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.

index.html
<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>
main.js
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));
example.js
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.',
  });
}

Module files for a project with a bundler such as Vite. To run it with no setup, use the HTML tab or Try it.

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.

index.html
<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>
main.js
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));
example.js
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.');
}