当前位置:首页 > React

react如何实现打印pdf功能

2026-01-25 05:16:36React

使用react-to-print库

安装react-to-print库:

npm install react-to-print

创建一个可打印的组件:

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

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

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

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

使用PDF库生成PDF

安装pdf-lib库:

npm install pdf-lib

创建并下载PDF文件:

import { PDFDocument, StandardFonts, rgb } from 'pdf-lib';

const generatePdf = async () => {
  const pdfDoc = await PDFDocument.create();
  const page = pdfDoc.addPage();
  const { width, height } = page.getSize();

  const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
  page.drawText('Hello World!', {
    x: 50,
    y: height - 50,
    size: 30,
    font,
    color: rgb(0, 0, 0),
  });

  const pdfBytes = await pdfDoc.save();
  const blob = new Blob([pdfBytes], { type: 'application/pdf' });
  const url = URL.createObjectURL(blob);

  const link = document.createElement('a');
  link.href = url;
  link.download = 'document.pdf';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

使用浏览器打印API

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

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

// 在组件中
<button onClick={handlePrint}>打印页面</button>

样式调整优化打印效果

添加打印样式表:

@media print {
  body * {
    visibility: hidden;
  }
  .print-container, .print-container * {
    visibility: visible;
  }
  .print-container {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
  }
  .no-print {
    display: none;
  }
}

使用html2canvas和jspdf组合

安装依赖:

npm install html2canvas jspdf

实现截图转PDF:

react如何实现打印pdf功能

import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';

const exportToPDF = async (elementId, fileName) => {
  const element = document.getElementById(elementId);
  const canvas = await html2canvas(element);
  const imgData = canvas.toDataURL('image/png');

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

  pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
  pdf.save(`${fileName}.pdf`);
};

分享给朋友:

相关文章

vue实现审核功能

vue实现审核功能

实现审核功能的基本思路 审核功能通常涉及状态管理、权限控制和操作记录。Vue中可以通过组件化设计、状态管理库(如Vuex或Pinia)和后端API配合实现。 审核状态管理 使用Vuex或Pinia存…

vue如何实现记住我

vue如何实现记住我

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

vue实现后台功能

vue实现后台功能

Vue 实现后台功能的方法 Vue.js 是一个流行的前端框架,适合构建后台管理系统。以下是实现后台功能的常见方法和步骤。 项目初始化 使用 Vue CLI 或 Vite 初始化项目: # Vue…

如何实现语音react

如何实现语音react

语音识别基础设置 在React中实现语音识别功能通常需要借助浏览器的Web Speech API或第三方库。Web Speech API提供了SpeechRecognition接口,允许应用程序直接访…

vue如何实现滚动

vue如何实现滚动

Vue 实现滚动的方法 使用原生滚动 在Vue中可以直接使用HTML原生滚动,通过CSS设置overflow: auto或overflow: scroll来实现滚动效果。适用于简单场景。 <d…

h5能实现抽题功能吗

h5能实现抽题功能吗

H5实现抽题功能的技术方案 H5完全能够实现抽题功能,主要通过前端技术结合后端数据交互完成。以下是具体实现方式: 前端技术实现 HTML5结合JavaScript可以动态生成和展示题目,利用DOM操…