react-pdf icon indicating copy to clipboard operation
react-pdf copied to clipboard

PDF Doesn't display, Loading PDF message displayed. No Errors.

Open scarton opened this issue 2 years ago • 6 comments

Before you start - checklist

  • [X] I followed instructions in documentation written for my React-PDF version
  • [X] I have checked if this bug is not already reported
  • [X] I have checked if an issue is not listed in Known issues
  • [X] If I have a problem with PDF rendering, I checked if my PDF renders properly in PDF.js demo

Description

I have to download a PDF from a NodeJS API and render it. The results of the API call render in both the react-pdf test page and also in Firefox. I've also hard-coded the path to a PDF file and that renders fine.

But when used in my app, I get the "Loading PDF" message and that never goes away and tthe PDF doesn't render.

My code is simple enough:

import React, { Component } from 'react';
import { Document, Page } from 'react-pdf/dist/esm/entry.webpack';
import pdfFile from './CMS-2021-0070-0003-attachment_1.pdf';

class CommentPartPDF extends Component {
	constructor(props) {
		super(props);
		this.state = {
			pdf: null,
			pages: 0,
		};  
	}
	
	componentDidMount() {
		fetch(`/api/${this.props.office}/getPdf/${this.props.commentId}/${this.props.attNum}`)
		.then((data) => {
			this.setState({pdf: data});
		});
	}
	
	setPages = (p) => {
		this.setState({pages: p});
	}

	render() {  
		if (this.props.attNum >= 1 && this.state.pdf != null) {
			var pdf=this.state.pdf;
			return (
				<Document file={{data: pdf.data}}
					onLoadError={(e) => console.log(`PDF LOAD ERROR: ${JSON.stringify(e)}`)}
					onLoadSuccess={(p) => this.setPages(p)}>
					<Page pageNumber={1} />
				</Document>
			)
		} else {
			return null;
		}
	};
}
export default CommentPartPDF;

I suspect I'm not setting up the Document file attribute correctly, Any help would be great.

Steve

Steps to reproduce

Simply run the component as above

Expected behavior

Render and display the PDF

Actual behavior

Loading PDF is displayed forever and PDF file isn't displayed

Additional information

None

Environment

  • **Browser (if applicable): Chrome 96, Firefox 94
  • React-PDF version: 5.7.1
  • React version: 16.14.0
  • Webpack version (if applicable): none

scarton avatar Mar 18 '22 18:03 scarton

The code looks fine to me. How does a sample response you get from fetch looks like?

wojtekmaj avatar Mar 18 '22 22:03 wojtekmaj

Well, it looks like a stream of data :) When I plug the URL into the test site, it renders fine. and I can tweak the headers on the response (I wrote the API too) and get a download which opens in FF and Chrome.

scarton avatar Mar 19 '22 00:03 scarton

I am experiencing the same issue.

thomas-barry avatar Mar 30 '22 19:03 thomas-barry

I am experiencing the same issue.

jaskirat1120 avatar May 19 '22 12:05 jaskirat1120

I am experiencing the same issue.

TristynTorriani avatar Jun 13 '22 19:06 TristynTorriani

I had the same issue, and I managed to pinpoint the error.

"Error: The API version "2.12.313" does not match the Worker version "2.16.105"."

In my case I was using the most recent version of pdfjs-dist (to set the worker) but the most recent version of this package only supports up to 2.12.313.

This was the fix (on 5.7.2 of this package):

npm i [email protected]

Also, loading local PDFs did not work for me. You have to convert them to URL as follows:

const blob = await axios.get(pdf, {responseType: "blob"}).then((r) => r.data)
const url = URL.createObjectURL(blob)

Tenpi avatar Sep 01 '22 01:09 Tenpi

This issue is stale because it has been open 90 days with no activity. Remove stale label or comment or this issue will be closed in 14 days.

github-actions[bot] avatar Dec 05 '22 00:12 github-actions[bot]

I have this same issue when trying to load a data stream and convert it to a Buffer (UInt8Array) before writing it into the document:

  const getDocument = useQuery(['my-pdf'],   () => axios.get('https://my-pdf-endpoint.net'), {
    select: (response) => Buffer.from(response.data[0].content)
  });

  console.log('The data', getDocument.data); // Comes in as a UInt8Array object

  return (
    <Dialog open={open} onClose={handleClose} disableEscapeKeyDown>
      <Container
        sx={{
          overflow: 'scroll',
          backgroundColor: 'white',
          borderRadius: '.5rem',
          mt: '.25rem',
        }}
      >
        <Document file={getDocument.data || ''}>
          <Page pageNumber={1} />
        </Document>
    </Container>
  </Dialog

TheNathanBlake avatar Dec 09 '22 20:12 TheNathanBlake

This issue is stale because it has been open 90 days with no activity. Remove stale label or comment or this issue will be closed in 14 days.

github-actions[bot] avatar Mar 13 '23 00:03 github-actions[bot]

This issue was closed because it has been stalled for 14 days with no activity.

github-actions[bot] avatar Apr 03 '23 00:04 github-actions[bot]

I have the same issue, still not resolve it. I am using Next.js

`"use client";

import { ChevronDown, Loader2 } from "lucide-react"; import { pdfjs, Page, Document } from "react-pdf"; import "react-pdf/dist/Page/AnnotationLayer.css"; import "react-pdf/dist/Page/TextLayer.css"; import { useToast } from "./ui/use-toast"; import { useResizeDetector } from "react-resize-detector"; import { Button } from "./ui/button"; import { Input } from "./ui/input"; import { useEffect, useState } from "react";

pdfjs.GlobalWorkerOptions.workerSrc = //unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.js;

interface PDFRendererProps { url: string; }

const PdfRenderer = ({ url }: PDFRendererProps) => { const { toast } = useToast(); const { width, ref } = useResizeDetector(); const [numPages, setNumPages] = useState();

// console.log("===", url);

return ( <div className="w-full bg-white rounded-md shadow flex flex-col items-center"> <div className="h-14 w-full border-b border-zinc-200 flex items-center justify-between px-2"> <div className="flex items-center gap-1.5"> <Button variant={"ghost"} aria-label="previous-page"> <ChevronDown className="h-4 w-4 " /> </Button>

      <div className="flex items-center gap-1.5">
        <Input className="w-12 h-8" />
        <p className="text-zinc-700 text-sm space-x-1">
          <span>/</span>
          <span>{numPages ?? "x"}</span>
        </p>
      </div>
    </div>
  </div>

  <div className="flex-1 w-full max-h-screen" style={{ height: "500px" }}>
    <div ref={ref} style={{ width: "100%", height: "100%" }}>
      {/* <p>{url}</p> */}
      <Document
        file={url}
        loading={
          <div className="flex justify-center">
            <Loader2 className="my-24 h-6 w-6 animate-spin" />
          </div>
        }
        onLoadError={(err) => {
          console.log("err====",err)
          toast({
            title: "Error loading PDF",
            description: "Please try again later.",
            variant: "destructive",
          });
        }}
        onLoadSuccess={({ numPages }) => {
          console.log("PDF loaded successfully with", numPages, "pages");
          setNumPages(numPages)}}
        className="max-h-full ">
        <Page
          width={width ? width : 1}
          pageNumber={1}
          renderTextLayer={false}
        />
      </Document>
    </div>
  </div>
</div>

); };

export default PdfRenderer; `

iamdebobrota avatar Nov 28 '23 10:11 iamdebobrota