A simple guide on accessing a local PDF file and returning it as the response for an ExpressJS application

In my ExpressJS application, I have a method for generating a PDF file and sending it to the client. However, there are cases where I need to retrieve an existing local PDF file and return it as the response.

I'm unsure how to handle this scenario.

import express from 'express'
import PDFDocument from 'pdfkit'

const router = express.Router()

router.get('/pdf/:id?',
  async (req, res) => {
    const { id } = req.params

    if (id) {
      // Need assistance with reading and outputting a local PDF file here
    } else {
      const doc = new PDFDocument()
      res.setHeader('Content-disposition', 'inline; filename="output.pdf"')
      res.setHeader('Content-type', 'application/pdf')

      doc
        .rect(60, 50, 200, 120)
        .fontSize(8)
        .text('some text', 64, 54)
        .stroke()

      doc.pipe(res)
      doc.end()
    }        
  }
)

export default router

Answer №1

const fetchPDF = async () => {
  import express from 'express'
  import fs from 'fs'
  import PDFDocument from 'pdfkit'

  const router = express.Router()

  router.get('/pdf/:id?',
    async (req, res) => {
      const { id } = req.params

      if (id) {
        // how to read local pdf file and output this file?
        const filepath = getPathSomehow(id);
        const stream = fs.createReadStream(filepath);
        res.setHeader('Content-disposition', 'inline; filename="output.pdf"')
        res.setHeader('Content-type', 'application/pdf')

        stream.pipe(res);
      } else {
        const doc = new PDFDocument()
        res.setHeader('Content-disposition', 'inline; filename="output.pdf"')
        res.setHeader('Content-type', 'application/pdf')

        doc
          .rect(60, 50, 200, 120)
          .fontSize(8)
          .text('some text', 64, 54)
          .stroke()

        doc.pipe(res)
        doc.end()
      }        
    }
  )

  export default router
}

fetchPDF();

You need to implement getPathSomehow yourself.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding a Vue component to HTML using a script tag: A step-by-step guide

Scenario: I am working on creating a community platform where users can share comments. Whenever a comment contains a URL, I want to turn it into a clickable component. Challenge Statement: I have a dataset in the form of a string and my aim is to replac ...

Copy both the image and JSON object to the clipboard

I am attempting to utilize the clipboard API to write an image and JSON object to the window clipboard. I am working with Vue and Electron and have successfully written an image and plain text, but I encounter an error when trying to write a JSON object: ...

I'm confused, I installed the module but it's still showing an error message saying it can

I've been working on coding a discord music bot, and here is the code I have so far: const config = require('config.json') const Discord = require('discord.js'); const ffmpeg = require('ffmpeg-extra') const client = new ...

Is it possible to set a read-only attribute using getElementByName method

To make a text field "readonly" by placing JavaScript code inside an external JS file, the HTML page cannot be directly modified because it is located on a remote server. However, interaction can be done by adding code in an external JS file hosted on a pe ...

Stop user from navigating to specific route using React-router

I am currently utilizing react-router with history useQueries(createHashHistory)(), and I have a requirement to restrict navigation to certain routes based on the route's configuration. The route configuration looks like this: <Route path="/" name ...

Encountering a problem with Selenium when dealing with tabular data displayed in a DIV format on a website, where each row is encapsulated within its own DIV element

While creating Selenium automation tests for a website with multiple rows contained within a main DIV element, each row represented by a separate DIV. For example, if there are 5 dynamically generated rows, the HTML code structure would look like this: < ...

Javascript alert: forgetting to add ; before statement causes SyntaxError

Seeking to incorporate a post-it application into my django website using Javascript/JQuery. Came across a tutorial and attempted to add it to my script, but encountered a SyntaxError: SyntaxError: missing ; before statement post-it.js:2:19 Not be ...

Three JS does not support dynamic color changing functionality

In my ThreeJS project, I have created a 3D wall and am attempting to change its color dynamically on a click event. However, the code doesn't seem to be working as expected. Can you help me identify the error in the following code snippet? var materi ...

Transform the JSON structure with the power of JavaScript

Seeking assistance in converting the following array of JSON using either javascript or jquery: [ [{"day1":10,"day2":154,"day3":24,"day4":48,"day5":154,"day6":48,"day7":154,"name":"Packet"}], [{"day1":10,"day2":154,"day3":24,"day4":48,"day5":154,"day6":4 ...

Vulnerability protection against AngularJS JSON is not removed

I am currently working on an Angular app that communicates with an API. The JSON responses from the API are prefixed with )]}', as recommended in Angular's official documentation. The issue I am facing is that my browser seems to try decoding th ...

I aim to showcase particular cookies within an input field using jQuery

I am seeking a way to create a responsive page that showcases cookies. My goal is to have the output of a function automatically appear in the input value upon loading the page, instead of requiring a click event. Here is the code snippet I have been worki ...

Highcharts introduces shared tooltips for specific data series

I am seeking to implement specific behavior in highcharts regarding tooltips. The desired setup includes having two types of tooltips: the default shared tooltip a custom tooltip For the custom tooltip, a simple formatter can be utilized. However, the c ...

Configuring headless unit testing with requirejs

Seeking a JavaScript unit testing environment, I feel like I'm on a quest for the Holy Grail. The criteria are as follows: testing Requirejs AMD modules isolating each module by mocking out dependencies ability to test in-browser during development ...

Tips for organizing an array of objects in JavaScript according to a specific attribute value?

I'm trying to sort an array of notification objects in decreasing order of severity: Error > Warning > Information. For example: var notificationArray = [ { code : "103", severity : "Error" }, { code : "104", severity : "Inform ...

Incorporating Ajax to allow users to choose an option from a selection for

I want to populate a dropdown menu with values received from an ajax call in the form of a json array. However, the current code results in an empty select element being created. $.ajax({ type: "GET", url: "/wp-content/gta/search_airport.php", data: ...

Tips on setting dynamic headers in tabulator

Is there a way to dynamically set the header name passed from JSON? Additionally, how can I hide multiple columns in Tabulator instead of just one? I would also like to be able to show/hide multiple columns on button click. These questions pertain to a co ...

Despite Functioning Locally, React/Express App is Missing on Heroku Deployment

After successfully running my React/Express application locally, I deployed it to Heroku only to find that the app is not working. A 404 error keeps popping up and I can't figure out why. I meticulously checked my code for any typos or errors but cou ...

Tips for transferring a Spring MVC controller variable to JavaScript

I am currently working on retrieving a variable for a JavaScript function from an object that is sent to the view by the controller. The object I am dealing with is called Bpmsn. https://i.sstatic.net/FxlAo.png Through the controller, I have injected th ...

Safari's Web Audio API suffering from subpar performance and various shortcomings

For my University project, I am developing an HTML and JavaScript-based mp3 player using the Web Audio API. You can check out the progress of this project by visiting this link: While everything is running smoothly on Firefox and Chrome, Safari is posing ...

Generate random floating numbers at intervals and calculate their sum

I've been given a task to complete. Upon page load, there should be 10 fields labeled as A, B, C, D ... each with the initial value of 3. After the page has loaded, every 2 seconds all field values should change randomly. The change will be a rand ...