How to show a PDF Stream on a React Client without any library
Here’s the situation:
i’ve a PDF Stream, coming from a PHP Backend, and i’ve to show it up on a new window called by a React Web App client.
I’ve searched the Web for some PDF Libraries, but i’ve not found nothing that could help me.
The most known libraries are for building a PDF directly from a React App, but not one covers my needs.
So i’ve decided to search a work around, and this is how i made it, and it’s pretty simple.
Explanation:
First of all, we need to get the PDF data from and API endpoint.
axios(`${apiURL}/pdf`, {
method: 'GET',
responseType: 'blob' //Force to receive data in a Blob Format
})
I’ve used axios, it was configured in the project where i’ve implemented the method, but it’s not necessary for this purpose, you can use a simple js fetch().
${apiURL}/pdf should be configured as your API endpoint that returns the PDF stream.
responseType: ‘blob’ is the first part of the “magic”, so we force the API endpoint to send us the data in a Blob format, for our further activities.
Then, we have to format the data received.
//Create a Blob from the PDF Stream
const file = new Blob(
[response.data],
{type: 'application/pdf'});
Here is the second part of the “magic”.
Our Blob response is formatted in a specific Blob variable, where the data are the same take from the server, and wrapped in a application/pdf output.
Now we have only to build a usable URL to show the result to the user, and here’s how:
//Build a URL from the file
const fileURL = URL.createObjectURL(file);
//Open the URL on new Window
window.open(fileURL);
Ta-daaan, a new browser window opens up with the PDF we expected.
Complete Code
axios(`${apiURL}/pdf`, {
method: 'GET',
responseType: 'blob' //Force to receive data in a Blob Format
})
.then(response => {
//Create a Blob from the PDF Stream
const file = new Blob(
[response.data],
{type: 'application/pdf'});
//Build a URL from the file
const fileURL = URL.createObjectURL(file);
//Open the URL on new Window
window.open(fileURL);
})
.catch(error => {
console.log(error);
});
The downloaded version looks fine but when I do it like this, it shows a blank pdf (but with the right dimensions). The data of the pdf is not there.
Good solution but doesnt work for Safari Browser since Safari doesnt support Blob Urls 😑
hello, I have a problem with the execution gold; We cannot open this file An error has occurred. thank you for help