[英]How to read local pdf file and send it as response of expressJS application?
這就是我在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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.