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

PDF로 내려받기: 용지·글자 크기·고른 줄Download PDF: paper, font size and selected rows

용지, 방향, 글자 크기와 체크한 줄만 내보내기를 정해서 한글 PDF를 만들어요.Choose paper, orientation, font size and selected-only export to make a Korean PDF.

입문Beginner
직접 써 보기Live previewPDF로 내려받기: 용지·글자 크기·고른 줄Download PDF: paper, font size and selected rows

코드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="size">
      <option value="A4" selected>A4</option>
      <option value="Letter">Letter</option>
    </select>
    <select aria-label="방향" id="orientation">
      <option value="portrait" selected>세로</option>
      <option value="landscape">가로</option>
    </select>
    <select aria-label="글자 크기" id="fontSize">
      <option value="8">8pt</option>
      <option value="9" selected>9pt</option>
      <option value="11">11pt</option>
    </select>
    <select aria-label="내보낼 줄" id="scope">
      <option value="visible" selected>보이는 줄</option>
      <option value="selected">고른 줄만</option>
    </select>
    <button type="button" id="download">내려받기</button>
  </div>
  <div id="grid" style="height: 330px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('size').addEventListener('change', (event) => actions.size(api, event.target.value));
document.getElementById('orientation').addEventListener('change', (event) => actions.orientation(api, event.target.value));
document.getElementById('fontSize').addEventListener('change', (event) => actions.fontSize(api, event.target.value));
document.getElementById('scope').addEventListener('change', (event) => actions.scope(api, event.target.value));
document.getElementById('download').addEventListener('click', () => actions.download(api));
example.js
import { withExport } from '@maxgrid/export';
import { koreanFont } from '@maxgrid/export-font-ko';
// 라이브러리가 보내는 경고(영어·기술 용어)를 쉬운 한국어로 바꿔요.
const warnText = (w) => w.code === 'missing-glyph'
  ? `폰트에 없는 글자를 ?로 바꿨어요: ${w.characters}`
  : w.code === 'font-unavailable'
    ? '한글 폰트를 불러오지 못해서 기본 폰트로 만들었어요.'
    : '세로로 합친 칸은 PDF에서 합치지 않았어요.';
// 만드는 동안 버튼을 잠가서, 두 번 눌러도 파일이 두 개 만들어지지 않게 해요.
async function busy(ids, work) {
  const buttons = ids
    .map((id) => document.getElementById(id))
    .filter((el) => el instanceof HTMLButtonElement);
  if (buttons.some((b) => b.disabled))
    return;
  for (const b of buttons)
    b.disabled = true;
  try {
    await work();
  }
  finally {
    for (const b of buttons)
      b.disabled = false;
  }
}
const 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',
  selection: { mode: 'multiple', checkbox: true },
};
let pageSize = 'A4';
let orientation = 'portrait';
let fontSize = 9;
let selectedOnly = false;
let say = () => { };
export function setup(api, log) {
  say = log;
  withExport(api);
}
export const actions = {
  size: (_api, v) => void (pageSize = v === 'Letter' ? 'Letter' : 'A4'),
  orientation: (_api, v) => void (orientation = v === 'landscape' ? 'landscape' : 'portrait'),
  fontSize: (_api, v) => void (fontSize = Number(v ?? '9')),
  scope: (_api, v) => void (selectedOnly = v === 'selected'),
  download: async (api) => {
    if (selectedOnly && api.getSelectedKeys().length === 0)
      return say({ ko: '체크한 줄이 없어요.', en: 'No rows are checked.' });
    await busy(['download'], async () => {
      say({
        ko: '만드는 중… 처음에는 한글 폰트를 읽느라 몇 초 걸려요.',
        en: 'Building… the first time takes a few seconds to load the Korean font.',
      });
      const warnings = [];
      try {
        await withExport(api).downloadPdf('주문.pdf', {
          pageSize,
          orientation,
          fontSize,
          font: koreanFont,
          title: '주문 목록',
          rowScope: selectedOnly ? 'selected' : 'visible',
          onWarning: (w) => warnings.push(warnText(w)),
        });
        for (const w of warnings)
          say(w);
        say({
          ko: `${pageSize} ${orientation === 'landscape' ? '가로' : '세로'}, ${fontSize}pt로 주문.pdf를 내려받았어요.`,
          en: `Downloaded 주문.pdf as ${pageSize} ${orientation === 'landscape' ? 'landscape' : 'portrait'}, ${fontSize}pt.`,
        });
      }
      catch {
        say({
          ko: 'PDF를 만들지 못했어요. 잠시 뒤에 다시 눌러 주세요.',
          en: 'Could not make the PDF. Please try again in a moment.',
        });
      }
    });
  },
};

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="Paper" id="size">
      <option value="A4" selected>A4</option>
      <option value="Letter">Letter</option>
    </select>
    <select aria-label="Orientation" id="orientation">
      <option value="portrait" selected>Portrait</option>
      <option value="landscape">Landscape</option>
    </select>
    <select aria-label="Font size" id="fontSize">
      <option value="8">8pt</option>
      <option value="9" selected>9pt</option>
      <option value="11">11pt</option>
    </select>
    <select aria-label="Rows" id="scope">
      <option value="visible" selected>Visible rows</option>
      <option value="selected">Selected only</option>
    </select>
    <button type="button" id="download">Download</button>
  </div>
  <div id="grid" style="height: 330px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('size').addEventListener('change', (event) => actions.size(api, event.target.value));
