当前位置:首页 > 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() 方法

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

react实现模板打印

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;
  }
}

在组件中应用:

react实现模板打印

<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>
  );
};

打印前数据处理

在打印前处理数据:

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
分享给朋友:

相关文章

vue实现a4打印模板

vue实现a4打印模板

使用Vue实现A4打印模板 在Vue中实现A4打印模板需要结合CSS的打印样式和Vue的模板渲染能力。以下是具体实现方法: 设置A4纸张尺寸 在CSS中定义A4纸张的标准尺寸(210mm × 297…

react moment如何使用

react moment如何使用

安装 react-moment 通过 npm 或 yarn 安装 react-moment 包。确保项目中已安装 moment.js,因为 react-moment 依赖它。 npm install…

react实现vue

react实现vue

React 实现 Vue 功能 React 和 Vue 是两种不同的前端框架,但可以通过一些方法在 React 中实现 Vue 的特性。以下是几种常见 Vue 功能在 React 中的实现方式:…

vue实现a4打印模板

vue实现a4打印模板

Vue 实现 A4 打印模板 页面布局与样式设置 设置 A4 纸张尺寸(210mm × 297mm)的打印样式,通过 CSS 确保打印内容适配纸张。在 Vue 组件的 <style> 标签…

react native如何启动

react native如何启动

如何启动 React Native 项目 安装 Node.js 和 npm 确保已安装 Node.js(建议版本 16 或更高)和 npm(Node.js 自带)。可通过以下命令检查版本: node…

如何手写一个react

如何手写一个react

手写一个简单的 React 创建一个基础的 React 实现需要理解其核心概念:虚拟 DOM、组件、状态管理和渲染。以下是一个简化版的 React 实现。 创建虚拟 DOM 虚拟 DOM 是真实…