PDF Stream in New Tab in React application

Aakash pokhrel
1 min readJan 10, 2022

--

I was working on getting the PDF Stream in new tab using the javascript function but found out that it’s not opening instead it automatically downloads the file . The reason was the response-type from the server is setup as application/octet-stream. If it was setup as application/pdf then window.open could easily open in new tab.

I went to googling about it and found out that saving the stream in a blob would fix that issue. Well, but in my case, it wasn’t the exact solution. The reason is I will get the CORS issue from the client side. So I used the node backend of my application as a proxy server. Below is the detail steps .

First I made the request to the backend along with the pdf-url.

const pdfFunction=(pdfLink)={
const pdfProxy=`http://localhost:8080/pdfApi/${pdfLink}`;
window.open(pdfProxy,'_blank');
}

Here the pdfProxy is my backend get request to get the pdf in exact format(application/pdf) that I want. And the window.open will be able to open it in new tab following the ‘_blank’ option.

Below is my backend code snippet for getting the pdf stream in correct format.

router.get('pdfApi/:apiURL', async (req,res)=>{
const pdfResponse=await Axios.get(apiUrl,{
'responseEncoding':'binary'
}).catch(err=>console.log(err.message));
res.setHeader('Content-type',application/pdf);
res.send(Buffer.from(pdfResponse.data,'binary'));
})

Here we are setting up the responseEncoding as binary while sending request to the server so that the format will not be messed up.(By default it will encode in UTF-8). And finally we are sending the data in a binary format in the last line of the code.

Thanks.

--

--