当前位置:首页 > React

react如何实现直接打印pdf

2026-01-25 07:46:33React

使用 react-to-print 库实现 PDF 打印

安装 react-to-print 库:

npm install react-to-print

创建一个可打印的组件:

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

class PrintableComponent extends React.Component {
  render() {
    return (
      <div>
        <h1>可打印内容</h1>
        <p>这里是要打印的内容</p>
      </div>
    );
  }
}

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

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

export default PrintComponent;

使用 window.print() 方法

创建一个打印按钮并绑定 window.print():

const PrintButton = () => {
  const handlePrint = () => {
    window.print();
  };

  return <button onClick={handlePrint}>打印页面</button>;
};

添加打印样式到 CSS 文件:

@media print {
  body * {
    visibility: hidden;
  }
  .printable-area, .printable-area * {
    visibility: visible;
  }
  .printable-area {
    position: absolute;
    left: 0;
    top: 0;
  }
  .no-print {
    display: none;
  }
}

使用 html2canvas 和 jsPDF 生成 PDF

安装所需库:

react如何实现直接打印pdf

npm install html2canvas jspdf

实现代码:

import React from 'react';
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';

const PDFGenerator = () => {
  const printRef = React.useRef();

  const handleDownloadPdf = async () => {
    const element = printRef.current;
    const canvas = await html2canvas(element);
    const data = canvas.toDataURL('image/png');

    const pdf = new jsPDF();
    const imgProperties = pdf.getImageProperties(data);
    const pdfWidth = pdf.internal.pageSize.getWidth();
    const pdfHeight = (imgProperties.height * pdfWidth) / imgProperties.width;

    pdf.addImage(data, 'PNG', 0, 0, pdfWidth, pdfHeight);
    pdf.save('print.pdf');
  };

  return (
    <div>
      <div ref={printRef}>
        <h1>要转换为PDF的内容</h1>
        <p>这里是详细内容</p>
      </div>
      <button onClick={handleDownloadPdf}>下载PDF</button>
    </div>
  );
};

export default PDFGenerator;

使用 @react-pdf/renderer 生成 PDF 文档

安装库:

npm install @react-pdf/renderer

创建 PDF 文档组件:

react如何实现直接打印pdf

import React from 'react';
import { Page, Text, View, Document, StyleSheet, PDFDownloadLink } from '@react-pdf/renderer';

const styles = StyleSheet.create({
  page: {
    flexDirection: 'row',
    backgroundColor: '#E4E4E4'
  },
  section: {
    margin: 10,
    padding: 10,
    flexGrow: 1
  }
});

const MyDocument = () => (
  <Document>
    <Page size="A4" style={styles.page}>
      <View style={styles.section}>
        <Text>Section #1</Text>
      </View>
      <View style={styles.section}>
        <Text>Section #2</Text>
      </View>
    </Page>
  </Document>
);

const PDFExport = () => (
  <div>
    <PDFDownloadLink document={<MyDocument />} fileName="somename.pdf">
      {({ loading }) => (loading ? 'Loading document...' : 'Download now!')}
    </PDFDownloadLink>
  </div>
);

export default PDFExport;

注意事项

确保打印内容在渲染时完全加载,避免打印空白页或部分内容

对于复杂布局,可能需要调整 CSS 打印样式以确保正确显示

某些浏览器可能需要用户手动允许弹出窗口进行打印操作

考虑添加加载状态,特别是在生成大型 PDF 文件时

分享给朋友:

相关文章

vue如何实现记住我

vue如何实现记住我

实现“记住我”功能的步骤 在Vue中实现“记住我”功能通常涉及前端保存用户登录状态(如token)到本地存储,并在下次访问时自动恢复登录状态。以下是具体实现方法: 使用localStorage或co…

vue如何实现原理

vue如何实现原理

Vue 实现原理的核心机制 Vue.js 的核心实现原理基于响应式系统、虚拟 DOM 和组件化设计。以下是关键机制的详细解析: 响应式系统 Vue 通过 Object.defineProperty(…

vue如何实现select

vue如何实现select

Vue 实现 Select 组件的方法 在 Vue 中实现 Select 组件可以通过原生 HTML <select> 元素或使用第三方 UI 库(如 Element UI、Ant Des…

vue如何实现级联

vue如何实现级联

实现级联选择器的基本方法 在Vue中实现级联选择器通常使用现成的组件库或自定义组件。以下是两种常见方式: 使用Element UI的Cascader组件 安装Element UI后,直接使用el-c…

vue如何实现刷新

vue如何实现刷新

实现页面刷新的方法 在Vue中实现刷新功能可以通过以下几种方式实现: 使用location.reload() 直接调用浏览器的原生方法强制刷新整个页面: methods: { refreshP…

vue如何实现控制

vue如何实现控制

Vue 实现控制的方法 Vue 提供了多种方式来实现对应用的控制,包括数据绑定、条件渲染、循环渲染、事件处理等。以下是几种常见的控制方法: 数据绑定 通过 v-model 指令实现双向数据绑定,可以…