ArticleZip > Display Pdf In Browser Using Express Js

Display Pdf In Browser Using Express Js

Are you looking to display PDF files in a browser using Express.js? This how-to guide will walk you through the process step by step, so you can seamlessly integrate this functionality into your web application!

Express.js is a popular Node.js framework that enables developers to build robust and scalable web applications. By utilizing Express.js, you can easily serve PDF files to users directly in their browsers.

To get started, you first need to have Node.js and Express.js installed on your system. If you haven't already installed them, head over to the official Node.js website and follow the instructions to get Node.js up and running on your machine. Once you have Node.js installed, you can use npm, the Node Package Manager, to install Express.js by running the following command in your terminal:

Plaintext

npm install express

Next, you'll need to create a new Express.js project. You can do this by running the following commands in your terminal:

Plaintext

mkdir display-pdf
cd display-pdf
npm init -y

After initializing a new Node.js project, you can install the `express-pdf` package, which will allow you to easily render PDF files in the browser. You can install this package by running the following command:

Plaintext

npm install express-pdf

Now that you have the necessary dependencies installed, you can start writing the Express.js code to display PDF files. Create a new JavaScript file, such as `app.js`, and add the following code:

Javascript

const express = require('express');
const app = express();
const port = 3000;
const path = require('path');

app.use(express.static(path.join(__dirname, 'public')));

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'sample.pdf'));
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

In this code snippet, we are creating an Express app that serves static files from the `public` directory. We then create a route that sends a sample PDF file located in the `public` directory to the client when they visit the root URL.

To run your Express.js server and start displaying PDF files in the browser, execute the following command in your terminal:

Plaintext

node app.js

Once your server is running, open your browser and navigate to `http://localhost:3000`. You should see the sample PDF file displayed directly in your browser!

By following these simple steps, you can easily implement PDF file display functionality in your Express.js web application. Whether you're building a document management system, an e-learning platform, or any other web application that requires PDF file rendering, Express.js makes it straightforward to achieve this feature seamlessly.