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

한글과 중국어 간체가 섞인 PDFA PDF with Korean and Simplified Chinese

한글 폰트 뒤에 간체 폰트를 이어서 주면 한 표에 한글과 중국어 간체가 같이 있는 PDF가 만들어져요. 한글 폰트만 쓰면 간체 글자가 ?로 바뀌는 것도 비교해 볼 수 있어요.Chain the Simplified Chinese font after the Korean font and one table can hold Korean and Simplified Chinese in the same PDF. You can also compare with the Korean font alone, where Simplified characters become ?.

활용Intermediate
직접 써 보기Live preview한글과 중국어 간체가 섞인 PDFA PDF with Korean and Simplified Chinese

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

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

index.html
<div id="app">
  <div class="toolbar">
    <select aria-label="폰트" id="mode">
      <option value="both" selected>한글 + 간체 폰트</option>
      <option value="korean">한글 폰트만</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';
import { createSimplifiedChineseFont } from '@maxgrid/export-font-sc';
// 라이브러리가 보내는 경고(영어·기술 용어)를 쉬운 말로 바꿔요.
const warnText = (w) => w.code === 'missing-glyph'
  ? {
    ko: `폰트에 없는 글자를 ?로 바꿨어요: ${w.characters}`,
    en: `Characters missing from the font became ?: ${w.characters}`,
  }
  : w.code === 'font-unavailable'
    ? {
      ko: '폰트를 불러오지 못해서 기본 폰트로 만들었어요.',
      en: 'The font could not be loaded, so the default font was used.',
    }
    : {
      ko: '세로로 합친 칸은 PDF에서 합치지 않았어요.',
      en: 'Vertically merged cells were not merged in the 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 customersCn = ['北京商贸', '广东货运', '开发区门店', '上海贸易', '深圳电子', '东方食品'];
const items = ['사과 상자', '철제 선반', '포장 테이프', '전자저울'];
const itemsCn = ['苹果箱', '铁架', '包装胶带', '电子秤'];
const rows = Array.from({ length: 12 }, (_, i) => ({
  id: i + 1,
  orderNo: `SO-${3001 + i}`,
  customer: customers[i % customers.length],
  customerCn: customersCn[i % customersCn.length],
  item: items[i % items.length],
  itemCn: itemsCn[i % itemsCn.length],
  qty: 3 + ((i * 7) % 28),
}));
// 폰트를 [한글 폰트, 간체 폰트]로 이어서 주면 글자마다 앞 폰트에 있으면 그것을, 없으면 뒤 폰트를 써요.
export const options = {
  columns: [
    { id: 'orderNo', title: '주문번호 订单号', width: 110 },
    { id: 'customer', title: '거래처', width: 100 },
    { id: 'customerCn', title: '客户', width: 100 },
    { id: 'item', title: '품목', width: 100 },
    { id: 'itemCn', title: '商品', width: 90 },
    { id: 'qty', title: '수량 数量', kind: 'number', width: 90, align: 'end' },
  ],
  rows,
  rowKey: 'id',
};
let mode = 'both';
let say = () => { };
export function setup(api, log) {
  say = log;
  withExport(api);
}
// 글꼴 로더는 한 번만 만들어요. onProgress가 받은 바이트를 알려 주면 아래 work()가 "받는 중 12.3 / 28.2 MB"로 보여 줘요.
// (스크립트 태그로 돌리는 "HTML" 탭에서는 전역 글꼴을 그대로 쓰니까 진행 알림이 없고, 대신 몇 초째인지 알려 줘요.)
const got = { ko: 0, sc: 0 };
let onBytes = () => { };
const koreanFont = createKoreanFont({
  onProgress: ({ loaded }) => {
    got.ko = loaded;
    onBytes();
  },
});
const simplifiedChineseFont = createSimplifiedChineseFont({
  onProgress: ({ loaded }) => {
    got.sc = loaded;
    onBytes();
  },
});
const fontOf = () => (mode === 'both' ? [koreanFont, simplifiedChineseFont] : koreanFont);
// 진행 표시: 막대 하나를 제자리에서 바꿔요(기록에 줄을 쌓지 않아요). 값을 모르면 움직이는 막대예요.
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, sc: 17_772_300 };
const totalBytes = () => FONT_BYTES.ko + (mode === 'both' ? FONT_BYTES.sc : 0);
const loadedBytes = () => got.ko + (mode === 'both' ? got.sc : 0);
const fontNames = () => (mode === 'both' ? 'Noto Sans KR + Noto Sans SC' : 'Noto Sans KR');
let fontsLoaded = false;
/** 글꼴을 받고 PDF를 만드는 일을 감싼다: 안내, 진행 막대, 실패 안내(다시 눌러 보라는 말). 기술적인 오류 내용은 콘솔에만 남긴다. */
async function work(job) {
  await busy(['build', 'download'], async () => {
    const usesFont = true;
    const mb = (totalBytes() / 1e6).toFixed(1);
    const bar = progressBar();
    if (usesFont && !fontsLoaded)
      say({
        ko: `처음 한 번은 글꼴 약 ${mb}MB를 받아요(${fontNames()}). 연결이 느리면 20초 넘게 걸릴 수 있고, 두 번째부터는 바로 만들어져요.`,
        en: `The first time, about ${mb} MB of fonts are downloaded (${fontNames()}). On a slow connection it can take over 20 seconds; later PDFs are made right away.`,
      });
    const started = Date.now();
    let receiving = false;
    got.ko = 0;
    got.sc = 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 fonts… ${s} s${s >= 10 ? ' (a slow connection takes longer)' : ''}`,
      });
    };
    if (usesFont && !fontsLoaded)
      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 fonts ${a} / ${mb} MB (${pct}%)`,
      }, pct);
    };
    // 받은 바이트 알림이 없으면(스크립트 태그로 도는 탭 등) 몇 초째인지만 1초마다 바꿔요.
    const timer = setInterval(() => {
      if (usesFont && !fontsLoaded && !receiving)
        waiting();
    }, 1000);
    try {
      await job();
      if (usesFont)
        fontsLoaded = 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 fonts 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 ?? 'both'),
  build: async (api) => {
    await work(async () => {
      const warnings = [];
      const bytes = await exportPdf(api, { font: fontOf(), onWarning: (w) => warnings.push(w) });
      // 기록은 위가 최신이라, 결과 줄을 마지막에 적어야 맨 위에 보여요.
      for (const w of warnings)
        say(warnText(w));
      if (warnings.length === 0)
        say({
          ko: '경고가 없어요. 한글과 간체가 그대로 들어갔어요.',
          en: 'No warnings. Korean and Simplified Chinese went in as they are.',
        });
      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: fontOf(),
        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 @maxgrid/export-font-sc.

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="both" selected>Korean + Simplified font</option>
      <option value="korean">Korean font only</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';
import { createSimplifiedChineseFont } from '@maxgrid/export-font-sc';
// 라이브러리가 보내는 경고(영어·기술 용어)를 쉬운 말로 바꿔요.
const warnText = (w) => w.code === 'missing-glyph'
  ? {
    ko: `폰트에 없는 글자를 ?로 바꿨어요: ${w.characters}`,
    en: `Characters missing from the font became ?: ${w.characters}`,
  }
  : w.code === 'font-unavailable'
    ? {
      ko: '폰트를 불러오지 못해서 기본 폰트로 만들었어요.',
      en: 'The font could not be loaded, so the default font was used.',
    }
    : {
      ko: '세로로 합친 칸은 PDF에서 합치지 않았어요.',
      en: 'Vertically merged cells were not merged in the 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 customersCn = ['北京商贸', '广东货运', '开发区门店', '上海贸易', '深圳电子', '东方食品'];
const items = ['사과 상자', '철제 선반', '포장 테이프', '전자저울'];
const itemsCn = ['苹果箱', '铁架', '包装胶带', '电子秤'];
const rows = Array.from({ length: 12 }, (_, i) => ({
  id: i + 1,
  orderNo: `SO-${3001 + i}`,
  customer: customers[i % customers.length],
  customerCn: customersCn[i % customersCn.length],
  item: items[i % items.length],
  itemCn: itemsCn[i % itemsCn.length],
  qty: 3 + ((i * 7) % 28),
}));
// 폰트를 [한글 폰트, 간체 폰트]로 이어서 주면 글자마다 앞 폰트에 있으면 그것을, 없으면 뒤 폰트를 써요.
export const options = {
  columns: [
    { id: 'orderNo', title: '주문번호 订单号', width: 110 },
    { id: 'customer', title: '거래처', width: 100 },
    { id: 'customerCn', title: '客户', width: 100 },
    { id: 'item', title: '품목', width: 100 },
    { id: 'itemCn', title: '商品', width: 90 },
    { id: 'qty', title: '수량 数量', kind: 'number', width: 90, align: 'end' },
  ],
  rows,
  rowKey: 'id',
};
let mode = 'both';
let say = () => { };
export function setup(api, log) {
  say = log;
  withExport(api);
}
// 글꼴 로더는 한 번만 만들어요. onProgress가 받은 바이트를 알려 주면 아래 work()가 "받는 중 12.3 / 28.2 MB"로 보여 줘요.
// (스크립트 태그로 돌리는 "HTML" 탭에서는 전역 글꼴을 그대로 쓰니까 진행 알림이 없고, 대신 몇 초째인지 알려 줘요.)
const got = { ko: 0, sc: 0 };
let onBytes = () => { };
const koreanFont = createKoreanFont({
  onProgress: ({ loaded }) => {
    got.ko = loaded;
    onBytes();
  },
});
const simplifiedChineseFont = createSimplifiedChineseFont({
  onProgress: ({ loaded }) => {
    got.sc = loaded;
    onBytes();
  },
});
const fontOf = () => (mode === 'both' ? [koreanFont, simplifiedChineseFont] : koreanFont);
// 진행 표시: 막대 하나를 제자리에서 바꿔요(기록에 줄을 쌓지 않아요). 값을 모르면 움직이는 막대예요.
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, sc: 17_772_300 };
const totalBytes = () => FONT_BYTES.ko + (mode === 'both' ? FONT_BYTES.sc : 0);
const loadedBytes = () => got.ko + (mode === 'both' ? got.sc : 0);
const fontNames = () => (mode === 'both' ? 'Noto Sans KR + Noto Sans SC' : 'Noto Sans KR');
let fontsLoaded = false;
/** 글꼴을 받고 PDF를 만드는 일을 감싼다: 안내, 진행 막대, 실패 안내(다시 눌러 보라는 말). 기술적인 오류 내용은 콘솔에만 남긴다. */
async function work(job) {
  await busy(['build', 'download'], async () => {
    const usesFont = true;
    const mb = (totalBytes() / 1e6).toFixed(1);
    const bar = progressBar();
    if (usesFont && !fontsLoaded)
      say({
        ko: `처음 한 번은 글꼴 약 ${mb}MB를 받아요(${fontNames()}). 연결이 느리면 20초 넘게 걸릴 수 있고, 두 번째부터는 바로 만들어져요.`,
        en: `The first time, about ${mb} MB of fonts are downloaded (${fontNames()}). On a slow connection it can take over 20 seconds; later PDFs are made right away.`,
      });
    const started = Date.now();
    let receiving = false;
    got.ko = 0;
    got.sc = 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 fonts… ${s} s${s >= 10 ? ' (a slow connection takes longer)' : ''}`,
      });
    };
    if (usesFont && !fontsLoaded)
      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 fonts ${a} / ${mb} MB (${pct}%)`,
      }, pct);
    };
    // 받은 바이트 알림이 없으면(스크립트 태그로 도는 탭 등) 몇 초째인지만 1초마다 바꿔요.
    const timer = setInterval(() => {
      if (usesFont && !fontsLoaded && !receiving)
        waiting();
    }, 1000);
    try {
      await job();
      if (usesFont)
        fontsLoaded = 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 fonts 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 ?? 'both'),
  build: async (api) => {
    await work(async () => {
      const warnings = [];
      const bytes = await exportPdf(api, { font: fontOf(), onWarning: (w) => warnings.push(w) });
      // 기록은 위가 최신이라, 결과 줄을 마지막에 적어야 맨 위에 보여요.
      for (const w of warnings)
        say(warnText(w));
      if (warnings.length === 0)
        say({
          ko: '경고가 없어요. 한글과 간체가 그대로 들어갔어요.',
          en: 'No warnings. Korean and Simplified Chinese went in as they are.',
        });
      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: fontOf(),
        onWarning: (w) => warnings.push(w),
      });
      for (const w of warnings)
        say(warnText(w));
      say({ ko: '주문-다국어.pdf를 내려받았어요.', en: 'Downloaded 주문-다국어.pdf.' });
    });
  },
};