简体   繁体   中英

How to read local pdf file and send it as response of expressJS application?

This is how I'm generating a pdf file in my expressJS app and send it to the client. But in some cases I need to read an existing local pdf file and return this as the response.

I don't know how to handle this.

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) {
      // how to read local pdf file and output this file?
    } 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

 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 

You need to implement getPathSomehow yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM