react-pdf load source everytime when page number changed

I am using react-pdf to render my site and when I tried to custom pagination, I found the pdf file(I stored in the azure storage blob) would be reloaded everytime when I change my page number. I just want to fix this issue.

This is my example code:

const pdfLink = "xxxxx";

export const ViewPdf = () => {
  const { fileId } = useParams<IViewPdfParam>();
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [totalPageNumbers, setTotalPageNumbers] = useState<number>(0);

  const docRef = useRef<IPdfViewerRef>(null);

  const myFile = useMemo(() => {
    return { url: pdfLink };
  }, []);

  const onLoadSuccess = (totalNumber: number) => {
    console.debug("load pdf success", `total number ${totalNumber}`);
    setTotalPageNumbers(totalNumber);
  };

  const onPageChanged = () => {
    setCurrentPage(i => i + 1);
  };

  return (
    <Stack>
      <Document
        ref={docRef}
        // file={myFile} // use the way in wiki
        file={pdfLink}
        onLoadSuccess={ctx => {
          onLoadSuccess(ctx.numPages);
        }}
        className="pdf_fileView_document"
        options={{
          cMapUrl: "cmaps"
        }}
      >
        <Page
          key={`page_${currentPage}`}
          pageNumber={currentPage}
          renderTextLayer={false}
          renderAnnotationLayer={false}
        />
      </Document>
      <DefaultButton onClick={onPageChanged}>Add Page</DefaultButton>
    </Stack>
  );
};

I tried two files, one pdf size is 189MB, and the other one’s is 800+KB.
When I using the large one, it reloads everytime when pagenumber changed, however, when I using the small one, the same initiator(fetch_stream.js) will load the data from disk cache, but still trigger the request.

I tried use url directly and the way in wiki, none of them works.

I also tried to follow this issue, I get my file blob and set it to file property, and meet the same case.

  • It will be generally be the same whatever way a PDF is called since to reset the render the file needs rescanning from finish to start (PDFs are internally very Postscript/Stack/ReversePN like) When a client emits open.PDF#page=5 then 6 each invokation will naturally be a fresh external call to start the render at a new decompressed file pointer and PDF is probably one the slowest ways to open a file.

    – 




Leave a Comment