Display PDF in reactJS

Viewed 81567

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'
8 Answers

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>

Try this

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

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.

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!

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>
<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.

Related