← 中文资源

简体中文版本

window.print 与 beforeprint 状态切换

用 window.print() 打开打印对话框,beforeprint 把图表换成适合纸面的表格,afterprint 恢复原状,两个事件成对夹住打印过程。

阅读英文原文

实现说明

chart、table 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 浏览器才是这里的运行环境:document、window 在 Node 里拿不到。
  • 守卫 !chart || !table 成立时借助提前的 return 直接离开。

常见问题

「window.print 与 beforeprint 状态切换」能在裸 Node.js 里跑吗?

不能——它用到 document、window。这些 API 只在浏览器里有效,裸 Node 进程没有这些能力,请放到页面(或 DevTools 控制台)里执行。

核心语句

document.querySelector<HTMLButtonElement>('#print-btn')?.addEventListener('click', () => {
  window.print();
});
window.addEventListener('beforeprint', () => {
  if (!chart || !table) return;
  chart.hidden = true;
  table.hidden = false; // paper needs the numbers, not the visualization
});
window.addEventListener('afterprint', () => {
  if (!chart || !table) return;
  chart.hidden = false;
  table.hidden = true;
});

代码示例

// window.print() opens the print dialog; beforeprint/afterprint bracket it so
// screen-only state can be swapped for a print-friendly one and restored.
const chart = document.querySelector<HTMLElement>('#chart-summary');
const table = document.querySelector<HTMLElement>('#chart-table');

window.addEventListener('beforeprint', () => {
  if (!chart || !table) return;
  chart.hidden = true;
  table.hidden = false; // paper needs the numbers, not the visualization
});

window.addEventListener('afterprint', () => {
  if (!chart || !table) return;
  chart.hidden = false;
  table.hidden = true;
});

document.querySelector<HTMLButtonElement>('#print-btn')?.addEventListener('click', () => {
  window.print();
});