这就是我在expressJS应用程序中生成pdf文件并将其发送给客户端的方式。 但在某些情况下,我需要读取现有的本地 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
最佳答案
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
。
关于javascript - 如何读取本地pdf文件并将其作为expressJS应用程序的响应发送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56968051/