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

그룹·합계를 PDF·xlsx로, 많은 줄은 취소와 상한Groups and totals in PDF and xlsx; cancel and limit for large exports

지역별 그룹과 합계가 든 PDF·xlsx를 만들고, 2만 줄 PDF를 만들다 취소하거나 줄 수 상한으로 막아요.Build PDF and xlsx with region groups and totals, cancel a 20,000-row PDF build or stop it with a row limit.

심화Advanced
직접 써 보기Live preview그룹·합계를 PDF·xlsx로, 많은 줄은 취소와 상한Groups and totals in PDF and xlsx; cancel and limit for large exports

코드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 @maxgrid/export-font-ko로 설치하세요.

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

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="expandAll">모두 펼치기</button>
    <button type="button" id="collapseAll">모두 접기</button>
    <button type="button" id="group">그룹 PDF 만들기</button>
    <button type="button" id="xlsx">xlsx 내려받기 (그룹 포함)</button>
    <select aria-label="줄 수" id="size">
      <option value="20000">20,000줄</option>
      <option value="100000">100,000줄</option>
      <option value="300000" selected>300,000줄</option>
    </select>
    <button type="button" id="big">전체 PDF 만들기</button>
    <button type="button" id="cancel">취소</button>
    <button type="button" id="limit">1,000줄 상한 시험</button>
  </div>
  <div id="grid" style="height: 330px"></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('expandAll').addEventListener('click', () => actions.expandAll(api));
document.getElementById('collapseAll').addEventListener('click', () => actions.collapseAll(api));
document.getElementById('group').addEventListener('click', () => actions.group(api));
document.getElementById('xlsx').addEventListener('click', () => actions.xlsx(api));
document.getElementById('size').addEventListener('change', (event) => actions.size(api, event.target.value));
document.getElementById('big').addEventListener('click', () => actions.big(api));
document.getElementById('cancel').addEventListener('click', () => actions.cancel(api));
document.getElementById('limit').addEventListener('click', () => actions.limit(api));
example.js
import { withExport } from '@maxgrid/export';
import { koreanFont } from '@maxgrid/export-font-ko';
// 라이브러리가 보내는 경고(영어·기술 용어)를 쉬운 한국어로 바꿔요.
const warnText = (w) => w.code === 'missing-glyph'
  ? `폰트에 없는 글자를 ?로 바꿨어요: ${w.characters}`
  : w.code === 'font-unavailable'
    ? '한글 폰트를 불러오지 못해서 기본 폰트로 만들었어요.'
    : '세로로 합친 칸은 PDF에서 합치지 않았어요.';
