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

how to load local PDF file, not from URL

Open liujianyu2022 opened this issue 3 years ago • 6 comments

I want to load a local PDF file, but I don't know how to do it. On the example, the PDF file was loadded by URL in the "testHighlights". Thanks !!

liujianyu2022 avatar Dec 02 '22 06:12 liujianyu2022

+1 to this issue, would like to load a local PDF file!

akhilgupta1093 avatar Jan 07 '23 00:01 akhilgupta1093

It doesn't look like it does...

https://github.com/agentcooper/react-pdf-highlighter/blob/main/src/components/PdfLoader.tsx#L76-L78

I pulled the source code into my project and changed the loading process

danrasmuson avatar Jan 07 '23 18:01 danrasmuson

@danrasmuson Thanks for the info. If you don't mind, could you point me to your own code where you did that? Would love an example of the change

akhilgupta1093 avatar Jan 09 '23 01:01 akhilgupta1093

Hi @akhilgupta1093

I ended up not using this library as my usecase was simply adding highlights above my pdf text. I ended up solving my problem like this...

<Document
  file={pdfFile}
  onLoadSuccess={setPdf}
>
  <div>
    {
      highlights.map((highlight, i) => <Highlight key={i} boundingRect={highlight.boundingBox} />)
    }
    {
      pdf && new Array(pdf.numPages)
        .fill(0)
        .map((_, i) => (
            <Page
              key={i}
              width={900}
              pageIndex={i}
              renderTextLayer={false}
              renderAnnotationLayer={false}
            />
        ))
    }
  </div>
</Document>

If you do want to use this library and load local files you will need to fork this package or load the source code locally and remove the !url section here https://github.com/agentcooper/react-pdf-highlighter/blob/main/src/components/PdfLoader.tsx#L76-L78

Along with voiding the fetch call here https://github.com/agentcooper/react-pdf-highlighter/blob/main/src/components/PdfLoader.tsx#L80-L87

And likely a few smaller changes to get the class operating internally with the lack of url as needed instance variable https://github.com/agentcooper/react-pdf-highlighter/blob/main/src/components/PdfLoader.tsx#L10

danrasmuson avatar Jan 15 '23 02:01 danrasmuson

@danrasmuson Would you mind to provide the full code/project of loading a local pdf file?

imgonewild avatar Aug 15 '23 15:08 imgonewild

You can transform any blob to url

export const useFileAsUrl = (file: File | null | undefined) => {
  return useMemo(() => {
    if (!file) {
      return "";
    }
    const blob = new Blob([file], { type: "application/pdf" });
    return URL.createObjectURL(blob);
  }, [file]);
};

Naerriel avatar May 17 '24 09:05 Naerriel