PDFKit生成PDF后,React中Blob URL预览空白的问题排查
问题:React中下载PDFKit生成的PDF显示空白
场景还原
Express服务器通过PDFKit生成每页含单张图片的PDF,/genpdf路由处理代码如下:
res.setHeader('Content-Disposition', 'attachment; filename=mypdf.pdf'); res.setHeader('Content-Type', 'application/octet stream'); res.status(200).send(pdfBuffer) // pdfBuffer为PDFKit生成的Buffer
直接在浏览器访问该路由时,PDF可正常打开且每页图片显示正常。但在React应用中通过以下代码转换为可下载URL时,生成的PDF页面数量正确但全部空白:
const res = await axios.get('/genpdf'); const url = window.URL.createObjectURL(new Blob([res.data]));
控制台错误提示
打开空白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默认会将响应内容以UTF-8字符串格式解析,而PDF是二进制文件,字符串化过程会破坏原始二进制数据,导致后续生成的Blob无法被PDF阅读器正确解析(这就是控制台中“Bad FCHECK in flate stream”错误的来源)。
解决步骤
修改Axios请求配置,保留二进制数据
在Axios请求中添加responseType: 'arraybuffer',让Axios直接返回原始二进制数组,避免数据损坏:const res = await axios.get('/genpdf', { responseType: 'arraybuffer' }); // 创建Blob时指定正确的MIME类型 const url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/pdf' }));优化Express响应头(可选但推荐)
原代码中Content-Type的写法有误,正确的二进制流类型是application/octet-stream(注意连字符),或者直接使用PDF的专属MIME类型application/pdf更准确:res.setHeader('Content-Disposition', 'attachment; filename=mypdf.pdf'); res.setHeader('Content-Type', 'application/pdf'); res.status(200).send(pdfBuffer);
内容的提问来源于stack exchange,提问作者GhostOrder
相关产品推荐
相关产品推荐

