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

Flask服务中使用pypdf合并PDF报错:'NoneType'对象不可调用

在Flask服务中使用pypdf合并PDF触发TypeError的解决方法

问题场景

我在Flask服务中编写了合并PDF的接口,代码如下:

@website.route('/test-pypdf', methods=('GET',))
def test_pypdf():
    with open('document.pdf', 'rb') as inFile, open('overlay.pdf', 'rb') as overlay:
        original = PdfReader(inFile)
        background = original.pages[0]
        print(inFile)
        print(background)
        print(type(background))
        foreground = PdfReader(overlay)
        o = foreground.pages[0]
        print(o)
        print(type(o))

        # merge the first two pages
        background.merge_page(o)

    return 'success'

运行后能正常打印对象信息,但执行background.merge_page(o)时抛出错误:TypeError: 'NoneType' object is not callable,且确认对象本身不是None类型。本地终端单独运行这段逻辑完全正常,但部署在Digital Ocean droplet的Flask服务中必现错误,尝试调换合并顺序、更换不同PDF文件都无法解决。

关键差异排查

对比两种环境的打印输出,发现核心差异:

  • 本地终端中,页面对象的类型为pypdf._page.PageObject
  • Flask服务环境中,页面对象的类型为pdfrw.objects.pdfdict.PdfDict,且对象的属性格式存在明显差异

最终解决方法

切换到PyPDF2(该库已合并入pypdf,官方不再更新维护),使用以下代码实现PDF合并,问题得到解决:

from PyPDF2 import PdfFileReader,PdfFileWriter
import sys

f = sys.argv[1]
k = sys.argv[2]
print(f, k)
file1 = PdfFileReader(open(f, "rb"))
file2 = PdfFileReader(open(k, "rb"))
output = PdfFileWriter()
page = file1.getPage(0)
page.mergePage(file2.getPage(0))
output.addPage(page)

with open("join.pdf", "wb") as outputStream:
    output.write(outputStream)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 12:15:06