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

인쇄용 보기 만들기Make a print view

보이는 줄로 인쇄용 표를 만들어 미리 보고 인쇄해요. 인쇄할 때는 이 표만 나와요.Build a print table from the visible rows, preview it and print; only that table is printed.

활용Intermediate
직접 써 보기Live preview인쇄용 보기 만들기Make a print view

코드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 탭이나 직접 해보기를 쓰세요.

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

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="preview">미리 보기</button>
    <button type="button" id="print">인쇄</button>
    <button type="button" id="close">닫기</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);
document.getElementById('preview').addEventListener('click', () => actions.preview(api));
document.getElementById('print').addEventListener('click', () => actions.print(api));
document.getElementById('close').addEventListener('click', () => actions.close(api));
example.js
export const options = {
  columns: [
    { id: 'item', title: '품목', width: 180 },
    { id: 'qty', title: '수량', kind: 'number', width: 80, align: 'end' },
    {
      id: 'amount',
      title: '금액(원)',
      kind: 'number',
      width: 110,
      align: 'end',
      formatValue: (v) => Number(v).toLocaleString('ko-KR'),
    },
  ],
  rows: Array.from({ length: 40 }, (_, i) => ({
    id: i + 1,
    item: `부품 ${String(i + 1).padStart(3, '0')}`,
    qty: 1 + (i % 9),
    amount: 1200 * (1 + (i % 9)),
  })),
  rowKey: 'id',
};
const SHEET_ID = 'mxg-print-sheet';
const STYLE_ID = 'mxg-print-style';
// 숫자 컬럼은 그리드와 같이 오른쪽 정렬이에요(컬럼에 align을 주면 그것을 따라요).
function alignsEnd(column) {
  return column.align === 'end' || (column.align === undefined && column.kind === 'number');
}
// 그리드는 보이는 줄만 그려서, 인쇄할 때는 보이는 줄로 평범한 표를 만들어 써요.
function buildSheet(api) {
  const table = document.createElement('table');
  const head = table.createTHead().insertRow();
  for (const column of api.getColumns()) {
    const th = head.insertCell();
    th.textContent = column.title ?? column.id;
    if (alignsEnd(column))
      th.className = 'e';
  }
  const body = table.createTBody();
  for (const row of api.getVisibleRows()) {
    const tr = body.insertRow();
    for (const column of api.getColumns()) {
      const value = row[column.id];
      const td = tr.insertCell();
      td.textContent = typeof value === 'number' ? value.toLocaleString('ko-KR') : String(value);
      if (alignsEnd(column))
        td.className = 'e';
    }
  }
  const sheet = document.createElement('div');
  sheet.id = SHEET_ID;
  sheet.append(table);
  return sheet;
}
function removeSheet() {
  document.getElementById(SHEET_ID)?.remove();
  document.getElementById(STYLE_ID)?.remove();
}
export function setup() {
  return removeSheet;
}
export const actions = {
  // 화면에서는 위에 덮는 층이고, 인쇄할 때는 다른 것을 모두 숨기고 이 표만 인쇄돼요.
  preview: (api) => {
    removeSheet();
    // 위의 버튼(인쇄·닫기)이 가려지지 않게, 표가 시작하는 높이부터 덮어요.
    const top = Math.max(0, Math.round(document.getElementById('grid')?.getBoundingClientRect().top ?? 0));
    const style = document.createElement('style');
    style.id = STYLE_ID;
    style.textContent = `
    #${SHEET_ID} { position: fixed; top: ${top}px; left: 0; right: 0; bottom: 0; overflow: auto; padding: 24px; background: #fff; color: #000; z-index: 9999; }
    #${SHEET_ID} table { border-collapse: collapse; width: 100%; }
    #${SHEET_ID} th, #${SHEET_ID} td { border: 1px solid #888; padding: 4px 8px; text-align: left; }
    #${SHEET_ID} th.e, #${SHEET_ID} td.e { text-align: right; }
    #${SHEET_ID} thead { display: table-header-group; }
    #${SHEET_ID} tr { break-inside: avoid; }
    @media print { body > *:not(#${SHEET_ID}) { display: none !important; } #${SHEET_ID} { position: static; padding: 0; } }`;
    document.head.append(style);
    const sheet = buildSheet(api);
    sheet.addEventListener('click', removeSheet, { once: true });
    document.body.append(sheet);
  },
  print: (api) => {
    actions.preview(api);
    if (typeof window.print === 'function')
      window.print();
  },
  close: () => removeSheet(),
};

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

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">
    <button type="button" id="preview">Preview</button>
    <button type="button" id="print">Print</button>
    <button type="button" id="close">Close</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);
