You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React TS实现PDF转翻页书遇问题求助(附代码)

React中使用turn.js和pdf-lib实现PDF翻页书遇到的问题

我在React环境中尝试用turn.js、pdf-lib等库将PDF文件转为翻页书,但访问网页时IDM会自动下载目标PDF文件,且翻页书无法正常显示,折腾多日没解决,求技术支持。

以下是我的实现代码:

import "turn.js";
import { PDFDocument } from 'pdf-lib';
import Turn from "./Turn";
import { useEffect, useState } from "react";
import axios from "axios";

const isTouch = 'ontouchstart' in window || navigator.maxTouchPoints > 0;

const options = {
  width: 800,
  height: 600,
  autoCenter: true,
  display: "double",
  acceleration: true,
  elevation: 50,
  gradients: !isTouch,
};

interface PDFinterface {
  url: string;
}

const PDFViewer: React.FC<PDFinterface> = ({ url }) => {
  const [images, setImages] = useState<string[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(true); // State to track loading

  useEffect(() => {
    async function loadPdf() {
      try {
        const response = await axios.get(url, {
          responseType: 'arraybuffer', // Set responseType to arraybuffer to get binary data
          withCredentials: true
        });
        const pdfBuffer = response.data;
        return PDFDocument.load(pdfBuffer);
      } catch (error) {
        console.error('Error loading PDF:', error);
        throw new Error('Failed to load PDF');
      }
    }
    // loadPdf()

    const fetchAndRenderPages = async () => {
      const pdf = await loadPdf();
      const imageUrls: string[] = [];

      for (let i = 0; i < pdf.getPageCount(); i++) {
        const imageUrl = await fetchPdfPage(pdf, i);
        imageUrls.push(imageUrl);
      }

      setImages(imageUrls); // Set the state after fetching images
      setIsLoading(false); // Set loading state to false after loading is complete
    };

    fetchAndRenderPages();
  }, [url]);

  const fetchPdfPage = async (pdf: any, pageNumber: number) => {
    const page = pdf.getPage(pageNumber);
    const imageBytes = await page?.toPng();
    
    if (!imageBytes) {
      throw new Error('Failed to render PDF page as image');
    }
    
    const imageUrl = URL.createObjectURL(new Blob([imageBytes], { type: 'image/png' }));
    return imageUrl;
  };

  if (isLoading) {
    // Render loader while loading
    return (
      <div className="loader">
        Loading...
      </div>
    );
  }

  return (
    <Turn options={options} className="mx-auto">
      {images.map((image, index) => (
        <div key={index} className="page">
          <img src={image} alt="" className="max-w-full h-full" />
        </div>
      ))}
    </Turn>
  );
};

export default PDFViewer;

内容的提问来源于stack exchange,提问作者Bibisoltan Rustamowa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 05:12:47