VueJS+Spring Boot 后端生成PDF下载后显示空白问题排查求助
PDF下载后显示空白问题解决方案
核心原因
90%以上的该类问题是前端请求未指定二进制响应格式,导致默认字符串编码转换损坏了PDF二进制内容,其次是后端未配置正确的响应头,少数情况为后端本地PDF生成本身就存在问题。
修复步骤
1. 验证后端PDF生成逻辑
在Service层返回字节数组前,先直接打开生成到本地的pdfFile文件:
- 如果本地打开就是空白:排查
createPdfFromTemplate、concat两个PDF生成、拼接方法的逻辑问题 - 如果本地打开正常:属于传输环节问题,继续执行后续修复
2. 修正后端Controller响应配置
不要直接返回byte[],用ResponseEntity指定明确的PDF响应头,避免Spring默认序列化逻辑损坏内容:
@PostMapping(value = "build/{reportId}") public ResponseEntity<byte[]> buildReportFileVersion(@PathVariable Integer reportId, @RequestBody List<Annex> annexToAppendList) throws DocumentTemplateException, IOException { byte[] pdfBytes = reportFileVersionService.buildReportFile(reportId, annexToAppendList); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_PDF); headers.setContentLength(pdfBytes.length); // 如需直接触发下载而非浏览器预览,可添加以下配置 // headers.setContentDispositionFormData("attachment", "custom-report-name.pdf"); return new ResponseEntity<>(pdfBytes, headers, HttpStatus.OK); }
3. 修正前端请求配置
在发起请求的downloadAnnexFile方法中,必须指定响应类型为blob,避免框架默认将二进制响应按UTF-8字符串解析导致内容损坏。以Axios为例,请求配置需添加responseType参数:
// annexService中的请求逻辑示例 function downloadAnnexFile(annexId) { return axios.post(`/api/build/${annexId}`, { // 你的请求参数 }, { responseType: 'blob' // 必须添加该配置 }) }
原有下载逻辑可新增资源释放优化,避免内存泄漏:
downloadAnnex (annexId) { annexService.downloadAnnexFile(annexId).then(res => { const file = new Blob([res.data], { type: 'application/pdf' }) const fileURL = URL.createObjectURL(file) window.open(fileURL) // 预览完成后释放blob资源 setTimeout(() => URL.revokeObjectURL(fileURL), 1000) }).catch(err => console.log(err)) }
内容的提问来源于stack exchange,提问作者arevilla009
相关产品推荐
相关产品推荐