// 만드는 동안 버튼을 잠가서, 두 번 눌러도 파일이 두 개 만들어지지 않게 해요.
async function busy(ids, work) {
  const buttons = ids
    .map((id) => document.getElementById(id))
    .filter((el) => el instanceof HTMLButtonElement);
  if (buttons.some((b) => b.disabled))
    return;
  for (const b of buttons)
    b.disabled = true;
  try {
    await work();
  }
  finally {
    for (const b of buttons)
      b.disabled = false;
  }
}
const regions = ['서울', '부산', '대전', '광주'];
// 줄 수 선택: 기본값은 이 서버에서 PDF가 수 초 걸리는 크기라서, 만드는 도중에 취소를 눌러 볼 수 있어요.
const DEFAULT_SIZE = 300_000;
const makeRows = (count) => Array.from({ length: count }, (_, i) => ({
  id: i + 1,
  region: regions[i % regions.length],
  code: `ORD-${String(i + 1).padStart(6, '0')}`,
  amount: ((i * 7919) % 90_000) + 1_000,
}));
// 많은 줄은 나눠서 만들어서 화면이 멈추지 않고, 도중에 취소하거나 줄 수 상한으로 막을 수 있어요.
export const options = {
  columns: [
    { id: 'region', title: '지역', width: 90 },
    // 지역 줄(그룹 줄)의 이 칸에는 주문 건수를 보여요: 집계를 정하지 않은 칸은 그룹 줄에서 비어 있어요.
    {
      id: 'code',
      title: '주문코드',
      width: 130,
      aggregate: 'rowCount',
      aggregateFormat: (v) => `${Number(v).toLocaleString('ko-KR')}건`,
    },
    {
      id: 'amount',
      title: '금액(원)',
      kind: 'number',
      width: 120,
      align: 'end',
      aggregate: 'sum',
      formatValue: (v) => Number(v).toLocaleString('ko-KR'),
      // 내보내기의 그룹·합계 줄은 aggregateFormat이 없으면 원시 숫자를 쓰므로, 화면과 같은 쉼표 서식을 여기에도 줘요.
      aggregateFormat: (v) => Number(v).toLocaleString('ko-KR'),
    },
  ],
  rows: makeRows(DEFAULT_SIZE),
  rowKey: 'id',
  grouping: { by: ['region'], expandDepth: 0 },
  summary: { label: '합계' },
};
let say = () => { };
let ctrl;
export function setup(api, log) {
  say = log;
  withExport(api);
  return () => ctrl?.abort();
}
export const actions = {
  expandAll: (api) => api.expandAll(),
  collapseAll: (api) => api.collapseAll(),
  // 지금 화면의 줄 그대로 내려받아요: 접혀 있으면 지역 줄과 합계만, 펼치면 모든 주문이 들어가요.
  group: async (api) => {
    await busy(['group', 'xlsx', 'big'], async () => {
      say({
        ko: '만드는 중… 처음에는 한글 폰트를 읽느라 몇 초 걸려요.',
        en: 'Building… the first time takes a few seconds to load the Korean font.',
      });
      const warnings = [];
      await withExport(api).downloadPdf('주문-그룹.pdf', {
        font: koreanFont,
        hierarchy: true,
        onWarning: (w) => warnings.push(w),
      });
      for (const w of warnings)
        say(warnText(w));
      say({
        ko: `주문-그룹.pdf를 내려받았어요 (보이는 줄 ${api.getVisibleRowCount().toLocaleString('ko-KR')}개).`,
        en: `Downloaded 주문-그룹.pdf (${api.getVisibleRowCount().toLocaleString('en-US')} visible rows).`,
      });
    });
  },
  xlsx: async (api) => {
    await busy(['group', 'xlsx', 'big'], async () => {
      await withExport(api).downloadXlsx('주문-그룹.xlsx', {
        hierarchy: true,
        applyFormatValue: false,
      });
      say({
        ko: `주문-그룹.xlsx를 내려받았어요 (보이는 줄 ${api.getVisibleRowCount().toLocaleString('ko-KR')}개).`,
        en: `Downloaded 주문-그룹.xlsx (${api.getVisibleRowCount().toLocaleString('en-US')} visible rows).`,
      });
    });
  },
  // 줄 수를 바꾸면 그리드의 줄을 새로 채워요. 만드는 도중에는 바꾸지 않아요.
  size: (api, value) => {
    if (ctrl)
      return;
    api.setRows(makeRows(Number(value) || DEFAULT_SIZE));
  },
  // 고른 줄 수 전체를 나눠 만들어요. 만드는 동안에도 화면이 멈추지 않고 취소할 수 있어요.
  big: async (api) => {
    await busy(['group', 'xlsx', 'big'], async () => {
      const mine = (ctrl = new AbortController());
      const started = Date.now();
      const count = api.getRowCount();
      const n = { ko: count.toLocaleString('ko-KR'), en: count.toLocaleString('en-US') };
      say({ ko: `${n.ko}줄 PDF를 만드는 중이에요…`, en: `Building a ${n.en}-row PDF…` });
      try {
        await withExport(api).downloadPdf('주문-전체.pdf', {
          rowScope: 'all',
          maxRows: 1_000_000, // 기본 상한(10만 줄)보다 많은 줄 수도 고를 수 있게 올려요.
          signal: mine.signal,
          font: koreanFont,
        });
        say({
          ko: `주문-전체.pdf를 내려받았어요 (${((Date.now() - started) / 1000).toFixed(1)}초).`,
          en: `Downloaded 주문-전체.pdf (${((Date.now() - started) / 1000).toFixed(1)} s).`,
        });
      }
      catch {
        say({
          ko: mine.signal.aborted
            ? '취소했어요.'
            : 'PDF를 만들지 못했어요. 잠시 뒤에 다시 눌러 주세요.',
          en: mine.signal.aborted
            ? 'Cancelled.'
            : 'Could not make the PDF. Please try again in a moment.',
        });
      }
      finally {
        ctrl = undefined;
      }
    });
  },
  cancel: () => {
    if (!ctrl)
      return say({ ko: '만드는 중이 아니에요.', en: 'Nothing is being built.' });
    ctrl.abort();
  },
  // 줄 수가 상한보다 많으면 아무것도 만들기 전에 막아요.
  limit: async (api) => {
    try {
      await withExport(api).exportPdf({ rowScope: 'all', maxRows: 1_000 });
      say({
        ko: '줄 수가 상한 안이라 만들어졌어요.',
        en: 'The row count is within the limit, so it was built.',
      });
    }
    catch (error) {
      say({
        ko: error instanceof RangeError
          ? `줄이 너무 많아서 만들지 않았어요. 전체 ${api.getRowCount().toLocaleString('ko-KR')}줄인데 1,000줄까지만 만들도록 정해 두었어요.`
          : 'PDF를 만들지 못했어요.',
        en: error instanceof RangeError
          ? `Too many rows, so it was not built. There are ${api.getRowCount().toLocaleString('en-US')} rows in all and the limit is set to 1,000.`
          : 'Could not make the PDF.',
      });
    }
  },
};

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 @maxgrid/export-font-ko.

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">
    <button type="button" id="expandAll">Expand all</button>
    <button type="button" id="collapseAll">Collapse all</button>
    <button type="button" id="group">Build group PDF</button>
    <button type="button" id="xlsx">Download xlsx (with groups)</button>
    <select aria-label="Rows" id="size">
      <option value="20000">20,000 rows</option>
      <option value="100000">100,000 rows</option>
      <option value="300000" selected>300,000 rows</option>
    </select>
    <button type="button" id="big">Build full PDF</button>
    <button type="button" id="cancel">Cancel</button>
    <button type="button" id="limit">Test 1,000-row limit</button>
  </div>
  <div id="grid" style="height: 330px"></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('expandAll').addEventListener('click', () => actions.expandAll(api));
