How to send PDF in express route response and force browser download ? - GeeksforGeeks

26 Apr, 2021
In this article, we will see how to send PDF files in the express route’s response and make the browser force download the file.
Approach:
Load required packages, then create an express app.Define the routes for homepage and PDF download requests.Create an index.html file with a single button to download PDF.Execute ajax call on button click to GET the PDF.Specify responseType of ajax call as “blob” in the xhrFields, as “blob” is used to store objects such as images, audios and videos, since they require more space than other data types.On successful ajax call, convert the received  PDF file from blob format to PDF format.Now, to make the browser force download the PDF –a. Create a hidden <a> tag.b. Create a reference to the file using window.URL.createObjectURL() method.c. Set its href attribute to the blob’s URL.d. Set its download attribute to the filename.e. Click on the <a> tag.f. Remove the <a> tag from the DOM.g. Release an existing object URL, (the reference to the file), and let the browser know not to keep the reference to the file any longer.
Load required packages, then create an express app.
Define the routes for homepage and PDF download requests.
Create an index.html file with a single button to download PDF.
Execute ajax call on button click to GET the PDF.
Specify responseType of ajax call as “blob” in the xhrFields, as “blob” is used to store objects such as images, audios and videos, since they require more space than other data types.
On successful ajax call, convert the received  PDF file from blob format to PDF format.
Now, to make the browser force download the PDF –a. Create a hidden <a> tag.b. Create a reference to the file using window.URL.createObjectURL() method.c. Set its href attribute to the blob’s URL.d. Set its download attribute to the filename.e. Click on the <a> tag.f. Remove the <a> tag from the DOM.g. Release an existing object URL, (the reference to the file), and let the browser know not to keep the reference to the file any longer.
Step 1:  Install necessary packages
Firstly, install the following node packages.
npm install --save express
Step 2: Create a basic Express server setup
Create a file named app.js and with the following code as shown below.
App.js
// Load necessary packagesconst express = require("express");  // create an express appconst app = express();  // define PORT number to listen to the requestsconst PORT = process.env.PORT || 3000;  // to serve files from uploads directoryapp.use("/uploads", express.static("uploads"));  // express routesapp.use("/", require("./routes"));  // listen to requestsapp.listen(PORT, () => console.log(`Server started running on PORT ${PORT}`));
Step 3: Define routes for the app
Create a file named routes.js and with the following code as shown below.
routes.js
// Load necessary packagesconst express = require("express");  // express router const router = express.Router();  // respond with index.html when a GET request is made to the homepagerouter.get("/", (req, res) => {    res.sendFile(__dirname + "/views/index.html");});  // route for handling PDF requestrouter.get("/downloadPDF", (req, res) => {    res.download("uploads/Resume.pdf");});  // export router middleware and use it in app.jsmodule.exports = router;
Step 4: Run the server
Now start your express server using the following command:
node app.js
Step 5: Open browser and enter URL 
Open your favorite browser and in the address bar enter http://localhost:3000/downloadPDF and then hit Enter, Resume.pdf file will get downloaded automatically.
Output:
Step 6: To make the PDF downloadable through a button.
You can make the browser download the PDF one click of a button using on click event listener on the button and then making an ajax request to the above URL.
To make PDF download on button click, firstly create an index.html file with the following contents:
index.html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport"        content="width=device-width, initial-scale=1.0" /> <link  href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css"  rel="stylesheet"  integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6"  crossorigin="anonymous" /></head><body> <div class="container">  <button id="download" class="btn btn-primary my-5">   Download PDF  </button> </div> <script src="https://code.jquery.com/jquery-3.6.0.js"         integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="  crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js"         integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf"  crossorigin="anonymous"> </script>   <script>  $("#download").click(function (e) {   $.ajax({    type: "GET",    url: "/downloadPDF",    xhrFields: {     // specify response type as "blob" to handle objects     responseType: "blob",    },    success: function (data) {       // creating a hidden <a> tag     var a = document.createElement("a");       // creating a reference to the file     var url = window.URL.createObjectURL(data);       // setting anchor tag's href attribute to the blob's URL     a.href = url;       // setting anchor tag's download attribute to the filename     a.download = "Resume.pdf";     document.body.append(a);       // click on the <a> tag     a.click();       // after clicking it, remove it from the DOM     a.remove();     // release an existing object URL which was previously      // created by calling URL.createObjectURL()     // once we have finished using an object URL, let the     // browser know not to keep the reference to the file any longer.     window.URL.revokeObjectURL(url);    },    error: function (result) {     alert("error");    },   });  }); </script></body></html>
Output:
Express.js
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.readFile() Method
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to read and write Excel file in Node.js ?
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?