document.getElementById('orientation').addEventListener('change', (event) => actions.orientation(api, event.target.value));
document.getElementById('fontSize').addEventListener('change', (event) => actions.fontSize(api, event.target.value));
document.getElementById('scope').addEventListener('change', (event) => actions.scope(api, event.target.value));
document.getElementById('download').addEventListener('click', () => actions.download(api));
example.js
import { withExport } from '@maxgrid/export';
// Turn the warnings sent by the library (technical terms) into plain English.
const warnText = (w) => w.code === 'missing-glyph'
  ? `Characters missing from the font were replaced with ?: ${w.characters}`
  : w.code === 'font-unavailable'
    ? 'The font could not be loaded, so the default font was used.'
    : 'Vertically merged cells were not merged in the PDF.';
// Lock the buttons while building, so pressing twice does not make two files.
async function busy(ids, work) {
  const buttons = ids
    .map((id) => document.getElementById(id))
    .filter((el) => el instanceof HTMLButtonElement);
  if (buttons.some((b) => b.disabled))
    return;
  for (const b of buttons)
    b.disabled = true;
  try {
    await work();
  }
  finally {
    for (const b of buttons)
      b.disabled = false;
  }
}
const customers = [
  'Harbor Foods',
  'Pine Hardware',
  'Blue Market',
  'Maple Trading',
  'Ocean Supply',
  'Dawn Grocers',
];
const regions = ['Seoul', 'Busan', 'Daejeon', 'Gwangju'];
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),
}));
// A PDF is built with a chosen paper size, orientation, font size, margins and long-text handling.
// This English sample needs no extra font package, so the built-in font is used (font: false).
export const options = {
  columns: [
    { id: 'orderNo', title: 'Order no.', width: 100 },
    { id: 'customer', title: 'Customer', width: 110 },
    { id: 'region', title: 'Region', width: 80 },
    { id: 'qty', title: 'Qty', kind: 'number', width: 70, align: 'end' },
    {
      id: 'price',
      title: 'Price ($)',
      kind: 'number',
      width: 100,
      align: 'end',
      formatValue: (v) => Number(v).toLocaleString('en-US'),
    },
    { id: 'orderedAt', title: 'Ordered', kind: 'date', width: 110 },
  ],
  rows,
  rowKey: 'id',
  selection: { mode: 'multiple', checkbox: true },
};
let pageSize = 'A4';
let orientation = 'portrait';
let fontSize = 9;
let selectedOnly = false;
let say = () => { };
export function setup(api, log) {
  say = log;
  withExport(api);
}
export const actions = {
  size: (_api, v) => void (pageSize = v === 'Letter' ? 'Letter' : 'A4'),
  orientation: (_api, v) => void (orientation = v === 'landscape' ? 'landscape' : 'portrait'),
  fontSize: (_api, v) => void (fontSize = Number(v ?? '9')),
  scope: (_api, v) => void (selectedOnly = v === 'selected'),
  download: async (api) => {
    if (selectedOnly && api.getSelectedKeys().length === 0)
      return say('No rows are checked.');
    await busy(['download'], async () => {
      say('Building…');
      const warnings = [];
      try {
        await withExport(api).downloadPdf('orders.pdf', {
          pageSize,
          orientation,
          fontSize,
          font: false,
          title: 'Order list',
          rowScope: selectedOnly ? 'selected' : 'visible',
          onWarning: (w) => warnings.push(warnText(w)),
        });
        for (const w of warnings)
          say(w);
        say(`Downloaded orders.pdf as ${pageSize} ${orientation}, ${fontSize}pt.`);
      }
      catch {
        say('Could not make the PDF. Please try again in a moment.');
      }
    });
  },
};