Как прочитать локальный PDF-файл и отправить его в ответ на заявку ExpressJS? - PullRequest
0 голосов
/ 10 июля 2019

Вот так я генерирую файл pdf в своем приложении expressJS и отправляю его клиенту.Но в некоторых случаях мне нужно прочитать существующий локальный файл PDF и вернуть его в качестве ответа.

Я не знаю, как с этим справиться.

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

1 Ответ

1 голос
/ 10 июля 2019

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

Вам нужно реализовать getPathSomehow самостоятельно.

...