한글 PDF: 폰트 넣기Korean PDF: embed a font
한글 폰트를 넣은 PDF와 폰트 없이 만든 PDF를 비교하고, 빠진 글자는 경고로 알려 줘요.Compare a PDF made with a Korean font and without; missing glyphs are reported as warnings.
코드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">
<select aria-label="폰트" id="mode">
<option value="korean" selected>한글 폰트 넣기</option>
<option value="none">폰트 없음</option>
</select>
<button type="button" id="build">만들어 보기</button>
<button type="button" id="download">내려받기</button>
</div>
<div id="grid" style="height: 300px"></div>
</div>
<script type="module" src="./main.js"></script>import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('build').addEventListener('click', () => actions.build(api));
document.getElementById('download').addEventListener('click', () => actions.download(api));import { exportPdf, withExport } from '@maxgrid/export';
import { createKoreanFont } 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 customers = ['한빛푸드', '소나무철물', '파란마켓', '단풍상회', '바다유통', '새벽식자재'];
const regions = ['서울', '부산', '대전', '광주'];
const rows = Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
orderNo: `SO-${3001 + i}`,
customer: customers[i % customers.length],
region: regions[i % regions.length],
qty: 3 + ((i * 7) % 28),
price: 4200 + ((i * 1900) % 21000),
orderedAt: new Date(2026, 9, 1 + i * 2),
}));
// PDF 기본 폰트는 한글 글자가 없어요. 한글 폰트 패키지를 넣으면 한글이 나오고, 폰트를 끄면 한글이 ?로 바뀌어요.
export const options = {
columns: [
{ id: 'orderNo', title: '주문번호', width: 100 },
{ id: 'customer', title: '거래처', width: 110 },
{ id: 'region', title: '지역', width: 70 },
{ id: 'qty', title: '수량', kind: 'number', width: 70, align: 'end' },
{
id: 'price',
title: '단가(원)',
kind: 'number',
width: 100,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
{ id: 'orderedAt', title: '주문일', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
};
let mode = 'korean';
let say = () => { };
export function setup(api, log) {
say = log;
withExport(api);
}
// 글꼴 로더는 한 번만 만들어요. onProgress가 받은 바이트를 알려 주면 아래 work()가 "받는 중 3.1 / 10.4 MB"로 보여 줘요.
// (스크립트 태그로 돌리는 "HTML" 탭에서는 전역 글꼴을 그대로 쓰니까 진행 알림이 없고, 대신 몇 초째인지 알려 줘요.)
let gotBytes = 0;
let onBytes = () => { };
const koreanFont = createKoreanFont({
onProgress: ({ loaded }) => {
gotBytes = loaded;
onBytes();
},
});
// 진행 표시: 막대 하나를 제자리에서 바꿔요(기록에 줄을 쌓지 않아요). 값을 모르면 움직이는 막대예요.
function progressBar() {
let box = document.getElementById('pdf-progress');
if (!box) {
box = document.createElement('div');
box.id = 'pdf-progress';
box.className = 'pg-x';
box.hidden = true;
box.setAttribute('role', 'status');
box.innerHTML = '<progress max="100"></progress><span lang="ko"></span><span lang="en"></span>';
const log = document.getElementById('log');
if (log)
log.before(box);
else
document.body.append(box);
}
const root = box;
const bar = root.querySelector('progress');
const [ko, en] = Array.from(root.querySelectorAll('span'));
return {
show(text, percent) {
root.hidden = false;
if (percent === undefined)
bar.removeAttribute('value');
else
bar.value = percent;
if (ko)
ko.textContent = text.ko;
if (en)
en.textContent = text.en;
},
hide() {
root.hidden = true;
bar.removeAttribute('value');
if (ko)
ko.textContent = '';
if (en)
en.textContent = '';
},
};
}
const FONT_BYTES = { ko: 10_414_588 };
const totalBytes = () => FONT_BYTES.ko;
const loadedBytes = () => gotBytes;
let fontLoaded = false;
/** 글꼴을 받고 PDF를 만드는 일을 감싼다: 안내, 진행 막대, 실패 안내(다시 눌러 보라는 말). 기술적인 오류 내용은 콘솔에만 남긴다. */
async function work(job) {
await busy(['build', 'download'], async () => {
const usesFont = mode === 'korean';
const mb = (totalBytes() / 1e6).toFixed(1);
const bar = progressBar();
if (usesFont && !fontLoaded)
say({
ko: `처음 한 번은 글꼴 약 ${mb}MB를 받아요(Noto Sans KR). 연결이 느리면 20초 넘게 걸릴 수 있고, 두 번째부터는 바로 만들어져요.`,
en: `The first time, about ${mb} MB of Korean font is downloaded (Noto Sans KR). On a slow connection it can take over 20 seconds; later PDFs are made right away.`,
});
const started = Date.now();
let receiving = false;
gotBytes = 0;
const making = { ko: 'PDF를 만드는 중이에요…', en: 'Making the PDF…' };
const waiting = () => {
const s = Math.round((Date.now() - started) / 1000);
bar.show({
ko: `글꼴을 받는 중이에요… ${s}초${s >= 10 ? ' (연결이 느리면 더 걸려요)' : ''}`,
en: `Downloading the font… ${s} s${s >= 10 ? ' (a slow connection takes longer)' : ''}`,
});
};
if (usesFont && !fontLoaded)
waiting();
else
bar.show(making);
// 받은 바이트가 오면 막대가 실제 비율로 바뀌고, 다 받으면 "PDF를 만드는 중"으로 넘어가요.
onBytes = () => {
receiving = true;
const loaded = loadedBytes();
const total = totalBytes();
if (loaded >= total)
return bar.show(making);
const pct = Math.floor((loaded / total) * 100);
const a = (loaded / 1e6).toFixed(1);
bar.show({
ko: `글꼴 받는 중 ${a} / ${mb} MB (${pct}%)`,
en: `Downloading the font ${a} / ${mb} MB (${pct}%)`,
}, pct);
};
// 받은 바이트 알림이 없으면(스크립트 태그로 도는 탭 등) 몇 초째인지만 1초마다 바꿔요.
const timer = setInterval(() => {
if (usesFont && !fontLoaded && !receiving)
waiting();
}, 1000);
try {
await job();
if (usesFont)
fontLoaded = true;
}
catch (error) {
clearInterval(timer);
onBytes = () => { };
bar.hide(); // 실패 안내보다 먼저 지워서, 옛 "받는 중" 줄이 남지 않게 해요.
console.error('[PDF 예제] 글꼴을 받거나 PDF를 만드는 데 실패했어요', error);
say({
ko: '글꼴을 받지 못해서 PDF를 만들지 못했어요. 인터넷 연결을 확인한 뒤 버튼을 다시 눌러 주세요.',
en: 'The PDF could not be made because the font could not be downloaded. Check your internet connection and press the button again.',
});
}
finally {
clearInterval(timer);
onBytes = () => { };
bar.hide();
}
});
}
export const actions = {
mode: (_api, v) => void (mode = v ?? 'korean'),
build: async (api) => {
await work(async () => {
const warnings = [];
const bytes = await exportPdf(api, {
font: mode === 'korean' ? koreanFont : false,
onWarning: (w) => warnings.push(w),
});
// 기록은 위가 최신이라, 결과 줄을 마지막에 적어야 맨 위에 보여요.
for (const w of warnings)
say(warnText(w));
if (warnings.length === 0)
say({
ko: '경고가 없어요. 한글이 그대로 들어갔어요.',
en: 'No warnings. The Korean text went in as it is.',
});
say({
ko: `${bytes.length.toLocaleString('ko-KR')}바이트를 만들었어요.`,
en: `Made ${bytes.length.toLocaleString('en-US')} bytes.`,
});
});
},
download: async (api) => {
await work(async () => {
const warnings = [];
await withExport(api).downloadPdf('주문-폰트.pdf', {
font: mode === 'korean' ? koreanFont : false,
onWarning: (w) => warnings.push(w),
});
for (const w of warnings)
say(warnText(w));
say({ ko: '주문-폰트.pdf를 내려받았어요.', en: 'Downloaded 주문-폰트.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: 폰트 넣기</title>
</head>
<body>
<div class="toolbar">
<select aria-label="폰트" id="mode">
<option value="korean" selected>한글 폰트 넣기</option>
<option value="none">폰트 없음</option>
</select>
<button type="button" id="build">만들어 보기</button>
<button type="button" id="download">내려받기</button>
</div>
<div id="grid" style="height: 300px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.export.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@maxgrid/export-font-ko@1/dist/maxgrid.export-font-ko.min.js"></script>
<script>
const { exportPdf, withExport } = MaxGridExport;
const createKoreanFont = () => 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 customers = ['한빛푸드', '소나무철물', '파란마켓', '단풍상회', '바다유통', '새벽식자재'];
const regions = ['서울', '부산', '대전', '광주'];
const rows = Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
orderNo: `SO-${3001 + i}`,
customer: customers[i % customers.length],
region: regions[i % regions.length],
qty: 3 + ((i * 7) % 28),
price: 4200 + ((i * 1900) % 21000),
orderedAt: new Date(2026, 9, 1 + i * 2),
}));
// PDF 기본 폰트는 한글 글자가 없어요. 한글 폰트 패키지를 넣으면 한글이 나오고, 폰트를 끄면 한글이 ?로 바뀌어요.
const options = {
columns: [
{ id: 'orderNo', title: '주문번호', width: 100 },
{ id: 'customer', title: '거래처', width: 110 },
{ id: 'region', title: '지역', width: 70 },
{ id: 'qty', title: '수량', kind: 'number', width: 70, align: 'end' },
{
id: 'price',
title: '단가(원)',
kind: 'number',
width: 100,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
{ id: 'orderedAt', title: '주문일', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
};
let mode = 'korean';
let say = () => { };
function setup(api, log) {
say = log;
withExport(api);
}
// 글꼴 로더는 한 번만 만들어요. onProgress가 받은 바이트를 알려 주면 아래 work()가 "받는 중 3.1 / 10.4 MB"로 보여 줘요.
// (스크립트 태그로 돌리는 "HTML" 탭에서는 전역 글꼴을 그대로 쓰니까 진행 알림이 없고, 대신 몇 초째인지 알려 줘요.)
let gotBytes = 0;
let onBytes = () => { };
const koreanFont = createKoreanFont({
onProgress: ({ loaded }) => {
gotBytes = loaded;
onBytes();
},
});
// 진행 표시: 막대 하나를 제자리에서 바꿔요(기록에 줄을 쌓지 않아요). 값을 모르면 움직이는 막대예요.
function progressBar() {
let box = document.getElementById('pdf-progress');
if (!box) {
box = document.createElement('div');
box.id = 'pdf-progress';
box.className = 'pg-x';
box.hidden = true;
box.setAttribute('role', 'status');
box.innerHTML = '<progress max="100"></progress><span lang="ko"></span><span lang="en"></span>';
const log = document.getElementById('log');
if (log)
log.before(box);
else
document.body.append(box);
}
const root = box;
const bar = root.querySelector('progress');
const [ko, en] = Array.from(root.querySelectorAll('span'));
return {
show(text, percent) {
root.hidden = false;
if (percent === undefined)
bar.removeAttribute('value');
else
bar.value = percent;
if (ko)
ko.textContent = text.ko;
if (en)
en.textContent = text.en;
},
hide() {
root.hidden = true;
bar.removeAttribute('value');
if (ko)
ko.textContent = '';
if (en)
en.textContent = '';
},
};
}
const FONT_BYTES = { ko: 10_414_588 };
const totalBytes = () => FONT_BYTES.ko;
const loadedBytes = () => gotBytes;
let fontLoaded = false;
/** 글꼴을 받고 PDF를 만드는 일을 감싼다: 안내, 진행 막대, 실패 안내(다시 눌러 보라는 말). 기술적인 오류 내용은 콘솔에만 남긴다. */
async function work(job) {
await busy(['build', 'download'], async () => {
const usesFont = mode === 'korean';
const mb = (totalBytes() / 1e6).toFixed(1);
const bar = progressBar();
if (usesFont && !fontLoaded)
say({
ko: `처음 한 번은 글꼴 약 ${mb}MB를 받아요(Noto Sans KR). 연결이 느리면 20초 넘게 걸릴 수 있고, 두 번째부터는 바로 만들어져요.`,
en: `The first time, about ${mb} MB of Korean font is downloaded (Noto Sans KR). On a slow connection it can take over 20 seconds; later PDFs are made right away.`,
});
const started = Date.now();
let receiving = false;
gotBytes = 0;
const making = { ko: 'PDF를 만드는 중이에요…', en: 'Making the PDF…' };
const waiting = () => {
const s = Math.round((Date.now() - started) / 1000);
bar.show({
ko: `글꼴을 받는 중이에요… ${s}초${s >= 10 ? ' (연결이 느리면 더 걸려요)' : ''}`,
en: `Downloading the font… ${s} s${s >= 10 ? ' (a slow connection takes longer)' : ''}`,
});
};
if (usesFont && !fontLoaded)
waiting();
else
bar.show(making);
// 받은 바이트가 오면 막대가 실제 비율로 바뀌고, 다 받으면 "PDF를 만드는 중"으로 넘어가요.
onBytes = () => {
receiving = true;
const loaded = loadedBytes();
const total = totalBytes();
if (loaded >= total)
return bar.show(making);
const pct = Math.floor((loaded / total) * 100);
const a = (loaded / 1e6).toFixed(1);
bar.show({
ko: `글꼴 받는 중 ${a} / ${mb} MB (${pct}%)`,
en: `Downloading the font ${a} / ${mb} MB (${pct}%)`,
}, pct);
};
// 받은 바이트 알림이 없으면(스크립트 태그로 도는 탭 등) 몇 초째인지만 1초마다 바꿔요.
const timer = setInterval(() => {
if (usesFont && !fontLoaded && !receiving)
waiting();
}, 1000);
try {
await job();
if (usesFont)
fontLoaded = true;
}
catch (error) {
clearInterval(timer);
onBytes = () => { };
bar.hide(); // 실패 안내보다 먼저 지워서, 옛 "받는 중" 줄이 남지 않게 해요.
console.error('[PDF 예제] 글꼴을 받거나 PDF를 만드는 데 실패했어요', error);
say({
ko: '글꼴을 받지 못해서 PDF를 만들지 못했어요. 인터넷 연결을 확인한 뒤 버튼을 다시 눌러 주세요.',
en: 'The PDF could not be made because the font could not be downloaded. Check your internet connection and press the button again.',
});
}
finally {
clearInterval(timer);
onBytes = () => { };
bar.hide();
}
});
}
const actions = {
mode: (_api, v) => void (mode = v ?? 'korean'),
build: async (api) => {
await work(async () => {
const warnings = [];
const bytes = await exportPdf(api, {
font: mode === 'korean' ? koreanFont : false,
onWarning: (w) => warnings.push(w),
});
// 기록은 위가 최신이라, 결과 줄을 마지막에 적어야 맨 위에 보여요.
for (const w of warnings)
say(warnText(w));
if (warnings.length === 0)
say({
ko: '경고가 없어요. 한글이 그대로 들어갔어요.',
en: 'No warnings. The Korean text went in as it is.',
});
say({
ko: `${bytes.length.toLocaleString('ko-KR')}바이트를 만들었어요.`,
en: `Made ${bytes.length.toLocaleString('en-US')} bytes.`,
});
});
},
download: async (api) => {
await work(async () => {
const warnings = [];
await withExport(api).downloadPdf('주문-폰트.pdf', {
font: mode === 'korean' ? koreanFont : false,
onWarning: (w) => warnings.push(w),
});
for (const w of warnings)
say(warnText(w));
say({ ko: '주문-폰트.pdf를 내려받았어요.', en: 'Downloaded 주문-폰트.pdf.' });
});
},
};
options.ariaLabel = "한글 PDF: 폰트 넣기";
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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('build').addEventListener('click', () => actions.build(api));
document.getElementById('download').addEventListener('click', () => actions.download(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">
<select
aria-label="폰트"
disabled={!api}
onChange={(event) => api && actions.mode(api, event.target.value)}
>
<option value="korean">한글 폰트 넣기</option>
<option value="none">폰트 없음</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.build(api)}
>만들어 보기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.download(api)}
>내려받기</button>
</div>
<Grid style={{ height: 300 }} ref={gridRef} options={options} />
</>
);
}import { exportPdf, withExport, type PdfWarning } from '@maxgrid/export';
import { createKoreanFont } 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;
orderNo: string;
customer: string;
region: string;
qty: number;
price: number;
orderedAt: Date;
}
const customers = ['한빛푸드', '소나무철물', '파란마켓', '단풍상회', '바다유통', '새벽식자재'];
const regions = ['서울', '부산', '대전', '광주'];
const rows: Row[] = Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
orderNo: `SO-${3001 + i}`,
customer: customers[i % customers.length] as string,
region: regions[i % regions.length] as string,
qty: 3 + ((i * 7) % 28),
price: 4200 + ((i * 1900) % 21000),
orderedAt: new Date(2026, 9, 1 + i * 2),
}));
// PDF 기본 폰트는 한글 글자가 없어요. 한글 폰트 패키지를 넣으면 한글이 나오고, 폰트를 끄면 한글이 ?로 바뀌어요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'orderNo', title: '주문번호', width: 100 },
{ id: 'customer', title: '거래처', width: 110 },
{ id: 'region', title: '지역', width: 70 },
{ id: 'qty', title: '수량', kind: 'number', width: 70, align: 'end' },
{
id: 'price',
title: '단가(원)',
kind: 'number',
width: 100,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
{ id: 'orderedAt', title: '주문일', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
};
let mode = 'korean';
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
withExport(api);
}
// 글꼴 로더는 한 번만 만들어요. onProgress가 받은 바이트를 알려 주면 아래 work()가 "받는 중 3.1 / 10.4 MB"로 보여 줘요.
// (스크립트 태그로 돌리는 "HTML" 탭에서는 전역 글꼴을 그대로 쓰니까 진행 알림이 없고, 대신 몇 초째인지 알려 줘요.)
let gotBytes = 0;
let onBytes: () => void = () => {};
const koreanFont = createKoreanFont({
onProgress: ({ loaded }) => {
gotBytes = loaded;
onBytes();
},
});
// 진행 표시: 막대 하나를 제자리에서 바꿔요(기록에 줄을 쌓지 않아요). 값을 모르면 움직이는 막대예요.
function progressBar() {
let box = document.getElementById('pdf-progress');
if (!box) {
box = document.createElement('div');
box.id = 'pdf-progress';
box.className = 'pg-x';
box.hidden = true;
box.setAttribute('role', 'status');
box.innerHTML = '<progress max="100"></progress><span lang="ko"></span><span lang="en"></span>';
const log = document.getElementById('log');
if (log) log.before(box);
else document.body.append(box);
}
const root = box;
const bar = root.querySelector('progress') as HTMLProgressElement;
const [ko, en] = Array.from(root.querySelectorAll('span'));
return {
show(text: { ko: string; en: string }, percent?: number) {
root.hidden = false;
if (percent === undefined) bar.removeAttribute('value');
else bar.value = percent;
if (ko) ko.textContent = text.ko;
if (en) en.textContent = text.en;
},
hide() {
root.hidden = true;
bar.removeAttribute('value');
if (ko) ko.textContent = '';
if (en) en.textContent = '';
},
};
}
const FONT_BYTES = { ko: 10_414_588 };
const totalBytes = () => FONT_BYTES.ko;
const loadedBytes = () => gotBytes;
let fontLoaded = false;
/** 글꼴을 받고 PDF를 만드는 일을 감싼다: 안내, 진행 막대, 실패 안내(다시 눌러 보라는 말). 기술적인 오류 내용은 콘솔에만 남긴다. */
async function work(job: () => Promise<void>): Promise<void> {
await busy(['build', 'download'], async () => {
const usesFont = mode === 'korean';
const mb = (totalBytes() / 1e6).toFixed(1);
const bar = progressBar();
if (usesFont && !fontLoaded)
say({
ko: `처음 한 번은 글꼴 약 ${mb}MB를 받아요(Noto Sans KR). 연결이 느리면 20초 넘게 걸릴 수 있고, 두 번째부터는 바로 만들어져요.`,
en: `The first time, about ${mb} MB of Korean font is downloaded (Noto Sans KR). On a slow connection it can take over 20 seconds; later PDFs are made right away.`,
});
const started = Date.now();
let receiving = false;
gotBytes = 0;
const making = { ko: 'PDF를 만드는 중이에요…', en: 'Making the PDF…' };
const waiting = () => {
const s = Math.round((Date.now() - started) / 1000);
bar.show({
ko: `글꼴을 받는 중이에요… ${s}초${s >= 10 ? ' (연결이 느리면 더 걸려요)' : ''}`,
en: `Downloading the font… ${s} s${s >= 10 ? ' (a slow connection takes longer)' : ''}`,
});
};
if (usesFont && !fontLoaded) waiting();
else bar.show(making);
// 받은 바이트가 오면 막대가 실제 비율로 바뀌고, 다 받으면 "PDF를 만드는 중"으로 넘어가요.
onBytes = () => {
receiving = true;
const loaded = loadedBytes();
const total = totalBytes();
if (loaded >= total) return bar.show(making);
const pct = Math.floor((loaded / total) * 100);
const a = (loaded / 1e6).toFixed(1);
bar.show(
{
ko: `글꼴 받는 중 ${a} / ${mb} MB (${pct}%)`,
en: `Downloading the font ${a} / ${mb} MB (${pct}%)`,
},
pct,
);
};
// 받은 바이트 알림이 없으면(스크립트 태그로 도는 탭 등) 몇 초째인지만 1초마다 바꿔요.
const timer = setInterval(() => {
if (usesFont && !fontLoaded && !receiving) waiting();
}, 1000);
try {
await job();
if (usesFont) fontLoaded = true;
} catch (error) {
clearInterval(timer);
onBytes = () => {};
bar.hide(); // 실패 안내보다 먼저 지워서, 옛 "받는 중" 줄이 남지 않게 해요.
console.error('[PDF 예제] 글꼴을 받거나 PDF를 만드는 데 실패했어요', error);
say({
ko: '글꼴을 받지 못해서 PDF를 만들지 못했어요. 인터넷 연결을 확인한 뒤 버튼을 다시 눌러 주세요.',
en: 'The PDF could not be made because the font could not be downloaded. Check your internet connection and press the button again.',
});
} finally {
clearInterval(timer);
onBytes = () => {};
bar.hide();
}
});
}
export const actions = {
mode: (_api: GridApi<Row>, v?: string) => void (mode = v ?? 'korean'),
build: async (api: GridApi<Row>) => {
await work(async () => {
const warnings: PdfWarning[] = [];
const bytes = await exportPdf(api, {
font: mode === 'korean' ? koreanFont : false,
onWarning: (w) => warnings.push(w),
});
// 기록은 위가 최신이라, 결과 줄을 마지막에 적어야 맨 위에 보여요.
for (const w of warnings) say(warnText(w));
if (warnings.length === 0)
say({
ko: '경고가 없어요. 한글이 그대로 들어갔어요.',
en: 'No warnings. The Korean text went in as it is.',
});
say({
ko: `${bytes.length.toLocaleString('ko-KR')}바이트를 만들었어요.`,
en: `Made ${bytes.length.toLocaleString('en-US')} bytes.`,
});
});
},
download: async (api: GridApi<Row>) => {
await work(async () => {
const warnings: PdfWarning[] = [];
await withExport(api).downloadPdf('주문-폰트.pdf', {
font: mode === 'korean' ? koreanFont : false,
onWarning: (w) => warnings.push(w),
});
for (const w of warnings) say(warnText(w));
say({ ko: '주문-폰트.pdf를 내려받았어요.', en: 'Downloaded 주문-폰트.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">
<select
aria-label="폰트"
:disabled="!api"
@change="api && actions.mode(api, ($event.target as HTMLSelectElement).value)"
>
<option value="korean" selected>한글 폰트 넣기</option>
<option value="none">폰트 없음</option>
</select>
<button type="button" :disabled="!api" @click="api && actions.build(api)">만들어 보기</button>
<button
type="button"
:disabled="!api"
@click="api && actions.download(api)"
>내려받기</button>
</div>
<Grid style="height: 300px" :options="options" @ready="onReady" />
</template>import { exportPdf, withExport, type PdfWarning } from '@maxgrid/export';
import { createKoreanFont } 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;
orderNo: string;
customer: string;
region: string;
qty: number;
price: number;
orderedAt: Date;
}
const customers = ['한빛푸드', '소나무철물', '파란마켓', '단풍상회', '바다유통', '새벽식자재'];
const regions = ['서울', '부산', '대전', '광주'];
const rows: Row[] = Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
orderNo: `SO-${3001 + i}`,
customer: customers[i % customers.length] as string,
region: regions[i % regions.length] as string,
qty: 3 + ((i * 7) % 28),
price: 4200 + ((i * 1900) % 21000),
orderedAt: new Date(2026, 9, 1 + i * 2),
}));
// PDF 기본 폰트는 한글 글자가 없어요. 한글 폰트 패키지를 넣으면 한글이 나오고, 폰트를 끄면 한글이 ?로 바뀌어요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'orderNo', title: '주문번호', width: 100 },
{ id: 'customer', title: '거래처', width: 110 },
{ id: 'region', title: '지역', width: 70 },
{ id: 'qty', title: '수량', kind: 'number', width: 70, align: 'end' },
{
id: 'price',
title: '단가(원)',
kind: 'number',
width: 100,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
{ id: 'orderedAt', title: '주문일', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
};
let mode = 'korean';
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
withExport(api);
}
// 글꼴 로더는 한 번만 만들어요. onProgress가 받은 바이트를 알려 주면 아래 work()가 "받는 중 3.1 / 10.4 MB"로 보여 줘요.
// (스크립트 태그로 돌리는 "HTML" 탭에서는 전역 글꼴을 그대로 쓰니까 진행 알림이 없고, 대신 몇 초째인지 알려 줘요.)
let gotBytes = 0;
let onBytes: () => void = () => {};
const koreanFont = createKoreanFont({
onProgress: ({ loaded }) => {
gotBytes = loaded;
onBytes();
},
});
// 진행 표시: 막대 하나를 제자리에서 바꿔요(기록에 줄을 쌓지 않아요). 값을 모르면 움직이는 막대예요.
function progressBar() {
let box = document.getElementById('pdf-progress');
if (!box) {
box = document.createElement('div');
box.id = 'pdf-progress';
box.className = 'pg-x';
box.hidden = true;
box.setAttribute('role', 'status');
box.innerHTML = '<progress max="100"></progress><span lang="ko"></span><span lang="en"></span>';
const log = document.getElementById('log');
if (log) log.before(box);
else document.body.append(box);
}
const root = box;
const bar = root.querySelector('progress') as HTMLProgressElement;
const [ko, en] = Array.from(root.querySelectorAll('span'));
return {
show(text: { ko: string; en: string }, percent?: number) {
root.hidden = false;
if (percent === undefined) bar.removeAttribute('value');
else bar.value = percent;
if (ko) ko.textContent = text.ko;
if (en) en.textContent = text.en;
},
hide() {
root.hidden = true;
bar.removeAttribute('value');
if (ko) ko.textContent = '';
if (en) en.textContent = '';
},
};
}
const FONT_BYTES = { ko: 10_414_588 };
const totalBytes = () => FONT_BYTES.ko;
const loadedBytes = () => gotBytes;
let fontLoaded = false;
/** 글꼴을 받고 PDF를 만드는 일을 감싼다: 안내, 진행 막대, 실패 안내(다시 눌러 보라는 말). 기술적인 오류 내용은 콘솔에만 남긴다. */
async function work(job: () => Promise<void>): Promise<void> {
await busy(['build', 'download'], async () => {
const usesFont = mode === 'korean';
const mb = (totalBytes() / 1e6).toFixed(1);
const bar = progressBar();
if (usesFont && !fontLoaded)
say({
ko: `처음 한 번은 글꼴 약 ${mb}MB를 받아요(Noto Sans KR). 연결이 느리면 20초 넘게 걸릴 수 있고, 두 번째부터는 바로 만들어져요.`,
en: `The first time, about ${mb} MB of Korean font is downloaded (Noto Sans KR). On a slow connection it can take over 20 seconds; later PDFs are made right away.`,
});
const started = Date.now();
let receiving = false;
gotBytes = 0;
const making = { ko: 'PDF를 만드는 중이에요…', en: 'Making the PDF…' };
const waiting = () => {
const s = Math.round((Date.now() - started) / 1000);
bar.show({
ko: `글꼴을 받는 중이에요… ${s}초${s >= 10 ? ' (연결이 느리면 더 걸려요)' : ''}`,
en: `Downloading the font… ${s} s${s >= 10 ? ' (a slow connection takes longer)' : ''}`,
});
};
if (usesFont && !fontLoaded) waiting();
else bar.show(making);
// 받은 바이트가 오면 막대가 실제 비율로 바뀌고, 다 받으면 "PDF를 만드는 중"으로 넘어가요.
onBytes = () => {
receiving = true;
const loaded = loadedBytes();
const total = totalBytes();
if (loaded >= total) return bar.show(making);
const pct = Math.floor((loaded / total) * 100);
const a = (loaded / 1e6).toFixed(1);
bar.show(
{
ko: `글꼴 받는 중 ${a} / ${mb} MB (${pct}%)`,
en: `Downloading the font ${a} / ${mb} MB (${pct}%)`,
},
pct,
);
};
// 받은 바이트 알림이 없으면(스크립트 태그로 도는 탭 등) 몇 초째인지만 1초마다 바꿔요.
const timer = setInterval(() => {
if (usesFont && !fontLoaded && !receiving) waiting();
}, 1000);
try {
await job();
if (usesFont) fontLoaded = true;
} catch (error) {
clearInterval(timer);
onBytes = () => {};
bar.hide(); // 실패 안내보다 먼저 지워서, 옛 "받는 중" 줄이 남지 않게 해요.
console.error('[PDF 예제] 글꼴을 받거나 PDF를 만드는 데 실패했어요', error);
say({
ko: '글꼴을 받지 못해서 PDF를 만들지 못했어요. 인터넷 연결을 확인한 뒤 버튼을 다시 눌러 주세요.',
en: 'The PDF could not be made because the font could not be downloaded. Check your internet connection and press the button again.',
});
} finally {
clearInterval(timer);
onBytes = () => {};
bar.hide();
}
});
}
export const actions = {
mode: (_api: GridApi<Row>, v?: string) => void (mode = v ?? 'korean'),
build: async (api: GridApi<Row>) => {
await work(async () => {
const warnings: PdfWarning[] = [];
const bytes = await exportPdf(api, {
font: mode === 'korean' ? koreanFont : false,
onWarning: (w) => warnings.push(w),
});
// 기록은 위가 최신이라, 결과 줄을 마지막에 적어야 맨 위에 보여요.
for (const w of warnings) say(warnText(w));
if (warnings.length === 0)
say({
ko: '경고가 없어요. 한글이 그대로 들어갔어요.',
en: 'No warnings. The Korean text went in as it is.',
});
say({
ko: `${bytes.length.toLocaleString('ko-KR')}바이트를 만들었어요.`,
en: `Made ${bytes.length.toLocaleString('en-US')} bytes.`,
});
});
},
download: async (api: GridApi<Row>) => {
await work(async () => {
const warnings: PdfWarning[] = [];
await withExport(api).downloadPdf('주문-폰트.pdf', {
font: mode === 'korean' ? koreanFont : false,
onWarning: (w) => warnings.push(w),
});
for (const w of warnings) say(warnText(w));
say({ ko: '주문-폰트.pdf를 내려받았어요.', en: 'Downloaded 주문-폰트.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">
<select
aria-label="폰트"
[disabled]="!api"
(change)="api && actions.mode(api, $any($event.target).value)"
>
<option value="korean" selected>한글 폰트 넣기</option>
<option value="none">폰트 없음</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.build(api)"
>만들어 보기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.download(api)"
>내려받기</button>
</div>
<mx-grid style="height: 300px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import { exportPdf, withExport, type PdfWarning } from '@maxgrid/export';
import { createKoreanFont } 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;
orderNo: string;
customer: string;
region: string;
qty: number;
price: number;
orderedAt: Date;
}
const customers = ['한빛푸드', '소나무철물', '파란마켓', '단풍상회', '바다유통', '새벽식자재'];
const regions = ['서울', '부산', '대전', '광주'];
const rows: Row[] = Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
orderNo: `SO-${3001 + i}`,
customer: customers[i % customers.length] as string,
region: regions[i % regions.length] as string,
qty: 3 + ((i * 7) % 28),
price: 4200 + ((i * 1900) % 21000),
orderedAt: new Date(2026, 9, 1 + i * 2),
}));
// PDF 기본 폰트는 한글 글자가 없어요. 한글 폰트 패키지를 넣으면 한글이 나오고, 폰트를 끄면 한글이 ?로 바뀌어요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'orderNo', title: '주문번호', width: 100 },
{ id: 'customer', title: '거래처', width: 110 },
{ id: 'region', title: '지역', width: 70 },
{ id: 'qty', title: '수량', kind: 'number', width: 70, align: 'end' },
{
id: 'price',
title: '단가(원)',
kind: 'number',
width: 100,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
{ id: 'orderedAt', title: '주문일', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
};
let mode = 'korean';
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
withExport(api);
}
// 글꼴 로더는 한 번만 만들어요. onProgress가 받은 바이트를 알려 주면 아래 work()가 "받는 중 3.1 / 10.4 MB"로 보여 줘요.
// (스크립트 태그로 돌리는 "HTML" 탭에서는 전역 글꼴을 그대로 쓰니까 진행 알림이 없고, 대신 몇 초째인지 알려 줘요.)
let gotBytes = 0;
let onBytes: () => void = () => {};
const koreanFont = createKoreanFont({
onProgress: ({ loaded }) => {
gotBytes = loaded;
onBytes();
},
});
// 진행 표시: 막대 하나를 제자리에서 바꿔요(기록에 줄을 쌓지 않아요). 값을 모르면 움직이는 막대예요.
function progressBar() {
let box = document.getElementById('pdf-progress');
if (!box) {
box = document.createElement('div');
box.id = 'pdf-progress';
box.className = 'pg-x';
box.hidden = true;
box.setAttribute('role', 'status');
box.innerHTML = '<progress max="100"></progress><span lang="ko"></span><span lang="en"></span>';
const log = document.getElementById('log');
if (log) log.before(box);
else document.body.append(box);
}
const root = box;
const bar = root.querySelector('progress') as HTMLProgressElement;
const [ko, en] = Array.from(root.querySelectorAll('span'));
return {
show(text: { ko: string; en: string }, percent?: number) {
root.hidden = false;
if (percent === undefined) bar.removeAttribute('value');
else bar.value = percent;
if (ko) ko.textContent = text.ko;
if (en) en.textContent = text.en;
},
hide() {
root.hidden = true;
bar.removeAttribute('value');
if (ko) ko.textContent = '';
if (en) en.textContent = '';
},
};
}
const FONT_BYTES = { ko: 10_414_588 };
const totalBytes = () => FONT_BYTES.ko;
const loadedBytes = () => gotBytes;
let fontLoaded = false;
/** 글꼴을 받고 PDF를 만드는 일을 감싼다: 안내, 진행 막대, 실패 안내(다시 눌러 보라는 말). 기술적인 오류 내용은 콘솔에만 남긴다. */
async function work(job: () => Promise<void>): Promise<void> {
await busy(['build', 'download'], async () => {
const usesFont = mode === 'korean';
const mb = (totalBytes() / 1e6).toFixed(1);
const bar = progressBar();
if (usesFont && !fontLoaded)
say({
ko: `처음 한 번은 글꼴 약 ${mb}MB를 받아요(Noto Sans KR). 연결이 느리면 20초 넘게 걸릴 수 있고, 두 번째부터는 바로 만들어져요.`,
en: `The first time, about ${mb} MB of Korean font is downloaded (Noto Sans KR). On a slow connection it can take over 20 seconds; later PDFs are made right away.`,
});
const started = Date.now();
let receiving = false;
gotBytes = 0;
const making = { ko: 'PDF를 만드는 중이에요…', en: 'Making the PDF…' };
const waiting = () => {
const s = Math.round((Date.now() - started) / 1000);
bar.show({
ko: `글꼴을 받는 중이에요… ${s}초${s >= 10 ? ' (연결이 느리면 더 걸려요)' : ''}`,
en: `Downloading the font… ${s} s${s >= 10 ? ' (a slow connection takes longer)' : ''}`,
});
};
if (usesFont && !fontLoaded) waiting();
else bar.show(making);
// 받은 바이트가 오면 막대가 실제 비율로 바뀌고, 다 받으면 "PDF를 만드는 중"으로 넘어가요.
onBytes = () => {
receiving = true;
const loaded = loadedBytes();
const total = totalBytes();
if (loaded >= total) return bar.show(making);
const pct = Math.floor((loaded / total) * 100);
const a = (loaded / 1e6).toFixed(1);
bar.show(
{
ko: `글꼴 받는 중 ${a} / ${mb} MB (${pct}%)`,
en: `Downloading the font ${a} / ${mb} MB (${pct}%)`,
},
pct,
);
};
// 받은 바이트 알림이 없으면(스크립트 태그로 도는 탭 등) 몇 초째인지만 1초마다 바꿔요.
const timer = setInterval(() => {
if (usesFont && !fontLoaded && !receiving) waiting();
}, 1000);
try {
await job();
if (usesFont) fontLoaded = true;
} catch (error) {
clearInterval(timer);
onBytes = () => {};
bar.hide(); // 실패 안내보다 먼저 지워서, 옛 "받는 중" 줄이 남지 않게 해요.
console.error('[PDF 예제] 글꼴을 받거나 PDF를 만드는 데 실패했어요', error);
say({
ko: '글꼴을 받지 못해서 PDF를 만들지 못했어요. 인터넷 연결을 확인한 뒤 버튼을 다시 눌러 주세요.',
en: 'The PDF could not be made because the font could not be downloaded. Check your internet connection and press the button again.',
});
} finally {
clearInterval(timer);
onBytes = () => {};
bar.hide();
}
});
}
export const actions = {
mode: (_api: GridApi<Row>, v?: string) => void (mode = v ?? 'korean'),
build: async (api: GridApi<Row>) => {
await work(async () => {
const warnings: PdfWarning[] = [];
const bytes = await exportPdf(api, {
font: mode === 'korean' ? koreanFont : false,
onWarning: (w) => warnings.push(w),
});
// 기록은 위가 최신이라, 결과 줄을 마지막에 적어야 맨 위에 보여요.
for (const w of warnings) say(warnText(w));
if (warnings.length === 0)
say({
ko: '경고가 없어요. 한글이 그대로 들어갔어요.',
en: 'No warnings. The Korean text went in as it is.',
});
say({
ko: `${bytes.length.toLocaleString('ko-KR')}바이트를 만들었어요.`,
en: `Made ${bytes.length.toLocaleString('en-US')} bytes.`,
});
});
},
download: async (api: GridApi<Row>) => {
await work(async () => {
const warnings: PdfWarning[] = [];
await withExport(api).downloadPdf('주문-폰트.pdf', {
font: mode === 'korean' ? koreanFont : false,
onWarning: (w) => warnings.push(w),
});
for (const w of warnings) say(warnText(w));
say({ ko: '주문-폰트.pdf를 내려받았어요.', en: 'Downloaded 주문-폰트.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">
<select aria-label="Font" id="mode">
<option value="korean" selected>Include Korean font</option>
<option value="none">No font</option>
</select>
<button type="button" id="build">Build</button>
<button type="button" id="download">Download</button>
</div>
<div id="grid" style="height: 300px"></div>
</div>
<script type="module" src="./main.js"></script>import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('build').addEventListener('click', () => actions.build(api));
document.getElementById('download').addEventListener('click', () => actions.download(api));import { exportPdf, withExport } from '@maxgrid/export';
import { createKoreanFont } 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 customers = ['한빛푸드', '소나무철물', '파란마켓', '단풍상회', '바다유통', '새벽식자재'];
const regions = ['서울', '부산', '대전', '광주'];
const rows = Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
orderNo: `SO-${3001 + i}`,
customer: customers[i % customers.length],
region: regions[i % regions.length],
qty: 3 + ((i * 7) % 28),
price: 4200 + ((i * 1900) % 21000),
orderedAt: new Date(2026, 9, 1 + i * 2),
}));
// PDF 기본 폰트는 한글 글자가 없어요. 한글 폰트 패키지를 넣으면 한글이 나오고, 폰트를 끄면 한글이 ?로 바뀌어요.
export const options = {
columns: [
{ id: 'orderNo', title: '주문번호', width: 100 },
{ id: 'customer', title: '거래처', width: 110 },
{ id: 'region', title: '지역', width: 70 },
{ id: 'qty', title: '수량', kind: 'number', width: 70, align: 'end' },
{
id: 'price',
title: '단가(원)',
kind: 'number',
width: 100,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
{ id: 'orderedAt', title: '주문일', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
};
let mode = 'korean';
let say = () => { };
export function setup(api, log) {
say = log;
withExport(api);
}
// 글꼴 로더는 한 번만 만들어요. onProgress가 받은 바이트를 알려 주면 아래 work()가 "받는 중 3.1 / 10.4 MB"로 보여 줘요.
// (스크립트 태그로 돌리는 "HTML" 탭에서는 전역 글꼴을 그대로 쓰니까 진행 알림이 없고, 대신 몇 초째인지 알려 줘요.)
let gotBytes = 0;
let onBytes = () => { };
const koreanFont = createKoreanFont({
onProgress: ({ loaded }) => {
gotBytes = loaded;
onBytes();
},
});
// 진행 표시: 막대 하나를 제자리에서 바꿔요(기록에 줄을 쌓지 않아요). 값을 모르면 움직이는 막대예요.
function progressBar() {
let box = document.getElementById('pdf-progress');
if (!box) {
box = document.createElement('div');
box.id = 'pdf-progress';
box.className = 'pg-x';
box.hidden = true;
box.setAttribute('role', 'status');
box.innerHTML = '<progress max="100"></progress><span lang="ko"></span><span lang="en"></span>';
const log = document.getElementById('log');
if (log)
log.before(box);
else
document.body.append(box);
}
const root = box;
const bar = root.querySelector('progress');
const [ko, en] = Array.from(root.querySelectorAll('span'));
return {
show(text, percent) {
root.hidden = false;
if (percent === undefined)
bar.removeAttribute('value');
else
bar.value = percent;
if (ko)
ko.textContent = text.ko;
if (en)
en.textContent = text.en;
},
hide() {
root.hidden = true;
bar.removeAttribute('value');
if (ko)
ko.textContent = '';
if (en)
en.textContent = '';
},
};
}
const FONT_BYTES = { ko: 10_414_588 };
const totalBytes = () => FONT_BYTES.ko;
const loadedBytes = () => gotBytes;
let fontLoaded = false;
/** 글꼴을 받고 PDF를 만드는 일을 감싼다: 안내, 진행 막대, 실패 안내(다시 눌러 보라는 말). 기술적인 오류 내용은 콘솔에만 남긴다. */
async function work(job) {
await busy(['build', 'download'], async () => {
const usesFont = mode === 'korean';
const mb = (totalBytes() / 1e6).toFixed(1);
const bar = progressBar();
if (usesFont && !fontLoaded)
say({
ko: `처음 한 번은 글꼴 약 ${mb}MB를 받아요(Noto Sans KR). 연결이 느리면 20초 넘게 걸릴 수 있고, 두 번째부터는 바로 만들어져요.`,
en: `The first time, about ${mb} MB of Korean font is downloaded (Noto Sans KR). On a slow connection it can take over 20 seconds; later PDFs are made right away.`,
});
const started = Date.now();
let receiving = false;
gotBytes = 0;
const making = { ko: 'PDF를 만드는 중이에요…', en: 'Making the PDF…' };
const waiting = () => {
const s = Math.round((Date.now() - started) / 1000);
bar.show({
ko: `글꼴을 받는 중이에요… ${s}초${s >= 10 ? ' (연결이 느리면 더 걸려요)' : ''}`,
en: `Downloading the font… ${s} s${s >= 10 ? ' (a slow connection takes longer)' : ''}`,
});
};
if (usesFont && !fontLoaded)
waiting();
else
bar.show(making);
// 받은 바이트가 오면 막대가 실제 비율로 바뀌고, 다 받으면 "PDF를 만드는 중"으로 넘어가요.
onBytes = () => {
receiving = true;
const loaded = loadedBytes();
const total = totalBytes();
if (loaded >= total)
return bar.show(making);
const pct = Math.floor((loaded / total) * 100);
const a = (loaded / 1e6).toFixed(1);
bar.show({
ko: `글꼴 받는 중 ${a} / ${mb} MB (${pct}%)`,
en: `Downloading the font ${a} / ${mb} MB (${pct}%)`,
}, pct);
};
// 받은 바이트 알림이 없으면(스크립트 태그로 도는 탭 등) 몇 초째인지만 1초마다 바꿔요.
const timer = setInterval(() => {
if (usesFont && !fontLoaded && !receiving)
waiting();
}, 1000);
try {
await job();
if (usesFont)
fontLoaded = true;
}
catch (error) {
clearInterval(timer);
onBytes = () => { };
bar.hide(); // 실패 안내보다 먼저 지워서, 옛 "받는 중" 줄이 남지 않게 해요.
console.error('[PDF 예제] 글꼴을 받거나 PDF를 만드는 데 실패했어요', error);
say({
ko: '글꼴을 받지 못해서 PDF를 만들지 못했어요. 인터넷 연결을 확인한 뒤 버튼을 다시 눌러 주세요.',
en: 'The PDF could not be made because the font could not be downloaded. Check your internet connection and press the button again.',
});
}
finally {
clearInterval(timer);
onBytes = () => { };
bar.hide();
}
});
}
export const actions = {
mode: (_api, v) => void (mode = v ?? 'korean'),
build: async (api) => {
await work(async () => {
const warnings = [];
const bytes = await exportPdf(api, {
font: mode === 'korean' ? koreanFont : false,
onWarning: (w) => warnings.push(w),
});
// 기록은 위가 최신이라, 결과 줄을 마지막에 적어야 맨 위에 보여요.
for (const w of warnings)
say(warnText(w));
if (warnings.length === 0)
say({
ko: '경고가 없어요. 한글이 그대로 들어갔어요.',
en: 'No warnings. The Korean text went in as it is.',
});
say({
ko: `${bytes.length.toLocaleString('ko-KR')}바이트를 만들었어요.`,
en: `Made ${bytes.length.toLocaleString('en-US')} bytes.`,
});
});
},
download: async (api) => {
await work(async () => {
const warnings = [];
await withExport(api).downloadPdf('주문-폰트.pdf', {
font: mode === 'korean' ? koreanFont : false,
onWarning: (w) => warnings.push(w),
});
for (const w of warnings)
say(warnText(w));
say({ ko: '주문-폰트.pdf를 내려받았어요.', en: 'Downloaded 주문-폰트.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>Korean PDF: embed a font</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Font" id="mode">
<option value="korean" selected>Include Korean font</option>
<option value="none">No font</option>
</select>
<button type="button" id="build">Build</button>
<button type="button" id="download">Download</button>
</div>
<div id="grid" style="height: 300px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.export.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@maxgrid/export-font-ko@1/dist/maxgrid.export-font-ko.min.js"></script>
<script>
const { exportPdf, withExport } = MaxGridExport;
const createKoreanFont = () => 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 customers = ['한빛푸드', '소나무철물', '파란마켓', '단풍상회', '바다유통', '새벽식자재'];
const regions = ['서울', '부산', '대전', '광주'];
const rows = Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
orderNo: `SO-${3001 + i}`,
customer: customers[i % customers.length],
region: regions[i % regions.length],
qty: 3 + ((i * 7) % 28),
price: 4200 + ((i * 1900) % 21000),
orderedAt: new Date(2026, 9, 1 + i * 2),
}));
// PDF 기본 폰트는 한글 글자가 없어요. 한글 폰트 패키지를 넣으면 한글이 나오고, 폰트를 끄면 한글이 ?로 바뀌어요.
const options = {
columns: [
{ id: 'orderNo', title: '주문번호', width: 100 },
{ id: 'customer', title: '거래처', width: 110 },
{ id: 'region', title: '지역', width: 70 },
{ id: 'qty', title: '수량', kind: 'number', width: 70, align: 'end' },
{
id: 'price',
title: '단가(원)',
kind: 'number',
width: 100,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
{ id: 'orderedAt', title: '주문일', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
};
let mode = 'korean';
let say = () => { };
function setup(api, log) {
say = log;
withExport(api);
}
// 글꼴 로더는 한 번만 만들어요. onProgress가 받은 바이트를 알려 주면 아래 work()가 "받는 중 3.1 / 10.4 MB"로 보여 줘요.
// (스크립트 태그로 돌리는 "HTML" 탭에서는 전역 글꼴을 그대로 쓰니까 진행 알림이 없고, 대신 몇 초째인지 알려 줘요.)
let gotBytes = 0;
let onBytes = () => { };
const koreanFont = createKoreanFont({
onProgress: ({ loaded }) => {
gotBytes = loaded;
onBytes();
},
});
// 진행 표시: 막대 하나를 제자리에서 바꿔요(기록에 줄을 쌓지 않아요). 값을 모르면 움직이는 막대예요.
function progressBar() {
let box = document.getElementById('pdf-progress');
if (!box) {
box = document.createElement('div');
box.id = 'pdf-progress';
box.className = 'pg-x';
box.hidden = true;
box.setAttribute('role', 'status');
box.innerHTML = '<progress max="100"></progress><span lang="ko"></span><span lang="en"></span>';
const log = document.getElementById('log');
if (log)
log.before(box);
else
document.body.append(box);
}
const root = box;
const bar = root.querySelector('progress');
const [ko, en] = Array.from(root.querySelectorAll('span'));
return {
show(text, percent) {
root.hidden = false;
if (percent === undefined)
bar.removeAttribute('value');
else
bar.value = percent;
if (ko)
ko.textContent = text.ko;
if (en)
en.textContent = text.en;
},
hide() {
root.hidden = true;
bar.removeAttribute('value');
if (ko)
ko.textContent = '';
if (en)
en.textContent = '';
},
};
}
const FONT_BYTES = { ko: 10_414_588 };
const totalBytes = () => FONT_BYTES.ko;
const loadedBytes = () => gotBytes;
let fontLoaded = false;
/** 글꼴을 받고 PDF를 만드는 일을 감싼다: 안내, 진행 막대, 실패 안내(다시 눌러 보라는 말). 기술적인 오류 내용은 콘솔에만 남긴다. */
async function work(job) {
await busy(['build', 'download'], async () => {
const usesFont = mode === 'korean';
const mb = (totalBytes() / 1e6).toFixed(1);
const bar = progressBar();
if (usesFont && !fontLoaded)
say({
ko: `처음 한 번은 글꼴 약 ${mb}MB를 받아요(Noto Sans KR). 연결이 느리면 20초 넘게 걸릴 수 있고, 두 번째부터는 바로 만들어져요.`,
en: `The first time, about ${mb} MB of Korean font is downloaded (Noto Sans KR). On a slow connection it can take over 20 seconds; later PDFs are made right away.`,
});
const started = Date.now();
let receiving = false;
gotBytes = 0;
const making = { ko: 'PDF를 만드는 중이에요…', en: 'Making the PDF…' };
const waiting = () => {
const s = Math.round((Date.now() - started) / 1000);
bar.show({
ko: `글꼴을 받는 중이에요… ${s}초${s >= 10 ? ' (연결이 느리면 더 걸려요)' : ''}`,
en: `Downloading the font… ${s} s${s >= 10 ? ' (a slow connection takes longer)' : ''}`,
});
};
if (usesFont && !fontLoaded)
waiting();
else
bar.show(making);
// 받은 바이트가 오면 막대가 실제 비율로 바뀌고, 다 받으면 "PDF를 만드는 중"으로 넘어가요.
onBytes = () => {
receiving = true;
const loaded = loadedBytes();
const total = totalBytes();
if (loaded >= total)
return bar.show(making);
const pct = Math.floor((loaded / total) * 100);
const a = (loaded / 1e6).toFixed(1);
bar.show({
ko: `글꼴 받는 중 ${a} / ${mb} MB (${pct}%)`,
en: `Downloading the font ${a} / ${mb} MB (${pct}%)`,
}, pct);
};
// 받은 바이트 알림이 없으면(스크립트 태그로 도는 탭 등) 몇 초째인지만 1초마다 바꿔요.
const timer = setInterval(() => {
if (usesFont && !fontLoaded && !receiving)
waiting();
}, 1000);
try {
await job();
if (usesFont)
fontLoaded = true;
}
catch (error) {
clearInterval(timer);
onBytes = () => { };
bar.hide(); // 실패 안내보다 먼저 지워서, 옛 "받는 중" 줄이 남지 않게 해요.
console.error('[PDF 예제] 글꼴을 받거나 PDF를 만드는 데 실패했어요', error);
say({
ko: '글꼴을 받지 못해서 PDF를 만들지 못했어요. 인터넷 연결을 확인한 뒤 버튼을 다시 눌러 주세요.',
en: 'The PDF could not be made because the font could not be downloaded. Check your internet connection and press the button again.',
});
}
finally {
clearInterval(timer);
onBytes = () => { };
bar.hide();
}
});
}
const actions = {
mode: (_api, v) => void (mode = v ?? 'korean'),
build: async (api) => {
await work(async () => {
const warnings = [];
const bytes = await exportPdf(api, {
font: mode === 'korean' ? koreanFont : false,
onWarning: (w) => warnings.push(w),
});
// 기록은 위가 최신이라, 결과 줄을 마지막에 적어야 맨 위에 보여요.
for (const w of warnings)
say(warnText(w));
if (warnings.length === 0)
say({
ko: '경고가 없어요. 한글이 그대로 들어갔어요.',
en: 'No warnings. The Korean text went in as it is.',
});
say({
ko: `${bytes.length.toLocaleString('ko-KR')}바이트를 만들었어요.`,
en: `Made ${bytes.length.toLocaleString('en-US')} bytes.`,
});
});
},
download: async (api) => {
await work(async () => {
const warnings = [];
await withExport(api).downloadPdf('주문-폰트.pdf', {
font: mode === 'korean' ? koreanFont : false,
onWarning: (w) => warnings.push(w),
});
for (const w of warnings)
say(warnText(w));
say({ ko: '주문-폰트.pdf를 내려받았어요.', en: 'Downloaded 주문-폰트.pdf.' });
});
},
};
options.ariaLabel = "Korean PDF: embed a font";
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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('build').addEventListener('click', () => actions.build(api));
document.getElementById('download').addEventListener('click', () => actions.download(api));
</script>
</body>
</html> This example needs an extra package. To run it locally, install with npm i @maxgrid/react @maxgrid/export @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">
<select
aria-label="Font"
disabled={!api}
onChange={(event) => api && actions.mode(api, event.target.value)}
>
<option value="korean">Include Korean font</option>
<option value="none">No font</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.build(api)}
>Build</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.download(api)}
>Download</button>
</div>
<Grid style={{ height: 300 }} ref={gridRef} options={options} />
</>
);
}import { exportPdf, withExport, type PdfWarning } from '@maxgrid/export';
import { createKoreanFont } 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;
orderNo: string;
customer: string;
region: string;
qty: number;
price: number;
orderedAt: Date;
}
const customers = ['한빛푸드', '소나무철물', '파란마켓', '단풍상회', '바다유통', '새벽식자재'];
const regions = ['서울', '부산', '대전', '광주'];
const rows: Row[] = Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
orderNo: `SO-${3001 + i}`,
customer: customers[i % customers.length] as string,
region: regions[i % regions.length] as string,
qty: 3 + ((i * 7) % 28),
price: 4200 + ((i * 1900) % 21000),
orderedAt: new Date(2026, 9, 1 + i * 2),
}));
// PDF 기본 폰트는 한글 글자가 없어요. 한글 폰트 패키지를 넣으면 한글이 나오고, 폰트를 끄면 한글이 ?로 바뀌어요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'orderNo', title: '주문번호', width: 100 },
{ id: 'customer', title: '거래처', width: 110 },
{ id: 'region', title: '지역', width: 70 },
{ id: 'qty', title: '수량', kind: 'number', width: 70, align: 'end' },
{
id: 'price',
title: '단가(원)',
kind: 'number',
width: 100,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
{ id: 'orderedAt', title: '주문일', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
};
let mode = 'korean';
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
withExport(api);
}
// 글꼴 로더는 한 번만 만들어요. onProgress가 받은 바이트를 알려 주면 아래 work()가 "받는 중 3.1 / 10.4 MB"로 보여 줘요.
// (스크립트 태그로 돌리는 "HTML" 탭에서는 전역 글꼴을 그대로 쓰니까 진행 알림이 없고, 대신 몇 초째인지 알려 줘요.)
let gotBytes = 0;
let onBytes: () => void = () => {};
const koreanFont = createKoreanFont({
onProgress: ({ loaded }) => {
gotBytes = loaded;
onBytes();
},
});
// 진행 표시: 막대 하나를 제자리에서 바꿔요(기록에 줄을 쌓지 않아요). 값을 모르면 움직이는 막대예요.
function progressBar() {
let box = document.getElementById('pdf-progress');
if (!box) {
box = document.createElement('div');
box.id = 'pdf-progress';
box.className = 'pg-x';
box.hidden = true;
box.setAttribute('role', 'status');
box.innerHTML = '<progress max="100"></progress><span lang="ko"></span><span lang="en"></span>';
const log = document.getElementById('log');
if (log) log.before(box);
else document.body.append(box);
}
const root = box;
const bar = root.querySelector('progress') as HTMLProgressElement;
const [ko, en] = Array.from(root.querySelectorAll('span'));
return {
show(text: { ko: string; en: string }, percent?: number) {
root.hidden = false;
if (percent === undefined) bar.removeAttribute('value');
else bar.value = percent;
if (ko) ko.textContent = text.ko;
if (en) en.textContent = text.en;
},
hide() {
root.hidden = true;
bar.removeAttribute('value');
if (ko) ko.textContent = '';
if (en) en.textContent = '';
},
};
}
const FONT_BYTES = { ko: 10_414_588 };
const totalBytes = () => FONT_BYTES.ko;
const loadedBytes = () => gotBytes;
let fontLoaded = false;
/** 글꼴을 받고 PDF를 만드는 일을 감싼다: 안내, 진행 막대, 실패 안내(다시 눌러 보라는 말). 기술적인 오류 내용은 콘솔에만 남긴다. */
async function work(job: () => Promise<void>): Promise<void> {
await busy(['build', 'download'], async () => {
const usesFont = mode === 'korean';
const mb = (totalBytes() / 1e6).toFixed(1);
const bar = progressBar();
if (usesFont && !fontLoaded)
say({
ko: `처음 한 번은 글꼴 약 ${mb}MB를 받아요(Noto Sans KR). 연결이 느리면 20초 넘게 걸릴 수 있고, 두 번째부터는 바로 만들어져요.`,
en: `The first time, about ${mb} MB of Korean font is downloaded (Noto Sans KR). On a slow connection it can take over 20 seconds; later PDFs are made right away.`,
});
const started = Date.now();
let receiving = false;
gotBytes = 0;
const making = { ko: 'PDF를 만드는 중이에요…', en: 'Making the PDF…' };
const waiting = () => {
const s = Math.round((Date.now() - started) / 1000);
bar.show({
ko: `글꼴을 받는 중이에요… ${s}초${s >= 10 ? ' (연결이 느리면 더 걸려요)' : ''}`,
en: `Downloading the font… ${s} s${s >= 10 ? ' (a slow connection takes longer)' : ''}`,
});
};
if (usesFont && !fontLoaded) waiting();
else bar.show(making);
// 받은 바이트가 오면 막대가 실제 비율로 바뀌고, 다 받으면 "PDF를 만드는 중"으로 넘어가요.
onBytes = () => {
receiving = true;
const loaded = loadedBytes();
const total = totalBytes();
if (loaded >= total) return bar.show(making);
const pct = Math.floor((loaded / total) * 100);
const a = (loaded / 1e6).toFixed(1);
bar.show(
{
ko: `글꼴 받는 중 ${a} / ${mb} MB (${pct}%)`,
en: `Downloading the font ${a} / ${mb} MB (${pct}%)`,
},
pct,
);
};
// 받은 바이트 알림이 없으면(스크립트 태그로 도는 탭 등) 몇 초째인지만 1초마다 바꿔요.
const timer = setInterval(() => {
if (usesFont && !fontLoaded && !receiving) waiting();
}, 1000);
try {
await job();
if (usesFont) fontLoaded = true;
} catch (error) {
clearInterval(timer);
onBytes = () => {};
bar.hide(); // 실패 안내보다 먼저 지워서, 옛 "받는 중" 줄이 남지 않게 해요.
console.error('[PDF 예제] 글꼴을 받거나 PDF를 만드는 데 실패했어요', error);
say({
ko: '글꼴을 받지 못해서 PDF를 만들지 못했어요. 인터넷 연결을 확인한 뒤 버튼을 다시 눌러 주세요.',
en: 'The PDF could not be made because the font could not be downloaded. Check your internet connection and press the button again.',
});
} finally {
clearInterval(timer);
onBytes = () => {};
bar.hide();
}
});
}
export const actions = {
mode: (_api: GridApi<Row>, v?: string) => void (mode = v ?? 'korean'),
build: async (api: GridApi<Row>) => {
await work(async () => {
const warnings: PdfWarning[] = [];
const bytes = await exportPdf(api, {
font: mode === 'korean' ? koreanFont : false,
onWarning: (w) => warnings.push(w),
});
// 기록은 위가 최신이라, 결과 줄을 마지막에 적어야 맨 위에 보여요.
for (const w of warnings) say(warnText(w));
if (warnings.length === 0)
say({
ko: '경고가 없어요. 한글이 그대로 들어갔어요.',
en: 'No warnings. The Korean text went in as it is.',
});
say({
ko: `${bytes.length.toLocaleString('ko-KR')}바이트를 만들었어요.`,
en: `Made ${bytes.length.toLocaleString('en-US')} bytes.`,
});
});
},
download: async (api: GridApi<Row>) => {
await work(async () => {
const warnings: PdfWarning[] = [];
await withExport(api).downloadPdf('주문-폰트.pdf', {
font: mode === 'korean' ? koreanFont : false,
onWarning: (w) => warnings.push(w),
});
for (const w of warnings) say(warnText(w));
say({ ko: '주문-폰트.pdf를 내려받았어요.', en: 'Downloaded 주문-폰트.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">
<select
aria-label="Font"
:disabled="!api"
@change="api && actions.mode(api, ($event.target as HTMLSelectElement).value)"
>
<option value="korean" selected>Include Korean font</option>
<option value="none">No font</option>
</select>
<button type="button" :disabled="!api" @click="api && actions.build(api)">Build</button>
<button
type="button"
:disabled="!api"
@click="api && actions.download(api)"
>Download</button>
</div>
<Grid style="height: 300px" :options="options" @ready="onReady" />
</template>import { exportPdf, withExport, type PdfWarning } from '@maxgrid/export';
import { createKoreanFont } 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;
orderNo: string;
customer: string;
region: string;
qty: number;
price: number;
orderedAt: Date;
}
const customers = ['한빛푸드', '소나무철물', '파란마켓', '단풍상회', '바다유통', '새벽식자재'];
const regions = ['서울', '부산', '대전', '광주'];
const rows: Row[] = Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
orderNo: `SO-${3001 + i}`,
customer: customers[i % customers.length] as string,
region: regions[i % regions.length] as string,
qty: 3 + ((i * 7) % 28),
price: 4200 + ((i * 1900) % 21000),
orderedAt: new Date(2026, 9, 1 + i * 2),
}));
// PDF 기본 폰트는 한글 글자가 없어요. 한글 폰트 패키지를 넣으면 한글이 나오고, 폰트를 끄면 한글이 ?로 바뀌어요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'orderNo', title: '주문번호', width: 100 },
{ id: 'customer', title: '거래처', width: 110 },
{ id: 'region', title: '지역', width: 70 },
{ id: 'qty', title: '수량', kind: 'number', width: 70, align: 'end' },
{
id: 'price',
title: '단가(원)',
kind: 'number',
width: 100,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
{ id: 'orderedAt', title: '주문일', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
};
let mode = 'korean';
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
withExport(api);
}
// 글꼴 로더는 한 번만 만들어요. onProgress가 받은 바이트를 알려 주면 아래 work()가 "받는 중 3.1 / 10.4 MB"로 보여 줘요.
// (스크립트 태그로 돌리는 "HTML" 탭에서는 전역 글꼴을 그대로 쓰니까 진행 알림이 없고, 대신 몇 초째인지 알려 줘요.)
let gotBytes = 0;
let onBytes: () => void = () => {};
const koreanFont = createKoreanFont({
onProgress: ({ loaded }) => {
gotBytes = loaded;
onBytes();
},
});
// 진행 표시: 막대 하나를 제자리에서 바꿔요(기록에 줄을 쌓지 않아요). 값을 모르면 움직이는 막대예요.
function progressBar() {
let box = document.getElementById('pdf-progress');
if (!box) {
box = document.createElement('div');
box.id = 'pdf-progress';
box.className = 'pg-x';
box.hidden = true;
box.setAttribute('role', 'status');
box.innerHTML = '<progress max="100"></progress><span lang="ko"></span><span lang="en"></span>';
const log = document.getElementById('log');
if (log) log.before(box);
else document.body.append(box);
}
const root = box;
const bar = root.querySelector('progress') as HTMLProgressElement;
const [ko, en] = Array.from(root.querySelectorAll('span'));
return {
show(text: { ko: string; en: string }, percent?: number) {
root.hidden = false;
if (percent === undefined) bar.removeAttribute('value');
else bar.value = percent;
if (ko) ko.textContent = text.ko;
if (en) en.textContent = text.en;
},
hide() {
root.hidden = true;
bar.removeAttribute('value');
if (ko) ko.textContent = '';
if (en) en.textContent = '';
},
};
}
const FONT_BYTES = { ko: 10_414_588 };
const totalBytes = () => FONT_BYTES.ko;
const loadedBytes = () => gotBytes;
let fontLoaded = false;
/** 글꼴을 받고 PDF를 만드는 일을 감싼다: 안내, 진행 막대, 실패 안내(다시 눌러 보라는 말). 기술적인 오류 내용은 콘솔에만 남긴다. */
async function work(job: () => Promise<void>): Promise<void> {
await busy(['build', 'download'], async () => {
const usesFont = mode === 'korean';
const mb = (totalBytes() / 1e6).toFixed(1);
const bar = progressBar();
if (usesFont && !fontLoaded)
say({
ko: `처음 한 번은 글꼴 약 ${mb}MB를 받아요(Noto Sans KR). 연결이 느리면 20초 넘게 걸릴 수 있고, 두 번째부터는 바로 만들어져요.`,
en: `The first time, about ${mb} MB of Korean font is downloaded (Noto Sans KR). On a slow connection it can take over 20 seconds; later PDFs are made right away.`,
});
const started = Date.now();
let receiving = false;
gotBytes = 0;
const making = { ko: 'PDF를 만드는 중이에요…', en: 'Making the PDF…' };
const waiting = () => {
const s = Math.round((Date.now() - started) / 1000);
bar.show({
ko: `글꼴을 받는 중이에요… ${s}초${s >= 10 ? ' (연결이 느리면 더 걸려요)' : ''}`,
en: `Downloading the font… ${s} s${s >= 10 ? ' (a slow connection takes longer)' : ''}`,
});
};
if (usesFont && !fontLoaded) waiting();
else bar.show(making);
// 받은 바이트가 오면 막대가 실제 비율로 바뀌고, 다 받으면 "PDF를 만드는 중"으로 넘어가요.
onBytes = () => {
receiving = true;
const loaded = loadedBytes();
const total = totalBytes();
if (loaded >= total) return bar.show(making);
const pct = Math.floor((loaded / total) * 100);
const a = (loaded / 1e6).toFixed(1);
bar.show(
{
ko: `글꼴 받는 중 ${a} / ${mb} MB (${pct}%)`,
en: `Downloading the font ${a} / ${mb} MB (${pct}%)`,
},
pct,
);
};
// 받은 바이트 알림이 없으면(스크립트 태그로 도는 탭 등) 몇 초째인지만 1초마다 바꿔요.
const timer = setInterval(() => {
if (usesFont && !fontLoaded && !receiving) waiting();
}, 1000);
try {
await job();
if (usesFont) fontLoaded = true;
} catch (error) {
clearInterval(timer);
onBytes = () => {};
bar.hide(); // 실패 안내보다 먼저 지워서, 옛 "받는 중" 줄이 남지 않게 해요.
console.error('[PDF 예제] 글꼴을 받거나 PDF를 만드는 데 실패했어요', error);
say({
ko: '글꼴을 받지 못해서 PDF를 만들지 못했어요. 인터넷 연결을 확인한 뒤 버튼을 다시 눌러 주세요.',
en: 'The PDF could not be made because the font could not be downloaded. Check your internet connection and press the button again.',
});
} finally {
clearInterval(timer);
onBytes = () => {};
bar.hide();
}
});
}
export const actions = {
mode: (_api: GridApi<Row>, v?: string) => void (mode = v ?? 'korean'),
build: async (api: GridApi<Row>) => {
await work(async () => {
const warnings: PdfWarning[] = [];
const bytes = await exportPdf(api, {
font: mode === 'korean' ? koreanFont : false,
onWarning: (w) => warnings.push(w),
});
// 기록은 위가 최신이라, 결과 줄을 마지막에 적어야 맨 위에 보여요.
for (const w of warnings) say(warnText(w));
if (warnings.length === 0)
say({
ko: '경고가 없어요. 한글이 그대로 들어갔어요.',
en: 'No warnings. The Korean text went in as it is.',
});
say({
ko: `${bytes.length.toLocaleString('ko-KR')}바이트를 만들었어요.`,
en: `Made ${bytes.length.toLocaleString('en-US')} bytes.`,
});
});
},
download: async (api: GridApi<Row>) => {
await work(async () => {
const warnings: PdfWarning[] = [];
await withExport(api).downloadPdf('주문-폰트.pdf', {
font: mode === 'korean' ? koreanFont : false,
onWarning: (w) => warnings.push(w),
});
for (const w of warnings) say(warnText(w));
say({ ko: '주문-폰트.pdf를 내려받았어요.', en: 'Downloaded 주문-폰트.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">
<select
aria-label="Font"
[disabled]="!api"
(change)="api && actions.mode(api, $any($event.target).value)"
>
<option value="korean" selected>Include Korean font</option>
<option value="none">No font</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.build(api)"
>Build</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.download(api)"
>Download</button>
</div>
<mx-grid style="height: 300px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import { exportPdf, withExport, type PdfWarning } from '@maxgrid/export';
import { createKoreanFont } 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;
orderNo: string;
customer: string;
region: string;
qty: number;
price: number;
orderedAt: Date;
}
const customers = ['한빛푸드', '소나무철물', '파란마켓', '단풍상회', '바다유통', '새벽식자재'];
const regions = ['서울', '부산', '대전', '광주'];
const rows: Row[] = Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
orderNo: `SO-${3001 + i}`,
customer: customers[i % customers.length] as string,
region: regions[i % regions.length] as string,
qty: 3 + ((i * 7) % 28),
price: 4200 + ((i * 1900) % 21000),
orderedAt: new Date(2026, 9, 1 + i * 2),
}));
// PDF 기본 폰트는 한글 글자가 없어요. 한글 폰트 패키지를 넣으면 한글이 나오고, 폰트를 끄면 한글이 ?로 바뀌어요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'orderNo', title: '주문번호', width: 100 },
{ id: 'customer', title: '거래처', width: 110 },
{ id: 'region', title: '지역', width: 70 },
{ id: 'qty', title: '수량', kind: 'number', width: 70, align: 'end' },
{
id: 'price',
title: '단가(원)',
kind: 'number',
width: 100,
align: 'end',
formatValue: (v) => Number(v).toLocaleString('ko-KR'),
},
{ id: 'orderedAt', title: '주문일', kind: 'date', width: 110 },
],
rows,
rowKey: 'id',
};
let mode = 'korean';
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
withExport(api);
}
// 글꼴 로더는 한 번만 만들어요. onProgress가 받은 바이트를 알려 주면 아래 work()가 "받는 중 3.1 / 10.4 MB"로 보여 줘요.
// (스크립트 태그로 돌리는 "HTML" 탭에서는 전역 글꼴을 그대로 쓰니까 진행 알림이 없고, 대신 몇 초째인지 알려 줘요.)
let gotBytes = 0;
let onBytes: () => void = () => {};
const koreanFont = createKoreanFont({
onProgress: ({ loaded }) => {
gotBytes = loaded;
onBytes();
},
});
// 진행 표시: 막대 하나를 제자리에서 바꿔요(기록에 줄을 쌓지 않아요). 값을 모르면 움직이는 막대예요.
function progressBar() {
let box = document.getElementById('pdf-progress');
if (!box) {
box = document.createElement('div');
box.id = 'pdf-progress';
box.className = 'pg-x';
box.hidden = true;
box.setAttribute('role', 'status');
box.innerHTML = '<progress max="100"></progress><span lang="ko"></span><span lang="en"></span>';
const log = document.getElementById('log');
if (log) log.before(box);
else document.body.append(box);
}
const root = box;
const bar = root.querySelector('progress') as HTMLProgressElement;
const [ko, en] = Array.from(root.querySelectorAll('span'));
return {
show(text: { ko: string; en: string }, percent?: number) {
root.hidden = false;
if (percent === undefined) bar.removeAttribute('value');
else bar.value = percent;
if (ko) ko.textContent = text.ko;
if (en) en.textContent = text.en;
},
hide() {
root.hidden = true;
bar.removeAttribute('value');
if (ko) ko.textContent = '';
if (en) en.textContent = '';
},
};
}
const FONT_BYTES = { ko: 10_414_588 };
const totalBytes = () => FONT_BYTES.ko;
const loadedBytes = () => gotBytes;
let fontLoaded = false;
/** 글꼴을 받고 PDF를 만드는 일을 감싼다: 안내, 진행 막대, 실패 안내(다시 눌러 보라는 말). 기술적인 오류 내용은 콘솔에만 남긴다. */
async function work(job: () => Promise<void>): Promise<void> {
await busy(['build', 'download'], async () => {
const usesFont = mode === 'korean';
const mb = (totalBytes() / 1e6).toFixed(1);
const bar = progressBar();
if (usesFont && !fontLoaded)
say({
ko: `처음 한 번은 글꼴 약 ${mb}MB를 받아요(Noto Sans KR). 연결이 느리면 20초 넘게 걸릴 수 있고, 두 번째부터는 바로 만들어져요.`,
en: `The first time, about ${mb} MB of Korean font is downloaded (Noto Sans KR). On a slow connection it can take over 20 seconds; later PDFs are made right away.`,
});
const started = Date.now();
let receiving = false;
gotBytes = 0;
const making = { ko: 'PDF를 만드는 중이에요…', en: 'Making the PDF…' };
const waiting = () => {
const s = Math.round((Date.now() - started) / 1000);
bar.show({
ko: `글꼴을 받는 중이에요… ${s}초${s >= 10 ? ' (연결이 느리면 더 걸려요)' : ''}`,
en: `Downloading the font… ${s} s${s >= 10 ? ' (a slow connection takes longer)' : ''}`,
});
};
if (usesFont && !fontLoaded) waiting();
else bar.show(making);
// 받은 바이트가 오면 막대가 실제 비율로 바뀌고, 다 받으면 "PDF를 만드는 중"으로 넘어가요.
onBytes = () => {
receiving = true;
const loaded = loadedBytes();
const total = totalBytes();
if (loaded >= total) return bar.show(making);
const pct = Math.floor((loaded / total) * 100);
const a = (loaded / 1e6).toFixed(1);
bar.show(
{
ko: `글꼴 받는 중 ${a} / ${mb} MB (${pct}%)`,
en: `Downloading the font ${a} / ${mb} MB (${pct}%)`,
},
pct,
);
};
// 받은 바이트 알림이 없으면(스크립트 태그로 도는 탭 등) 몇 초째인지만 1초마다 바꿔요.
const timer = setInterval(() => {
if (usesFont && !fontLoaded && !receiving) waiting();
}, 1000);
try {
await job();
if (usesFont) fontLoaded = true;
} catch (error) {
clearInterval(timer);
onBytes = () => {};
bar.hide(); // 실패 안내보다 먼저 지워서, 옛 "받는 중" 줄이 남지 않게 해요.
console.error('[PDF 예제] 글꼴을 받거나 PDF를 만드는 데 실패했어요', error);
say({
ko: '글꼴을 받지 못해서 PDF를 만들지 못했어요. 인터넷 연결을 확인한 뒤 버튼을 다시 눌러 주세요.',
en: 'The PDF could not be made because the font could not be downloaded. Check your internet connection and press the button again.',
});
} finally {
clearInterval(timer);
onBytes = () => {};
bar.hide();
}
});
}
export const actions = {
mode: (_api: GridApi<Row>, v?: string) => void (mode = v ?? 'korean'),
build: async (api: GridApi<Row>) => {
await work(async () => {
const warnings: PdfWarning[] = [];
const bytes = await exportPdf(api, {
font: mode === 'korean' ? koreanFont : false,
onWarning: (w) => warnings.push(w),
});
// 기록은 위가 최신이라, 결과 줄을 마지막에 적어야 맨 위에 보여요.
for (const w of warnings) say(warnText(w));
if (warnings.length === 0)
say({
ko: '경고가 없어요. 한글이 그대로 들어갔어요.',
en: 'No warnings. The Korean text went in as it is.',
});
say({
ko: `${bytes.length.toLocaleString('ko-KR')}바이트를 만들었어요.`,
en: `Made ${bytes.length.toLocaleString('en-US')} bytes.`,
});
});
},
download: async (api: GridApi<Row>) => {
await work(async () => {
const warnings: PdfWarning[] = [];
await withExport(api).downloadPdf('주문-폰트.pdf', {
font: mode === 'korean' ? koreanFont : false,
onWarning: (w) => warnings.push(w),
});
for (const w of warnings) say(warnText(w));
say({ ko: '주문-폰트.pdf를 내려받았어요.', en: 'Downloaded 주문-폰트.pdf.' });
});
},
};