Display Pdf in reactJS
I Am Following This Package I Got the Entire Raw Pdf Data from Backend So I Was Trying with Code Below. but It Displayed "Failed to Load Pdf File." I Don't...
I am following this package
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://
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="" type="application/pdf" width="100%" height="100%">
<p>Alternative text - include a link <a href="">to the PDF!</a></p>
</object>
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: '
}}
/>
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} />
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.
Try this
<object width="100%" height="400" data="" type="application/pdf"> </object>
This is a very old issue causing pdf to get hidden on mobile devices.
Ive tried
<object width="100%" height="400" data="" 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="" frameborder="0" height="500px" width="100%"></iframe>
In the above iframe, in the src (replace YOUR_PDF_URL), which will work.