PyPDF2.py 合并pdf时报错问题

报错如下:

Traceback (most recent call last):
  File "./pdf_merge.py", line 68, in <module>
    main(sys.argv[1], sys.argv[2])
  File "./pdf_merge.py", line 51, in main
    blankpage.mergeTranslatedPage(pageobj, 0, 0)
  File "/Users/root/Library/Python/2.7/lib/python/site-packages/PyPDF2/pdf.py", line 2377, in mergeTranslatedPage
    tx, ty], expand)
  File "/Users/root/Library/Python/2.7/lib/python/site-packages/PyPDF2/pdf.py", line 2328, in mergeTransformedPage
    PageObject._addTransformationMatrix(page2Content, page2.pdf, ctm), ctm, expand)
  File "/Users/root/Library/Python/2.7/lib/python/site-packages/PyPDF2/pdf.py", line 2284, in _mergePage
    page2Content, rename, self.pdf)
  File "/Users/root/Library/Python/2.7/lib/python/site-packages/PyPDF2/pdf.py", line 2189, in _contentStreamRename
    op = operands[i]
KeyError: 0

解决:

  1. 打开 /Users/root/Library/Python/2.7/lib/python/site-packages/PyPDF2/pdf.py
  2. 在文件开头加上 import types
  3. 找到函数 _contentStreamRename
    修改函数:
    def _contentStreamRename(stream, rename, pdf):
        if not rename:
            return stream
        stream = ContentStream(stream, pdf)
        for operands, operator in stream.operations:
            # for i in range(len(operands)):
            #     op = operands[i]
            #     if isinstance(op, NameObject):
            #         operands[i] = rename.get(op,op)
            if type(operands) == types.ListType:
                for i in range(len(operands)):
                    op = operands[i]
                    if isinstance(op, NameObject):
                        operands[i] = rename.get(op,op)
            elif type(operands) == types.DictType:
                for i in operands:
                    op = operands[i]
                    if isinstance(op, NameObject):
                        operands[i] = rename.get(op,op)
            else:
                raise KeyError("type of operands is %s" % type(operands))
        return stream
    _contentStreamRename = staticmethod(_contentStreamRename)

参考链接:https://github.com/mstamy2/PyPDF2/issues/196

原文地址:https://www.cnblogs.com/hangj/p/12192128.html