使用forP循环使用PyPDF2模块合并多个PDF

时间:2018-02-11 14:44:48

标签: python-3.x for-loop pdf pdf-generation pypdf2

我是python的新手,尝试将多个pdf作为参数合并到一个带有PyPDF2模块的pdf但是我得到一个空的pdf文件作为结果 ,我的代码在下面

import os,sys,PyPDF2

pdf_write_object=PyPDF2.PdfFileWriter()

for i in sys.argv[1:]:
 file_object=open(i,'rb')
 pdf_read_object=PyPDF2.PdfFileReader(file_object)
 print('processing file : '+ i + 'number of pages : ' +  str(pdf_read_object.numPages))
 for page in range(pdf_read_object.numPages):
  pdf_write_object.addPage(pdf_read_object.getPage(page))
 file_object.close() 

final_file_object=open('final_PyPDF2.pdf','wb')
pdf_write_object.write(final_file_object)
final_file_object.close()

尝试使用with语句也仍然是相同的结果

#!/usr/bin/python3

import os,sys,PyPDF2

pdf_write_object=PyPDF2.PdfFileWriter()

for i in sys.argv[1:]:
 with open(i,'rb') as file_object:
  pdf_read_object=PyPDF2.PdfFileReader(file_object)
  print('processing file : '+ i + 'number of pages : ' +  str(pdf_read_object.numPages))
  for page in range(pdf_read_object.numPages):
   pdf_write_object.addPage(pdf_read_object.getPage(page))

final_file_object=open('final_PyPDF2.pdf','wb')
pdf_write_object.write(final_file_object)
final_file_object.close()

虽然在python终端上使用上面的方法对单个文件的效果一样好,但我在for循环中缺少一些东西,有人可以指导。

1 个答案:

答案 0 :(得分:0)

不要打开要阅读的文件。 PdfFileReader()可以自动执行,代码也可以运行:

#!/usr/bin/python3

import sys
import PyPDF2

pdf_write_object = PyPDF2.PdfFileWriter()

for i in sys.argv[1:]:
    pdf_read_object = PyPDF2.PdfFileReader(i)
    print('processing file : '+ i + 'number of pages : ' +  str(pdf_read_object.numPages))
    for page in range(pdf_read_object.numPages):
        pdf_write_object.addPage(pdf_read_object.getPage(page))

final_file_object = open('final_PyPDF2.pdf', 'wb')
pdf_write_object.write(final_file_object)
final_file_object.close()