document.getElementById('preview').addEventListener('click', () => actions.preview(api));
document.getElementById('print').addEventListener('click', () => actions.print(api));
document.getElementById('close').addEventListener('click', () => actions.close(api));
example.js
export const options = {
  columns: [
    { id: 'item', title: 'Item', width: 180 },
    { id: 'qty', title: 'Qty', kind: 'number', width: 80, align: 'end' },
    {
      id: 'amount',
      title: 'Amount ($)',
      kind: 'number',
      width: 110,
      align: 'end',
      formatValue: (v) => Number(v).toLocaleString('en-US'),
    },
  ],
  rows: Array.from({ length: 40 }, (_, i) => ({
    id: i + 1,
    item: `Part ${String(i + 1).padStart(3, '0')}`,
    qty: 1 + (i % 9),
    amount: 1200 * (1 + (i % 9)),
  })),
  rowKey: 'id',
};
const SHEET_ID = 'mxg-print-sheet';
const STYLE_ID = 'mxg-print-style';
// Number columns are right-aligned like in the grid (an explicit column align wins).
function alignsEnd(column) {
  return column.align === 'end' || (column.align === undefined && column.kind === 'number');
}
// The grid draws only the visible rows, so for printing a plain table is built from the visible rows.
function buildSheet(api) {
  const table = document.createElement('table');
  const head = table.createTHead().insertRow();
  for (const column of api.getColumns()) {
    const th = head.insertCell();
    th.textContent = column.title ?? column.id;
    if (alignsEnd(column))
      th.className = 'e';
  }
  const body = table.createTBody();
  for (const row of api.getVisibleRows()) {
    const tr = body.insertRow();
    for (const column of api.getColumns()) {
      const value = row[column.id];
      const td = tr.insertCell();
      td.textContent = typeof value === 'number' ? value.toLocaleString('en-US') : String(value);
      if (alignsEnd(column))
        td.className = 'e';
    }
  }
  const sheet = document.createElement('div');
  sheet.id = SHEET_ID;
  sheet.append(table);
  return sheet;
}
function removeSheet() {
  document.getElementById(SHEET_ID)?.remove();
  document.getElementById(STYLE_ID)?.remove();
}
export function setup() {
  return removeSheet;
}
export const actions = {
  // On screen it is a layer on top; when printing, everything else is hidden and only this table is printed.
  preview: (api) => {
    removeSheet();
    // Cover from the height where the table starts, so the buttons above (print, close) stay visible.
    const top = Math.max(0, Math.round(document.getElementById('grid')?.getBoundingClientRect().top ?? 0));
    const style = document.createElement('style');
    style.id = STYLE_ID;
    style.textContent = `
    #${SHEET_ID} { position: fixed; top: ${top}px; left: 0; right: 0; bottom: 0; overflow: auto; padding: 24px; background: #fff; color: #000; z-index: 9999; }
    #${SHEET_ID} table { border-collapse: collapse; width: 100%; }
    #${SHEET_ID} th, #${SHEET_ID} td { border: 1px solid #888; padding: 4px 8px; text-align: left; }
    #${SHEET_ID} th.e, #${SHEET_ID} td.e { text-align: right; }
    #${SHEET_ID} thead { display: table-header-group; }
    #${SHEET_ID} tr { break-inside: avoid; }
    @media print { body > *:not(#${SHEET_ID}) { display: none !important; } #${SHEET_ID} { position: static; padding: 0; } }`;
    document.head.append(style);
    const sheet = buildSheet(api);
    sheet.addEventListener('click', removeSheet, { once: true });
    document.body.append(sheet);
  },
  print: (api) => {
    actions.preview(api);
    if (typeof window.print === 'function')
      window.print();
  },
  close: () => removeSheet(),
};