document.getElementById('collapseAll').addEventListener('click', () => actions.collapseAll(api));
document.getElementById('group').addEventListener('click', () => actions.group(api));
document.getElementById('xlsx').addEventListener('click', () => actions.xlsx(api));
document.getElementById('size').addEventListener('change', (event) => actions.size(api, event.target.value));
document.getElementById('big').addEventListener('click', () => actions.big(api));
document.getElementById('cancel').addEventListener('click', () => actions.cancel(api));
document.getElementById('limit').addEventListener('click', () => actions.limit(api));
example.js
import { withExport } from '@maxgrid/export';
// Turn the warnings sent by the library (technical terms) into plain English.
const warnText = (w) => w.code === 'missing-glyph'
  ? `Characters missing from the font were replaced with ?: ${w.characters}`
  : w.code === 'font-unavailable'
    ? 'The font could not be loaded, so the default font was used.'
    : 'Vertically merged cells were not merged in the PDF.';
// Lock the buttons while building, so pressing twice does not make two files.
async function busy(ids, work) {
  const buttons = ids
    .map((id) => document.getElementById(id))
    .filter((el) => el instanceof HTMLButtonElement);
  if (buttons.some((b) => b.disabled))
    return;
  for (const b of buttons)
    b.disabled = true;
  try {
    await work();
  }
  finally {
    for (const b of buttons)
      b.disabled = false;
  }
}
const regions = ['Seoul', 'Busan', 'Daejeon', 'Gwangju'];
// Row count choice: the default is a size where the PDF takes several seconds on this server, so you can press Cancel while it builds.
const DEFAULT_SIZE = 300_000;
const makeRows = (count) => Array.from({ length: count }, (_, i) => ({
  id: i + 1,
  region: regions[i % regions.length],
  code: `ORD-${String(i + 1).padStart(6, '0')}`,
  amount: ((i * 7919) % 90_000) + 1_000,
}));
// Many rows are built in chunks, so the page does not freeze, and the build can be cancelled or blocked by a row limit.
export const options = {
  columns: [
    { id: 'region', title: 'Region', width: 90 },
    // This column of a region (group) row shows the order count: a column without an aggregate is empty on group rows.
    {
      id: 'code',
      title: 'Order code',
      width: 130,
      aggregate: 'rowCount',
      aggregateFormat: (v) => `${Number(v).toLocaleString('en-US')} orders`,
    },
    {
      id: 'amount',
      title: 'Amount ($)',
      kind: 'number',
      width: 120,
      align: 'end',
      aggregate: 'sum',
      formatValue: (v) => Number(v).toLocaleString('en-US'),
      // Export group and total rows use the raw number without aggregateFormat, so give the same comma format as the screen here too.
      aggregateFormat: (v) => Number(v).toLocaleString('en-US'),
    },
  ],
  rows: makeRows(DEFAULT_SIZE),
  rowKey: 'id',
  grouping: { by: ['region'], expandDepth: 0 },
  summary: { label: 'Total' },
};
let say = () => { };
let ctrl;
export function setup(api, log) {
  say = log;
  withExport(api);
  return () => ctrl?.abort();
}
export const actions = {
  expandAll: (api) => api.expandAll(),
  collapseAll: (api) => api.collapseAll(),
  // Download the rows as they are on screen: collapsed gives only region rows and the total, expanded includes every order.
  group: async (api) => {
    await busy(['group', 'xlsx', 'big'], async () => {
      say('Building…');
      const warnings = [];
      await withExport(api).downloadPdf('orders-grouped.pdf', {
        font: false,
        hierarchy: true,
        onWarning: (w) => warnings.push(w),
      });
      for (const w of warnings)
        say(warnText(w));
      say(`Downloaded orders-grouped.pdf (${api.getVisibleRowCount().toLocaleString('en-US')} visible rows).`);
    });
  },
  xlsx: async (api) => {
    await busy(['group', 'xlsx', 'big'], async () => {
      await withExport(api).downloadXlsx('orders-grouped.xlsx', {
        hierarchy: true,
        applyFormatValue: false,
      });
      say(`Downloaded orders-grouped.xlsx (${api.getVisibleRowCount().toLocaleString('en-US')} visible rows).`);
    });
  },
  // Changing the row count refills the grid rows. It is not changed while a build is running.
  size: (api, value) => {
    if (ctrl)
      return;
    api.setRows(makeRows(Number(value) || DEFAULT_SIZE));
  },
  // Build every row of the chosen count in chunks. The page does not freeze while building and the build can be cancelled.
  big: async (api) => {
    await busy(['group', 'xlsx', 'big'], async () => {
      const mine = (ctrl = new AbortController());
      const started = Date.now();
      const count = api.getRowCount();
      say(`Building a ${count.toLocaleString('en-US')}-row PDF…`);
      try {
        await withExport(api).downloadPdf('orders-all.pdf', {
          rowScope: 'all',
          maxRows: 1_000_000, // Raise the default limit (100,000 rows) so larger counts can be chosen too.
          signal: mine.signal,
          font: false,
        });
        say(`Downloaded orders-all.pdf (${((Date.now() - started) / 1000).toFixed(1)} s).`);
      }
      catch {
        say(mine.signal.aborted
          ? 'Cancelled.'
          : 'Could not make the PDF. Please try again in a moment.');
      }
      finally {
        ctrl = undefined;
      }
    });
  },
  cancel: () => {
    if (!ctrl)
      return say('Nothing is being built.');
    ctrl.abort();
  },
  // If the row count is above the limit, block it before building anything.
  limit: async (api) => {
    try {
      await withExport(api).exportPdf({ rowScope: 'all', maxRows: 1_000 });
      say('The row count is within the limit, so it was built.');
    }
    catch (error) {
      say(error instanceof RangeError
        ? `Too many rows, so it was not built. There are ${api.getRowCount().toLocaleString('en-US')} rows in all and the limit is set to 1,000.`
        : 'Could not make the PDF.');
    }
  },
};