2017-05-31 10 views
-1

私はすべてのpdfを1つのpdfに連結してPyPDF2ライブラリを使用しようとしています。 私はpython 2.7を同じものに使用しています。IOError:[Errno 22]無効な引数

私のエラーは次のとおりです。

>>> 
RESTART: C:\Users\Yash gupta\Desktop\first projectt\concatenate\test\New folder\test.py 
['Invoice.pdf', 'Invoice_2.pdf', 'invoice_3.pdf', 'last.pdf'] 

Traceback (most recent call last): 
    File "C:\Users\Yash gupta\Desktop\first projectt\concatenate\test\New folder\test.py", line 17, in <module> 
    pdfReader = PyPDF2.PdfFileReader(pdfFileObj) 
    File "C:\Python27\lib\site-packages\PyPDF2\pdf.py", line 1084, in __init__ 
    self.read(stream) 
    File "C:\Python27\lib\site-packages\PyPDF2\pdf.py", line 1689, in read 
    stream.seek(-1, 2) 
IOError: [Errno 22] Invalid argument 

私のコードは次のとおりです。

import PyPDF2, os 
# Get all the PDF filenames. 
pdfFiles = [] 
for filename in os.listdir('.'): 
    if filename.endswith('.pdf'): 
     pdfFiles.append(filename) 
pdfFiles.sort(key=str.lower) 
pdfWriter = PyPDF2.PdfFileWriter() 

print (pdfFiles) 

# Loop through all the PDF files. 
for filename in pdfFiles: 
    pdfFileObj = open(filename, 'rb') 
    pdfReader = PyPDF2.PdfFileReader(pdfFileObj) 
print (pdfFileObj) 

# Loop through all the pages 
for pageNum in range(0, pdfReader.numPages): 
    pageObj = pdfReader.getPage(pageNum) 
    pdfWriter.addPage(pageObj) 

# Save the resulting PDF to a file. 
pdfOutput = open('last.pdf', 'wb') 
pdfWriter.write(pdfOutput) 
pdfOutput.close() 

私のPDFファイルは、いくつかの非ASCII文字が含まれているので、私は 'r' を使用していますラーテン、その後は 'rb'

PS:私はPythonとこのライブラリのすべてのことに新しいです

答えて

1

私はあなたが収集したファイルを間違っていると考えていますy(Pythonはインデントセンシティブです)。

# Loop through all the PDF files. 
for filename in pdfFiles: 
    pdfFileObj = open(filename, 'rb') 
    pdfReader = PyPDF2.PdfFileReader(pdfFileObj) 

    # Loop through all the pages 
    for pageNum in range(0, pdfReader.numPages): 
     pageObj = pdfReader.getPage(pageNum) 
     pdfWriter.addPage(pageObj) 

    # Save the resulting PDF to a file. 
    pdfOutput = open('last.pdf', 'wb') 
    pdfWriter.write(pdfOutput) 
    pdfOutput.close() 

また、あなたはPDFファイルをマージしたい場合はPdfFileMergerを使用しよう:

merger = PdfFileMerger(strict=False) 

Check out the example code here

+0

おかげで、それをしたが、今、このエラーが ファイル来ている "C:\ Python27 \ libには\サイト・パッケージを\ PyPDF2 \ generic.py"、行585、readFromStreamで %(utils.hexStr(stream.tell ())、key)) PdfReadError:キーの0x2695の辞書の複数の定義/タイプ お手伝いできますか? –

+0

@YashGupta私の答えを更新しました。 – errata