그룹·합계를 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.
코드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 @maxgrid/export-font-ko로 설치하세요.
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<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>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));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.',
});
}
},
}; 이 HTML은 추가 번들(위 script 태그)도 함께 불러오고 전역 변수로 써요. 별도 설치는 필요 없어요.
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>그룹·합계를 PDF·xlsx로, 많은 줄은 취소와 상한</title>
</head>
<body>
<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>
<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 src="https://cdn.jsdelivr.net/npm/@maxgrid/export-font-ko@1/dist/maxgrid.export-font-ko.min.js"></script>
<script>
const { withExport } = MaxGridExport;
const koreanFont = MaxGridExportFontKo;
// 라이브러리가 보내는 경고(영어·기술 용어)를 쉬운 한국어로 바꿔요.
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,
}));
// 많은 줄은 나눠서 만들어서 화면이 멈추지 않고, 도중에 취소하거나 줄 수 상한으로 막을 수 있어요.
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;
function setup(api, log) {
say = log;
withExport(api);
return () => ctrl?.abort();
}
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.',
});
}
},
};
options.ariaLabel = "그룹·합계를 PDF·xlsx로, 많은 줄은 취소와 상한";
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('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));
</script>
</body>
</html> 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i @maxgrid/react @maxgrid/export @maxgrid/export-font-ko로 설치하세요.
버튼을 누르면 이 예제의 코드가 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">
<button
type="button"
disabled={!api}
onClick={() => api && actions.expandAll(api)}
>모두 펼치기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.collapseAll(api)}
>모두 접기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.group(api)}
>그룹 PDF 만들기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.xlsx(api)}
>xlsx 내려받기 (그룹 포함)</button>
<select
aria-label="줄 수"
disabled={!api}
onChange={(event) => api && actions.size(api, event.target.value)}
>
<option value="20000">20,000줄</option>
<option value="100000">100,000줄</option>
<option value="300000">300,000줄</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.big(api)}
>전체 PDF 만들기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.cancel(api)}
>취소</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.limit(api)}
>1,000줄 상한 시험</button>
</div>
<Grid style={{ height: 330 }} ref={gridRef} options={options} />
</>
);
}import { withExport, type PdfWarning } from '@maxgrid/export';
import { koreanFont } from '@maxgrid/export-font-ko';
import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
// 라이브러리가 보내는 경고(영어·기술 용어)를 쉬운 한국어로 바꿔요.
const warnText = (w: PdfWarning): string =>
w.code === 'missing-glyph'
? `폰트에 없는 글자를 ?로 바꿨어요: ${w.characters}`
: w.code === 'font-unavailable'
? '한글 폰트를 불러오지 못해서 기본 폰트로 만들었어요.'
: '세로로 합친 칸은 PDF에서 합치지 않았어요.';
// 만드는 동안 버튼을 잠가서, 두 번 눌러도 파일이 두 개 만들어지지 않게 해요.
async function busy(ids: string[], work: () => Promise<void>): Promise<void> {
const buttons = ids
.map((id) => document.getElementById(id))
.filter((el): el is HTMLButtonElement => 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;
}
}
export interface Row {
id: number;
region: string;
code: string;
amount: number;
}
const regions = ['서울', '부산', '대전', '광주'];
// 줄 수 선택: 기본값은 이 서버에서 PDF가 수 초 걸리는 크기라서, 만드는 도중에 취소를 눌러 볼 수 있어요.
const DEFAULT_SIZE = 300_000;
const makeRows = (count: number): Row[] =>
Array.from({ length: count }, (_, i) => ({
id: i + 1,
region: regions[i % regions.length] as string,
code: `ORD-${String(i + 1).padStart(6, '0')}`,
amount: ((i * 7919) % 90_000) + 1_000,
}));
// 많은 줄은 나눠서 만들어서 화면이 멈추지 않고, 도중에 취소하거나 줄 수 상한으로 막을 수 있어요.
export const options: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let ctrl: AbortController | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
withExport(api);
return () => ctrl?.abort();
}
export const actions = {
expandAll: (api: GridApi<Row>) => api.expandAll(),
collapseAll: (api: GridApi<Row>) => api.collapseAll(),
// 지금 화면의 줄 그대로 내려받아요: 접혀 있으면 지역 줄과 합계만, 펼치면 모든 주문이 들어가요.
group: async (api: GridApi<Row>) => {
await busy(['group', 'xlsx', 'big'], async () => {
say({
ko: '만드는 중… 처음에는 한글 폰트를 읽느라 몇 초 걸려요.',
en: 'Building… the first time takes a few seconds to load the Korean font.',
});
const warnings: PdfWarning[] = [];
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: GridApi<Row>) => {
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: GridApi<Row>, value?: string) => {
if (ctrl) return;
api.setRows(makeRows(Number(value) || DEFAULT_SIZE));
},
// 고른 줄 수 전체를 나눠 만들어요. 만드는 동안에도 화면이 멈추지 않고 취소할 수 있어요.
big: async (api: GridApi<Row>) => {
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: GridApi<Row>) => {
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.',
});
}
},
}; 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i @maxgrid/vue @maxgrid/export @maxgrid/export-font-ko로 설치하세요.
버튼을 누르면 이 예제의 코드가 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">
<button
type="button"
:disabled="!api"
@click="api && actions.expandAll(api)"
>모두 펼치기</button>
<button
type="button"
:disabled="!api"
@click="api && actions.collapseAll(api)"
>모두 접기</button>
<button type="button" :disabled="!api" @click="api && actions.group(api)">그룹 PDF 만들기</button>
<button type="button" :disabled="!api" @click="api && actions.xlsx(api)">xlsx 내려받기 (그룹 포함)</button>
<select
aria-label="줄 수"
:disabled="!api"
@change="api && actions.size(api, ($event.target as HTMLSelectElement).value)"
>
<option value="20000">20,000줄</option>
<option value="100000">100,000줄</option>
<option value="300000" selected>300,000줄</option>
</select>
<button type="button" :disabled="!api" @click="api && actions.big(api)">전체 PDF 만들기</button>
<button type="button" :disabled="!api" @click="api && actions.cancel(api)">취소</button>
<button type="button" :disabled="!api" @click="api && actions.limit(api)">1,000줄 상한 시험</button>
</div>
<Grid style="height: 330px" :options="options" @ready="onReady" />
</template>import { withExport, type PdfWarning } from '@maxgrid/export';
import { koreanFont } from '@maxgrid/export-font-ko';
import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
// 라이브러리가 보내는 경고(영어·기술 용어)를 쉬운 한국어로 바꿔요.
const warnText = (w: PdfWarning): string =>
w.code === 'missing-glyph'
? `폰트에 없는 글자를 ?로 바꿨어요: ${w.characters}`
: w.code === 'font-unavailable'
? '한글 폰트를 불러오지 못해서 기본 폰트로 만들었어요.'
: '세로로 합친 칸은 PDF에서 합치지 않았어요.';
// 만드는 동안 버튼을 잠가서, 두 번 눌러도 파일이 두 개 만들어지지 않게 해요.
async function busy(ids: string[], work: () => Promise<void>): Promise<void> {
const buttons = ids
.map((id) => document.getElementById(id))
.filter((el): el is HTMLButtonElement => 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;
}
}
export interface Row {
id: number;
region: string;
code: string;
amount: number;
}
const regions = ['서울', '부산', '대전', '광주'];
// 줄 수 선택: 기본값은 이 서버에서 PDF가 수 초 걸리는 크기라서, 만드는 도중에 취소를 눌러 볼 수 있어요.
const DEFAULT_SIZE = 300_000;
const makeRows = (count: number): Row[] =>
Array.from({ length: count }, (_, i) => ({
id: i + 1,
region: regions[i % regions.length] as string,
code: `ORD-${String(i + 1).padStart(6, '0')}`,
amount: ((i * 7919) % 90_000) + 1_000,
}));
// 많은 줄은 나눠서 만들어서 화면이 멈추지 않고, 도중에 취소하거나 줄 수 상한으로 막을 수 있어요.
export const options: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let ctrl: AbortController | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
withExport(api);
return () => ctrl?.abort();
}
export const actions = {
expandAll: (api: GridApi<Row>) => api.expandAll(),
collapseAll: (api: GridApi<Row>) => api.collapseAll(),
// 지금 화면의 줄 그대로 내려받아요: 접혀 있으면 지역 줄과 합계만, 펼치면 모든 주문이 들어가요.
group: async (api: GridApi<Row>) => {
await busy(['group', 'xlsx', 'big'], async () => {
say({
ko: '만드는 중… 처음에는 한글 폰트를 읽느라 몇 초 걸려요.',
en: 'Building… the first time takes a few seconds to load the Korean font.',
});
const warnings: PdfWarning[] = [];
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: GridApi<Row>) => {
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: GridApi<Row>, value?: string) => {
if (ctrl) return;
api.setRows(makeRows(Number(value) || DEFAULT_SIZE));
},
// 고른 줄 수 전체를 나눠 만들어요. 만드는 동안에도 화면이 멈추지 않고 취소할 수 있어요.
big: async (api: GridApi<Row>) => {
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: GridApi<Row>) => {
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.',
});
}
},
}; 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i @maxgrid/angular @maxgrid/export @maxgrid/export-font-ko로 설치하세요.
버튼을 누르면 이 예제의 코드가 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">
<button
type="button"
[disabled]="!api"
(click)="api && actions.expandAll(api)"
>모두 펼치기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.collapseAll(api)"
>모두 접기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.group(api)"
>그룹 PDF 만들기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.xlsx(api)"
>xlsx 내려받기 (그룹 포함)</button>
<select
aria-label="줄 수"
[disabled]="!api"
(change)="api && actions.size(api, $any($event.target).value)"
>
<option value="20000">20,000줄</option>
<option value="100000">100,000줄</option>
<option value="300000" selected>300,000줄</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.big(api)"
>전체 PDF 만들기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.cancel(api)"
>취소</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.limit(api)"
>1,000줄 상한 시험</button>
</div>
<mx-grid style="height: 330px" [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, type PdfWarning } from '@maxgrid/export';
import { koreanFont } from '@maxgrid/export-font-ko';
import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
// 라이브러리가 보내는 경고(영어·기술 용어)를 쉬운 한국어로 바꿔요.
const warnText = (w: PdfWarning): string =>
w.code === 'missing-glyph'
? `폰트에 없는 글자를 ?로 바꿨어요: ${w.characters}`
: w.code === 'font-unavailable'
? '한글 폰트를 불러오지 못해서 기본 폰트로 만들었어요.'
: '세로로 합친 칸은 PDF에서 합치지 않았어요.';
// 만드는 동안 버튼을 잠가서, 두 번 눌러도 파일이 두 개 만들어지지 않게 해요.
async function busy(ids: string[], work: () => Promise<void>): Promise<void> {
const buttons = ids
.map((id) => document.getElementById(id))
.filter((el): el is HTMLButtonElement => 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;
}
}
export interface Row {
id: number;
region: string;
code: string;
amount: number;
}
const regions = ['서울', '부산', '대전', '광주'];
// 줄 수 선택: 기본값은 이 서버에서 PDF가 수 초 걸리는 크기라서, 만드는 도중에 취소를 눌러 볼 수 있어요.
const DEFAULT_SIZE = 300_000;
const makeRows = (count: number): Row[] =>
Array.from({ length: count }, (_, i) => ({
id: i + 1,
region: regions[i % regions.length] as string,
code: `ORD-${String(i + 1).padStart(6, '0')}`,
amount: ((i * 7919) % 90_000) + 1_000,
}));
// 많은 줄은 나눠서 만들어서 화면이 멈추지 않고, 도중에 취소하거나 줄 수 상한으로 막을 수 있어요.
export const options: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let ctrl: AbortController | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
withExport(api);
return () => ctrl?.abort();
}
export const actions = {
expandAll: (api: GridApi<Row>) => api.expandAll(),
collapseAll: (api: GridApi<Row>) => api.collapseAll(),
// 지금 화면의 줄 그대로 내려받아요: 접혀 있으면 지역 줄과 합계만, 펼치면 모든 주문이 들어가요.
group: async (api: GridApi<Row>) => {
await busy(['group', 'xlsx', 'big'], async () => {
say({
ko: '만드는 중… 처음에는 한글 폰트를 읽느라 몇 초 걸려요.',
en: 'Building… the first time takes a few seconds to load the Korean font.',
});
const warnings: PdfWarning[] = [];
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: GridApi<Row>) => {
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: GridApi<Row>, value?: string) => {
if (ctrl) return;
api.setRows(makeRows(Number(value) || DEFAULT_SIZE));
},
// 고른 줄 수 전체를 나눠 만들어요. 만드는 동안에도 화면이 멈추지 않고 취소할 수 있어요.
big: async (api: GridApi<Row>) => {
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: GridApi<Row>) => {
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.',
});
}
},
}; 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.
<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>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));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.');
}
},
};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>Groups and totals in PDF and xlsx; cancel and limit for large exports</title>
</head>
<body>
<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>
<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;
// 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.
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;
function setup(api, log) {
say = log;
withExport(api);
return () => ctrl?.abort();
}
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.');
}
},
};
options.ariaLabel = "Groups and totals in PDF and xlsx; cancel and limit for large exports";
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('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));
</script>
</body>
</html> This example needs an extra package. To run it locally, install with npm i @maxgrid/react @maxgrid/export @maxgrid/export-font-ko.
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">
<button
type="button"
disabled={!api}
onClick={() => api && actions.expandAll(api)}
>Expand all</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.collapseAll(api)}
>Collapse all</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.group(api)}
>Build group PDF</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.xlsx(api)}
>Download xlsx (with groups)</button>
<select
aria-label="Rows"
disabled={!api}
onChange={(event) => api && actions.size(api, event.target.value)}
>
<option value="20000">20,000 rows</option>
<option value="100000">100,000 rows</option>
<option value="300000">300,000 rows</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.big(api)}
>Build full PDF</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.cancel(api)}
>Cancel</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.limit(api)}
>Test 1,000-row limit</button>
</div>
<Grid style={{ height: 330 }} ref={gridRef} options={options} />
</>
);
}import { withExport, type PdfWarning } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
// Turn the warnings sent by the library (technical terms) into plain English.
const warnText = (w: PdfWarning): string =>
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: string[], work: () => Promise<void>): Promise<void> {
const buttons = ids
.map((id) => document.getElementById(id))
.filter((el): el is HTMLButtonElement => 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;
}
}
export interface Row {
id: number;
region: string;
code: string;
amount: number;
}
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: number): Row[] =>
Array.from({ length: count }, (_, i) => ({
id: i + 1,
region: regions[i % regions.length] as string,
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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let ctrl: AbortController | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
withExport(api);
return () => ctrl?.abort();
}
export const actions = {
expandAll: (api: GridApi<Row>) => api.expandAll(),
collapseAll: (api: GridApi<Row>) => 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: GridApi<Row>) => {
await busy(['group', 'xlsx', 'big'], async () => {
say('Building…');
const warnings: PdfWarning[] = [];
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: GridApi<Row>) => {
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: GridApi<Row>, value?: string) => {
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: GridApi<Row>) => {
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: GridApi<Row>) => {
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.',
);
}
},
}; This example needs an extra package. To run it locally, install with npm i @maxgrid/vue @maxgrid/export @maxgrid/export-font-ko.
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">
<button
type="button"
:disabled="!api"
@click="api && actions.expandAll(api)"
>Expand all</button>
<button
type="button"
:disabled="!api"
@click="api && actions.collapseAll(api)"
>Collapse all</button>
<button type="button" :disabled="!api" @click="api && actions.group(api)">Build group PDF</button>
<button type="button" :disabled="!api" @click="api && actions.xlsx(api)">Download xlsx (with groups)</button>
<select
aria-label="Rows"
:disabled="!api"
@change="api && actions.size(api, ($event.target as HTMLSelectElement).value)"
>
<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" :disabled="!api" @click="api && actions.big(api)">Build full PDF</button>
<button type="button" :disabled="!api" @click="api && actions.cancel(api)">Cancel</button>
<button type="button" :disabled="!api" @click="api && actions.limit(api)">Test 1,000-row limit</button>
</div>
<Grid style="height: 330px" :options="options" @ready="onReady" />
</template>import { withExport, type PdfWarning } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
// Turn the warnings sent by the library (technical terms) into plain English.
const warnText = (w: PdfWarning): string =>
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: string[], work: () => Promise<void>): Promise<void> {
const buttons = ids
.map((id) => document.getElementById(id))
.filter((el): el is HTMLButtonElement => 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;
}
}
export interface Row {
id: number;
region: string;
code: string;
amount: number;
}
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: number): Row[] =>
Array.from({ length: count }, (_, i) => ({
id: i + 1,
region: regions[i % regions.length] as string,
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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let ctrl: AbortController | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
withExport(api);
return () => ctrl?.abort();
}
export const actions = {
expandAll: (api: GridApi<Row>) => api.expandAll(),
collapseAll: (api: GridApi<Row>) => 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: GridApi<Row>) => {
await busy(['group', 'xlsx', 'big'], async () => {
say('Building…');
const warnings: PdfWarning[] = [];
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: GridApi<Row>) => {
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: GridApi<Row>, value?: string) => {
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: GridApi<Row>) => {
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: GridApi<Row>) => {
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.',
);
}
},
}; This example needs an extra package. To run it locally, install with npm i @maxgrid/angular @maxgrid/export @maxgrid/export-font-ko.
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">
<button
type="button"
[disabled]="!api"
(click)="api && actions.expandAll(api)"
>Expand all</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.collapseAll(api)"
>Collapse all</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.group(api)"
>Build group PDF</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.xlsx(api)"
>Download xlsx (with groups)</button>
<select
aria-label="Rows"
[disabled]="!api"
(change)="api && actions.size(api, $any($event.target).value)"
>
<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"
[disabled]="!api"
(click)="api && actions.big(api)"
>Build full PDF</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.cancel(api)"
>Cancel</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.limit(api)"
>Test 1,000-row limit</button>
</div>
<mx-grid style="height: 330px" [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, type PdfWarning } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string;
// Turn the warnings sent by the library (technical terms) into plain English.
const warnText = (w: PdfWarning): string =>
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: string[], work: () => Promise<void>): Promise<void> {
const buttons = ids
.map((id) => document.getElementById(id))
.filter((el): el is HTMLButtonElement => 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;
}
}
export interface Row {
id: number;
region: string;
code: string;
amount: number;
}
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: number): Row[] =>
Array.from({ length: count }, (_, i) => ({
id: i + 1,
region: regions[i % regions.length] as string,
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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let ctrl: AbortController | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
withExport(api);
return () => ctrl?.abort();
}
export const actions = {
expandAll: (api: GridApi<Row>) => api.expandAll(),
collapseAll: (api: GridApi<Row>) => 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: GridApi<Row>) => {
await busy(['group', 'xlsx', 'big'], async () => {
say('Building…');
const warnings: PdfWarning[] = [];
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: GridApi<Row>) => {
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: GridApi<Row>, value?: string) => {
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: GridApi<Row>) => {
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: GridApi<Row>) => {
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.',
);
}
},
};