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

한글 PDF: 폰트 넣기Korean PDF: embed a font

한글 폰트를 넣은 PDF와 폰트 없이 만든 PDF를 비교하고, 빠진 글자는 경고로 알려 줘요.Compare a PDF made with a Korean font and without; missing glyphs are reported as warnings.

활용Intermediate
직접 써 보기Live preview한글 PDF: 폰트 넣기Korean PDF: embed a font

코드Code

탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.

이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)

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

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

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

index.html
<div id="app">
  <div class="toolbar">
    <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>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('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));
example.js
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.' });
    });
  },
};

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

This example needs an extra package. To run it locally, install with npm i maxgrid @maxgrid/export @maxgrid/export-font-ko.

When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.

index.html
<div id="app">
  <div class="toolbar">
    <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>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('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));
example.js
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.' });
    });
  },
};