728 x 90

Send pdf from Node to React for viewing and downloading

Send pdf from Node to React for viewing and downloading

In this tutorial, we will learn how to send pdf files from node to react end for viewing and downloading.

In this tutorial, we will learn how to send pdf files from node to react end for viewing and downloading.

pdf

Step 1 →
First, let’s make a server using node and express to serve a pdf file.
Create a folder called server and inside that folder “run npm” init to create package.json file.
Then let’s install basic dependencies needed by running command
npm install express cors
cors package is used here to avoid cors related errors
Then create a file called app.js and keep it blank for now.

Step 2 →
Create a folder called public and inside that folder put a pdf file which you want to serve on react end (Note that this pdf file can be dynamic but for this tutorial purpose we will use static pdf file)

Step 3 →
Then open previously created app.js file and put below content in it

const express = require("express");
const app = express();
const fs = require("fs");
const port = process.env.PORT || 4000;
const cors = require("cors");
app.use(cors());
// Pdf route that will serve pdf
app.get("/pdf", (req, res) => {
  var file = fs.createReadStream("./public/sample.pdf");
  file.pipe(res);
});
app.listen(port, () => {
  console.log("Server listining on port ", port);
});


Here we are serving pdf file stored in public folder as a stream.
Now run the server with a command
node app.js

Step 4 →
Now let’s create our react end of the app
First run below command to create a basic react app
create-react-app client
(You can run this command inside server folder or outside server folder)
Lets install package axios (Below this tutorial there is fetch implementation of the same)
npm i axois

Step 5 →
Inside client folder →src →App.js
Remove all code in app.js and put below code in it

import React, { Component } from "react";
import axios from "axios";
class App extends Component {
  viewHandler = async () => {
    axios(`http://localhost:4000/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);
      });
  };
  render() {
    return (
      <div>
        <button onClick={this.viewHandler}> View Pdf </button>{" "}
      </div>
    );
  }
}
export default App;


The code above is commented with details of what it is doing.
Now run npm start to run client and “click view pdf” button
You may get below pop up , allow that to view pdf file


Fetch implementation of above code →

fetch(`http://localhost:4000/pdf`, {
  method: "GET",
  headers: {
    "Content-Type": "application/pdf"
  }
})
  .then(res => res.blob())
  .then(response => {
    //Create a Blob from the PDF Stream
    console.log(response);
    const file = new Blob([response], {
      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);
  });


In this tutorial, we sent a pdf from the node as a stream and inside client i.e react, we are forcing to receive it as a blob, and after receiving blob we are building url out of it and opening it in a new window

Akash
EDITOR
PROFILE

Posts Carousel

Leave a Comment

Your email address will not be published. Required fields are marked with *

Latest Posts

Top Authors

Most Commented

Featured Videos