[英]make blob url from buffer generated by pdfKit
我在我的快速服务器中使用 pdfKit 生成带有图像的 pdf(每页一个图像),我将 pdfKit 生成的缓冲区发送到前端以便可以下载,这是我的 /genpdf 路由的处理程序:
res.setHeader('Content-Disposition', 'attachment; filename=mypdf.pdf');
res.setHeader('Content-Type', 'application/octet stream');
res.status(200).send(pdfBuffer) // this is the buffer generated by pdfKit
如果我直接在导航器上访问该路线(/genpdf),它工作得很好,它会在新选项卡中打开 pdf(带有图像,每页一个)。
但是,当我想在我的 react 应用程序中使用该 pdf 缓冲区创建可下载的 url 时,问题就来了。
const res = await axios.get('/genpdf');
const url = window.URL.createObjectURL(new Blob([res.data]));
这会生成一个 url,当我访问该 url 时,它会打开一个带有 pdf 的新选项卡,但所有页面都是空白的,所以假设我生成了一个包含 5 个图像的 pdf,它会打开一个包含 5 个页面的 pdf,但它们都是空白的。
编辑:
我没有意识到的一个细节是,如果我打开带有空白页的 pdf 打开的选项卡的控制台,我可以看到来自pdf.worker.js
的这些消息
Warning: Invalid absolute docBaseUrl: "blob:http://localhost:3000/3b38c310-f7a6-4950-b16b-e92369ddc810".
Warning: Indexing all PDF objects
Warning: Invalid stream: "FormatError: Bad FCHECK in flate stream: 120, 239"
Warning: Invalid stream: "FormatError: Bad FCHECK in flate stream: 120, 239"
Warning: Invalid stream: "FormatError: Bad FCHECK in flate stream: 120, 239"
这个来自viewer.js
PDF 538c033f41b7213bc8cc8e2c7c937518 [1.3 PDFKit / PDFKit] (PDF.js: 2.14.290)
这个来自pdf.js
mozCurrentTransform is deprecated and will be removed in the future. Use CanvasRenderingContext2D.getTransform() or CanvasRenderingContext2D.setTransform() instead.
我在这里缺少什么?
所以假设我们发送给客户端的是一个缓冲区(不是数组缓冲区)并且我们使用的是 axios,我们这样处理它:
const requestDocument = async () => {
const response = await axios.get('/getdocument', {
responseType: 'blob',
headers: {
'Content-Type': 'application/pdf'
}
})
const blob = new Blob([response.data], { type: 'application/pdf' });
const url = window.URL.createObjectURL(blob);
}
发送缓冲区时,我不必设置特殊的标头,正如我在问题中提到的,我发送给客户端的缓冲区是 pdfKit 生成的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.