2017-04-22 79 views
0

兩個PDF文件我搜索很多關於這個問題,我沒有找到這個問題的任何精確解,這就是爲什麼我問這個問題......錯誤,同時合併使用PyPDF2

這是我的代碼使用PyPDF2在python合併兩個PDF文件:

import os 
from PyPDF2 import PdfFileReader, PdfFileMerger 

files_dir = "/Users/ajayvictor/" 
pdf_files = [f for f in os.listdir(files_dir) if f.endswith("pdf")] 
merger = PdfFileMerger() 

for filename in pdf_files: 
    merger.append(PdfFileReader(os.path.join(files_dir, filename), "rb")) 

merger.write(os.path.join(files_dir, "merged_full.pdf")) 

發生在解釋這個代碼,我得到的錯誤是:

Traceback (most recent call last): 
    File "newtest.py", line 9, in <module> 
    merger.append(PdfFileReader(os.path.join(files_dir, filename), "rb")) 
    File "/Library/Python/2.7/site-packages/PyPDF2/merger.py", line 203, in append 
    self.merge(len(self.pages), fileobj, bookmark, pages, import_bookmarks) 
    File "/Library/Python/2.7/site-packages/PyPDF2/merger.py", line 151, in merge 
    outline = pdfr.getOutlines() 
    File "/Library/Python/2.7/site-packages/PyPDF2/pdf.py", line 1362, in getOutlines 
    outline = self._buildOutline(node) 
    File "/Library/Python/2.7/site-packages/PyPDF2/pdf.py", line 1449, in _buildOutline 
    raise utils.PdfReadError("Unexpected destination %r" % dest) 
PyPDF2.utils.PdfReadError: Unexpected destination '/__WKANCHOR_2' 

回答

0

我得到了這個替代..

import pyPdf 

filenames=[] 
path='/Users/ajayvictor/' 
output_filename='merged1.pdf' 

for i in range(12153602, 12153604): 
    j=str(i) 
    filenames.append(j + '.pdf') 

output = pyPdf.PdfFileWriter() 

for filename in filenames: 
    input = pyPdf.PdfFileReader(file(path + filename.strip(), "rb")) 
    for page in input.pages: 
     output.addPage(page) 

print(filenames) 
outputstream = file(output_filename, "wb") 
output.write(outputstream) 
outputstream.close()