1

我正在编写一个需要合并许多单页 pdf 文件的小脚本。我希望脚本与 Python3 一起运行并尽可能少地依赖。

对于 PDF 合并部分,我尝试使用PyPdf。然而,对 Python 3 的支持似乎有问题。它无法处理 inkscape 生成的 PDF 文件(我需要)。我安装了当前 git 版本的 PyPdf,但以下测试脚本不起作用:

import PyPDF2

output_pdf = PyPDF2.PdfFileWriter()

with open("testI.pdf", "rb") as input:
    input_pdf = PyPDF2.PdfFileReader(input)
    output_pdf.addPage(input_pdf.getPage(0))

with open("test.pdf", "wb") as output:
    output_pdf.write(output)

它抛出以下堆栈跟踪:

Traceback (most recent call last):
  File "test.py", line 7, in <module>
    output.addPage(input.getPage(0))
  File "/usr/lib/python3.3/site-packages/pyPdf/pdf.py", line 420, in getPage
    self._flatten()
  File "/usr/lib/python3.3/site-packages/pyPdf/pdf.py", line 574, in _flatten
    self._flatten(page.getObject(), inherit)
  File "/usr/lib/python3.3/site-packages/pyPdf/generic.py", line 165, in getObject
    return self.pdf.getObject(self).getObject()
  File "/usr/lib/python3.3/site-packages/pyPdf/pdf.py", line 616, in getObject
    retval = readObject(self.stream, self)
  File "/usr/lib/python3.3/site-packages/pyPdf/generic.py", line 66, in readObject
    return DictionaryObject.readFromStream(stream, pdf)
  File "/usr/lib/python3.3/site-packages/pyPdf/generic.py", line 526, in readFromStream
    value = readObject(stream, pdf)
  File "/usr/lib/python3.3/site-packages/pyPdf/generic.py", line 57, in readObject
    return ArrayObject.readFromStream(stream, pdf)
  File "/usr/lib/python3.3/site-packages/pyPdf/generic.py", line 152, in readFromStream
    obj = readObject(stream, pdf)
  File "/usr/lib/python3.3/site-packages/pyPdf/generic.py", line 86, in readObject
    return NumberObject.readFromStream(stream)
  File "/usr/lib/python3.3/site-packages/pyPdf/generic.py", line 231, in readFromStream
    return FloatObject(name.decode("ascii"))
  File "/usr/lib/python3.3/site-packages/pyPdf/generic.py", line 207, in __new__
    return decimal.Decimal.__new__(cls, str(value), context)
TypeError: optional argument must be a context

然而,相同的脚本在 Python 2.7 中可以完美运行。

我在这里做错了什么?这是图书馆的错误吗?我可以在不接触 PyPDF 库的情况下解决它吗?

4

2 回答 2

3

So I found the answer. The decimal.Decimal module in Python3.3 shows some weird behaviour. This is the corresponding StackOverflow question: Instantiate Decimal class I added some workaround to the PyPDF2 library and submitted a pull request.

于 2013-02-22T10:43:06.893 回答
2

只是为了确保您知道已经存在的工具可以做到这一点:

  • PDFtk
  • PDFjam (my favourite, requires LaTeX though)
  • Directly with GhostScript:
    gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=finished.pdf file1.pdf file2.pdf
于 2013-02-22T10:38:15.843 回答