You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确将合并后的PDF以_io.BytesIO传入Django FileResponse?合并后为空页

解决pypdf合并PDF后生成空白文档的问题

以下是几个排查和解决方向:

1. 验证PDF文件的可用性

先确认你读取的PDF文件本身没问题:

  • 检查pdf.location.path是否指向真实存在、可读取的PDF文件,可添加路径验证:
    import os
    for pdf in qs:
        path = pdf.location.path
        if not os.path.exists(path):
            print(f"文件不存在:{path}")
        elif not os.access(path, os.R_OK):
            print(f"无读取权限:{path}")
        else:
            reader = PdfReader(path)
            print(f"文件{path}页面数:{len(reader.pages)}")
    

如果输出页面数为0,说明文件损坏或路径错误,这是空白文档的常见原因。

2. 简化PdfMerger的使用流程

没必要先批量创建PdfReader对象再合并,直接给merger.append()传入文件路径更可靠,减少中间环节的潜在问题:

merger = PdfMerger()
for pdf in qs:
    path = pdf.location.path
    if os.path.exists(path) and os.access(path, os.R_OK):
        merger.append(path)  # 直接传入路径,PdfMerger会自行处理文件读取

3. 优化IO流与资源管理

使用with语句管理PdfMerger和BytesIO,确保资源正确释放,避免写入不完整:

temp = io.BytesIO()
with PdfMerger() as merger:
    for pdf in qs:
        path = pdf.location.path
        if os.path.exists(path):
            merger.append(path)
    merger.write(temp)
temp.seek(0)  # 将指针移到流开头,确保响应能读取全部内容

4. 明确响应的Content-Type

给FileResponse指定PDF的MIME类型,避免浏览器解析异常:

return FileResponse(
    temp,
    as_attachment=True,
    filename=fn,
    content_type='application/pdf'
)

内容的提问来源于stack exchange,提问作者baloersch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 10:12:51