Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open a pdf in new tab in reactjs?

We have the pdf document save in data base , from webapi I am returning as byte array,Now from UI I have to open the pdf in new tab of browser, and user should able to download the pdf. How can I achieve this requirement of opening and downloading the pdf document?

like image 705
Gorakh Nath Avatar asked Jan 10 '17 05:01

Gorakh Nath


People also ask

How do I open a new tab in React js?

To open a page in a new tab on button click in React: When the button is clicked, use the window. open() method to load the resource. Set the target parameter to _blank when calling the open() method.


3 Answers

You can use something like this:

<a href='/api/v1/print/example.pdf' target='_blank' rel='noopener noreferrer'>
like image 173
Max Alekseenko Avatar answered Oct 02 '22 00:10

Max Alekseenko


The following code work for me

try {
    await axios
      .get(uri.ApiBaseUrl + "AccountReport/GetTrialBalancePdfReport", {
        responseType: "blob",
        params: {
          ...searchObject,
        },
      })
      .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
         const pdfWindow = window.open();
         pdfWindow.location.href = fileURL;            
      })
      .catch((error) => {
        console.log(error);
      });
  } catch (error) {
    return { error };
  }
like image 26
Md. Nazrul Islam Avatar answered Oct 02 '22 00:10

Md. Nazrul Islam


Solution from 2020

   import Pdf from '../Documents/Document.pdf';

   <a href={Pdf} without rel="noopener noreferrer" target="_blank">
      <button trailingIcon="picture_as_pdf" label="Resume">
        PDF
      </button>
   </a>
like image 40
Qui-Gon Jinn Avatar answered Oct 02 '22 00:10

Qui-Gon Jinn