当前位置:首页 > React

react实现模板打印

2026-01-27 05:00:03React

React 实现模板打印的方法

使用 react-to-print 库

安装 react-to-print 库:

npm install react-to-print

创建一个可打印的组件:

import React, { useRef } from 'react';
import { useReactToPrint } from 'react-to-print';

const PrintableComponent = React.forwardRef((props, ref) => {
  return (
    <div ref={ref}>
      <h1>打印内容标题</h1>
      <p>这是要打印的内容</p>
    </div>
  );
});

const PrintButton = () => {
  const componentRef = useRef();
  const handlePrint = useReactToPrint({
    content: () => componentRef.current,
  });

  return (
    <div>
      <PrintableComponent ref={componentRef} />
      <button onClick={handlePrint}>打印</button>
    </div>
  );
};

使用 window.print() 方法

直接调用浏览器打印功能:

const PrintComponent = () => {
  const printContent = () => {
    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
      <html>
        <head>
          <title>打印页面</title>
          <style>
            @media print {
              body { font-family: Arial; }
              .no-print { display: none; }
            }
          </style>
        </head>
        <body>
          <h1>打印内容</h1>
          <p>这是要打印的正文</p>
        </body>
      </html>
    `);
    printWindow.document.close();
    printWindow.print();
  };

  return <button onClick={printContent}>打印</button>;
};

使用 CSS 控制打印样式

添加打印专用样式:

@media print {
  .no-print {
    display: none;
  }
  .print-only {
    display: block;
  }
  body {
    font-size: 12pt;
    color: #000;
  }
}

在组件中应用:

<div>
  <div className="no-print">屏幕显示但不打印的内容</div>
  <div className="print-only">仅打印时显示的内容</div>
  <button onClick={() => window.print()}>打印</button>
</div>

处理复杂打印布局

对于需要特殊布局的打印内容:

const ComplexPrintLayout = () => {
  const printRef = useRef();

  const handlePrint = () => {
    const content = printRef.current.innerHTML;
    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
      <html>
        <head>
          <title>复杂打印布局</title>
          <style>
            @page {
              size: A4 landscape;
              margin: 1cm;
            }
            table {
              width: 100%;
              border-collapse: collapse;
            }
            th, td {
              border: 1px solid #ddd;
              padding: 8px;
            }
          </style>
        </head>
        <body>
          ${content}
        </body>
      </html>
    `);
    printWindow.document.close();
    printWindow.print();
  };

  return (
    <div>
      <div ref={printRef}>
        <table>
          <thead>
            <tr>
              <th>列1</th>
              <th>列2</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>数据1</td>
              <td>数据2</td>
            </tr>
          </tbody>
        </table>
      </div>
      <button onClick={handlePrint}>打印表格</button>
    </div>
  );
};

打印前数据处理

在打印前处理数据:

react实现模板打印

const DataPrintComponent = () => {
  const [data, setData] = React.useState([]);
  const printRef = useRef();

  const fetchDataBeforePrint = async () => {
    const response = await fetch('api/data');
    const result = await response.json();
    setData(result);
    setTimeout(() => window.print(), 500); // 等待数据渲染
  };

  return (
    <div>
      <div ref={printRef}>
        {data.map(item => (
          <div key={item.id}>{item.name}</div>
        ))}
      </div>
      <button onClick={fetchDataBeforePrint}>加载并打印数据</button>
    </div>
  );
};

这些方法提供了从简单到复杂的打印解决方案,可以根据具体需求选择适合的方式实现React应用的打印功能。

标签: 模板react
分享给朋友:

相关文章

如何降低react版本

如何降低react版本

降低 React 项目版本的步骤 检查当前 React 版本 在项目根目录的 package.json 文件中查看 dependencies 或 devDependencies 下的 react 和…

CSS模板网站制作

CSS模板网站制作

CSS模板网站制作指南 制作CSS模板网站需要结合设计、布局和代码实现。以下是关键步骤和方法: 设计阶段 确定网站主题和风格,选择配色方案和字体组合。 使用设计工具(如Figma、Adobe XD…

react 如何分页

react 如何分页

分页实现方法 在React中实现分页功能可以通过多种方式完成,具体取决于数据来源(如API或本地数据)和UI库的选择。以下是常见的实现方法: 使用本地数据分页 对于存储在组件状态或Context中…

react如何动画

react如何动画

React 动画实现方法 React 中实现动画可以通过多种方式,包括原生 CSS、第三方库或 React 内置的动画解决方案。以下是几种常见方法: 使用 CSS 动画和过渡 通过 CSS 的 tr…

react 如何启动

react 如何启动

创建 React 项目 使用官方工具 create-react-app 快速初始化项目,需提前安装 Node.js(版本 ≥ 14.0.0)和 npm/yarn: npx create-react-…

react 如何遍历

react 如何遍历

遍历数组 在React中遍历数组通常使用map方法,它会返回一个新的数组。map是处理数组并渲染列表元素的首选方法。 const items = ['Apple', 'Banana', 'Cherr…