40

I am following this package https://www.npmjs.com/package/react-pdf

I got the entire raw pdf data from backend so I was trying with code below.

<ReactPDF file={renderPdf}/>

But it displayed "Failed to load PDF file." I don't wish to save any file in local. The best approach is the display the pdf with the raw data provided by backend.

In terminal, it logged the error:

URIError: Failed to decode param '/%PDF-1.4%%EF%BF%BD%EF%BF%BD%EF%BF%BD%EF%BF%BD%20ReportLab%20Generated%20PDF%20document%20http://www.reportlab.com1%200%20obj%3C%3C/F1%202%200%20R%20/F2%203%200%20R%20/F3%207%200%20R%3E%3Eendobj2%200%20obj%3C%3C/BaseFont%20/Helvetica%20/Encoding%20/WinAnsiEncoding%20/Name%20/F1%20/Subtype%20/Type1%20/Type%20/Font%3E%3Eendobj3%200%20obj%3C%3C/BaseFont%20/Helvetica-Bold%20/Encoding%20/WinAnsiEncoding%20/Name%20/F2%20/Subtype%20/Type1%20/Type%20/Font%3E%3Eendobj4%200%20obj%3C%3C/BitsPerComponent%208%20/ColorSpace%20/DeviceRGB%20/Filter%20[%20/ASCII85Decode%20/FlateDecode%20]%20/Height%20480%20/Length%2036803%20/SMask%205%200%20R%20%20%20/Subtype%20/Image%20/Type%20/XObject%20/Width%20640%3E%3EstreamGb%22-V'
2
  • what does renderPdf look like? Commented Aug 9, 2017 at 17:18
  • @DanO %PDF-1.4 %���� ReportLab Generated PDF document reportlab.com 1 0 obj << /F1 2 0 R /F2 3 0 R /F3 7 0 R >> endobj 2 0 obj << /BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font >> endobj 3 0 obj << /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font >> endobj 4 0 obj << /BitsPerComponent 8 /ColorSpace /DeviceRGB /Filter [ /ASCII85Decode /FlateDecode ] /Height 480 /Length 36803 /SMask 5 0 R /Subtype /Image /Type /XObject /Width 640 >> stream..... Commented Aug 9, 2017 at 17:20

11 Answers 11

74

If you goal is just to view the pdf in your application, the easiest way is using the object tag in HTML. You don't need to import any libraries and works most of the browsers. But this is lack of customization and styles.

  <object data="http://africau.edu/images/default/sample.pdf" type="application/pdf" width="100%" height="100%">
      <p>Alternative text - include a link <a href="http://africau.edu/images/default/sample.pdf">to the PDF!</a></p>
  </object>
Sign up to request clarification or add additional context in comments.

7 Comments

this is perfect! thans
This works just fine when you just need to embed a PDF, thanks for sharing this answer!
iOS browsers have a bug that prevents scrolling with this object embed approach
it doesnot prevent scroll behaviour, i just checked
How to display only pdf without extra controls like sidebar and top bar?
|
16

it looks like you're passing the PDF data directly to the <ReactPDF> component as the value of the file prop. But according to the docs you need to use an object containing a data property:

<ReactPDF
  file={{
    data: renderPdf
  }}
/>

it seems you can also set file to an object containing a url property, to let ReactPDF fetch the pdf from your backend by itself, if that's easier:

<ReactPDF
  file={{
    url: 'http://www.example.com/sample.pdf'
  }}
/>

2 Comments

Tried with first option with data: {renderPdf} which will trigger error. 2nd option is not possible since it will trigger a get request, while my backend perform some sort of authorization which will send a POST request to retrieve the pdf
@MervynLee for the latter you'd probably need to use a csrf token for it to be accepted.
12

Try this You can easily display a PDF in React using the native tag. Just set the data attribute to your PDF URL and define width and height as needed.

✅ No need for extra libraries — works well for simple use cases.

<object width="100%" height="400" data="http://www.africau.edu/images/default/sample.pdf" type="application/pdf">   </object>

7 Comments

it downloads. doesn't render.
ohh it renders...sweet
@NoopurPhalak No!! It didn't render. For me this package did the job! npmjs.com/package/@cyntler/react-doc-viewer Original Reference: youtu.be/E0aK6CKsSNg?si=3YTzshMtVsM-alVs Sorry for confusing language in previous comment
@AjitTStephen It does render the PDF...it worked for me. Here is my code: <object width="100%" height="100%" data={resume.resume} type="application/pdf" /> Here resume is the google cloud storage link to the PDF.
ohh...my links were... aws s3. That would matter ? @NoopurPhalak
|
3

I solved the problem. I convert the binary data that I received from backend into ArrayBuffer.

axios.post(//fire your API).then(response =>
        (response.status === 200? response.data : null))
    .then(pdfdata => {
        var len = pdfdata.length;
        var bytes = new Uint8Array( len );
        for (var i = 0; i < len; i++){
            bytes[i] = pdfdata.charCodeAt(i);
        }

        const renderPdf = bytes.buffer

Then I actually assign bytes.buffer to renderPDF to perform the rendering. Now it is working flawlessly!

In rendering html from react,

import PDF from 'react-pdf-scroll'
<PDF file={renderPdf} scale={1.3} pages={Infinity} />

5 Comments

Hi @MervynLee - Can you please post the full code for your solution?
Hi @JJHolloway, I have posted the code for logic and rendering part in react, anything else?
Thanks @MervynLee -- did you come across an issue where it just says "Loading PDF file..." and never loads the PDF?
@JJHolloway do you mind show the response content returned by server?
The library react-pdf-scroll has been deprecated according to the npm website npmjs.com/package/react-pdf-scroll
1

if your data that is returned from the backend is in the format of buffer then you can set the file info with a parsed JSON object that react-pdf can configure.

file={{data: JSON.parse(renderPDF).data}}

This will render your PDF file.

Comments

1

Expanding the answers posted above this works when using a pdf string

<object data={`data:application/pdf;base64,${base64_pdf_string}`} type="application/pdf" width="100%" height="100%">
      <p>Alternative text</p>
</object>

Comments

1
import { Document, Page } from "react-pdf/dist/esm/entry.webpack";

That will fix your problem. It worked for me

Comments

0
<iframe src="https://docs.google.com/viewer?url=YOUR_PDF_URL&embedded=true" frameborder="0" height="500px" width="100%"></iframe>

In the above iframe, in the src (replace YOUR_PDF_URL), which will work.

1 Comment

Using this way, is it possible to remove the "open in new window" button?
0
 import { Document, Page } from 'react-pdf';

          <div style={{marginLeft:"27%"}}>
            <Document file={fileUrl} onLoadSuccess={onDocumentLoadSuccess} >
              <Page pageNumber={pageNumber} />
            </Document>
            <p style={{marginLeft:"27%"}}>
              Page {pageNumber} of {numPages}
            </p>
          </div>

This will load your pdf make you give the proper URL or data and check https://www.npmjs.com/package/react-pdf

Comments

-1

This is a very old issue causing pdf to get hidden on mobile devices.

Ive tried

<object width="100%" height="400" data="http://www.africau.edu/images/default/sample.pdf" type="application/pdf"></object>

Even this doesn't work

Finally found a working solution

<iframe src={pdf_url} />

Hope This works.

Nice day coding!

Comments

-1

well other than using Document and page from react-pdf . You also need to use pdfjs. I don't know what or how it does but after using pdfjs . I could load my pdf. Just do

pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.js`;

and then

 <Document file={pdf} className="d-flex justify-content-center">
        <Page pageNumber={1} scale={width > 786 ? 1.7 : 0.6} />
      </Document>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.