当前位置:首页 > 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`);
};

分享给朋友:

相关文章

如何实现java序列化

如何实现java序列化

实现Java序列化的方法 1. 实现Serializable接口 要使一个类可序列化,需要让该类实现java.io.Serializable接口。这是一个标记接口,没有任何方法需要实现。 publi…

如何实现翻页式h5

如何实现翻页式h5

翻页式H5的实现方法 翻页式H5通常指通过滑动或点击切换页面的交互形式,常用于营销活动、产品展示等场景。以下是几种常见的实现方式: 使用HTML5和CSS3实现基础翻页 通过CSS3的transfo…

前段vue如何实现

前段vue如何实现

Vue 前端实现方法 Vue 是一款流行的前端框架,用于构建用户界面。以下是一些常见的 Vue 实现方法: 组件化开发 Vue 的核心思想是组件化开发。每个组件可以独立封装逻辑、模板和样式,便于复用…

vue实现注册功能

vue实现注册功能

前端实现注册功能 在Vue中实现注册功能通常需要结合表单验证、HTTP请求和状态管理。以下是一个基于Vue 3和Element Plus的完整实现方案: 模板部分 <template>…

php实现评论功能

php实现评论功能

数据库设计 创建评论表(示例结构): CREATE TABLE `comments` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id`…

php秒杀功能的实现

php秒杀功能的实现

秒杀功能的核心设计 高并发场景下秒杀系统的核心在于解决超卖问题和性能瓶颈。需要结合缓存、队列、锁机制等技术实现。 数据库设计 商品表需包含库存字段,例如: CREATE TABLE `seckil…