问题出现在使用PDFMake库生成PDF时。由于生成PDF的过程需要较长的时间,因此将其作为Blob返回。但是,在NextJS + Vercel中,由于应用程序部署在服务器上,客户端无法直接访问生成的Blob URL。因此,客户端会尝试发送HTTP请求以获取文件内容,但由于Blob尚未完全生成,因此请求将等待直到Blob可用或超时。
解决这个问题的办法是,使用Node.js的readable streams功能。它提供了将大型文件分成类似数据块的功能。这样,我们可以将PDFMake生成的Blob pipe到res(响应)对象中。当客户端通过访问响应对象时,它会立即开始增量地接收Blob数据,而不需要等待Blob生成完成。
以下是一个可以解决Blob流问题的示例:
const PdfPrinter = require('pdfmake')
const stream = require('stream')
export default async (req, res) => {
const fonts = {
Roboto: {
normal: 'fonts/Roboto-Regular.ttf',
bold: 'fonts/Roboto-Medium.ttf',
italics: 'fonts/Roboto-Italic.ttf',
bolditalics: 'fonts/Roboto-MediumItalic.ttf',
},
}
const printer = new PdfPrinter(fonts)
const docDefinition = {
content: [
{ text: 'Hello World!', fontSize: 22 },
],
}
const pdfStream = printer.createPdfKitDocument(docDefinition).pipe(new stream.PassThrough())
res.setHeader('Content-Type', 'application/pdf')
res.setHeader('Content-Disposition', 'attachment; filename=hello-world.pdf')
pdfStream.pipe(res)
}