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

Error handling for problematic fonts in PDFlib is not working as

Currently, I am working on a PHP program using PDFlib and encountered the following error while generating the PDF: "PDFlib exception occurred: [1434] info_textline: Option 'font' has bad font handle 0". This is the function where the ...

Ways to manage numerous AJAX actions within a single HTTP request?

Currently, I am utilizing jQuery to create a multipart web page containing a list of links that are updated through periodic AJAX HTTP requests. Each link on the page is triggered by a timer in JavaScript, causing it to make an HTTP request to its designat ...

The error message "Unable to update sessions due to headers being sent to the client" appeared during session regeneration

Having trouble with the "Cannot set headers after they are sent to the client" Error in Express/Passportjs. I understand that this error usually happens when callbacks are called multiple times, but I'm not sure why it's happening in my case. I&a ...

The function .val() is not a recognized method

hello everyone here is the section of my HTML code: <div class="radio"> <input type="radio" name="certain" id="oui" value="oui"/> <label for="oui"> oui </label> <br /> <input type="radio" name="certain" id=" ...

Node.js is essential when using Angular for implementing ui-select components

I'm currently delving into learning AngularJS. I've successfully created a basic web application using AngularJS, with Java EE powering the backend (server side). This app is being hosted on Tomcat. The advantages of AngularJS over JQuery are bec ...

Issue with jQuery function not recognizing escaped double quotes in PHP script

Greetings! I am currently utilizing a custom control with PHP code. $parentLinkCombo = '<select name="ParentComboLink" onchange="changeChildCombo(\"LICENCE\");" id="ParentComboLink" >'; In order to handle the onchange event, I ...

Issue with NodeJS main file not receiving output from a lookupService call within a function

Recently, I've encountered an issue with two of my JavaScript files: 'myinternet_utils.js' and 'server.js'. First, let me share with you the function from 'myinternet_utils.js': exports.hasInternet = function () { req ...

Run a PHP script that creates a PDF file using jQuery AJAX

I am currently working with a form that looks like this: <form action="tcpdf/examples/example_0611.php" method="get"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name="email"><br> <input type="subm ...

Tips for changing array items into an object using JavaScript

I am working with a list of arrays. let arr = ["one","two"] This is the code I am currently using: arr.map(item=>{ item }) I am trying to transform the array into an array of sub-arrays [ { "one": [{ ...

interrupt the node script using async behavior

I encountered an issue while running the npm install command to install a list of modules on Node, specifically related to async. TypeError: undefined is not a function What could be causing this problem? var fs = require( "fs" ), path = require( ...

conceal the mustard-colored dots within the overlay

Whenever I trigger the link, a modal window pops up, but it comes with an unwanted black background color and yellow dots. How can I prevent the yellow dots from showing up on the overlay? http://jsfiddle.net/y88WX/18/embedded/result/ <nav class="da-d ...

The Express.js application functions properly on a local environment, but encounters issues when deployed on Heroku

Currently, I am experiencing an issue with deploying a music visualizer that I created. It seems to work perfectly in all scenarios except when I click on a song to play from the search bar, where I keep encountering a '503 (Service Unavailable)' ...

Style selector for dynamic drop-down menus

import React, { Component } from "react"; export default class FontChanger extends Component{ constructor(props){ super(props); this.state ={ selectedFont: "", currentFont: "", }; this.handleFon ...

When there is no content in the responseText, AJAX will display an error

I've encountered an issue while trying to fetch data using AJAX. The problem lies in receiving an empty responseText. Here's the code I'm working with: JavaScript: function getFounder(id) { var founder = ""; $.ajax({ ...

A JavaScript async function with a nested call inside

Below is my node function for the API server: router.post('/find', async (req, res) => { try { const firewalls = []; let count = 0; const devices = await Device.find({ ...req.body }); devices.forEach(async (item) => { ...

Tips on how to correctly pass a .JSON object in the setState function of a reactJS

I am having an issue when attempting to pass a .json file in the following format: this is my class import MyForm from './MyForm'; class CreateProject extends React.Component{ constructor(){ super(); this.state = { categori ...

Limiting the length of parameters in an Angular directive

Is there a character limit for the parameter being sent to this directive? I'm encountering an issue with my code: header = JSON.stringify(header); columnObj = JSON.stringify(columnObj); $compile('<div column-filter-sort header=' + heade ...

Connecting the v-model in a Vue.js child component to update the parent value

I've encountered an issue with a vue component where I'm trying to link a text input in the child template to a variable in the parent using v-model, but it doesn't seem to be working. How can I make this work? Currently, I am using Vue.js ...

Decryption of Passwords Encrypted with SHA256 in NodeJS

I'm currently diving into the world of encryption and decryption for passwords using NodeJS. I've got my password hashed using SHA256 in my code. Now, the question is: how do I go about decrypting that data? exports.getHashedPassword = function(p ...

Unable to change the variable for the quiz

Currently, I am in the process of developing a quiz app and I am facing an issue with my correct variable not updating. Whenever I trigger the function correctTest() by clicking on the radio button that corresponds to the correct answer, it does get execut ...