python PyPDF2合並pdf問題


使用PyPDF2合並pdf出現的問題

1.問題一:

   錯誤提示:PdfReadWarning: Xref table not zero-indexed. ID numbers for objects will be corrected. [pdf.py:1736]

解決辦法:

1 import sys
2 
3 if not sys.warnoptions:
4     import warnings
5     warnings.simplefilter("ignore")

2.問題二:

  錯誤提示:PyPDF2.utils.PdfReadError: Expected object ID (5 0) does not match actual (4 0); xref table not zero-indexed.

  並且定位錯誤時發現PdfFileReader對象的所有方法都不能使用,比如getNumPages、getPage等

解決辦法:

1 # 讀取源PDF文件  加上strict=False
2 input = PdfFileReader(open(pdf_file, "rb"),strict=False)

合並pdf python代碼  來源:https://www.cnblogs.com/ken-yu/p/13924636.html

 1 # -*- coding:utf-8*-
 2 # 利用PyPDF2模塊合並同一文件夾下的所有PDF文件
 3 # 只需修改存放PDF文件的文件夾變量:file_dir 和 輸出文件名變量: outfile
 4 
 5 import os
 6 from PyPDF2 import PdfFileReader, PdfFileWriter
 7 import time
 8 import sys
 9 
10 if not sys.warnoptions:
11     import warnings
12     warnings.simplefilter("ignore")
13 
14 # 使用os模塊的walk函數,搜索出指定目錄下的全部PDF文件
15 # 獲取同一目錄下的所有PDF文件的絕對路徑
16 def getFileName(filedir):
17 
18     file_list = [os.path.join(root, filespath) \
19                  for root, dirs, files in os.walk(filedir) \
20                  for filespath in files \
21                  if str(filespath).endswith('pdf')
22                  ]
23     return file_list if file_list else []
24 
25 # 合並同一目錄下的所有PDF文件
26 def MergePDF(filepath, outfile):
27 
28     output = PdfFileWriter()
29     outputPages = 0
30     pdf_fileName = getFileName(filepath)
31 
32     if pdf_fileName:
33         for pdf_file in pdf_fileName:
34             print("路徑:%s"%pdf_file)
35 
36             # 讀取源PDF文件
37             input = PdfFileReader(open(pdf_file, "rb"),strict=False)
38 
39             #獲得源PDF文件中頁面總數
40             pageCount = input.getNumPages()
41             outputPages += pageCount
42             print("頁數:%d"%pageCount)
43 
44             # 分別將page添加到輸出output中
45             for iPage in range(pageCount):
46                 output.addPage(input.getPage(iPage))
47 
48         print("合並后的總頁數:%d."%outputPages)
49         # 寫入到目標PDF文件
50         outputStream = open(os.path.join(filepath, outfile), "wb")
51         output.write(outputStream)
52         outputStream.close()
53         print("PDF文件合並完成!")
54 
55     else:
56         print("沒有可以合並的PDF文件!")
57 
58 # 主函數
59 def main():
60     time1 = time.time()
61     file_dir = r"e:\test"   #待合並pdf路徑
62     outfile = "merge.pdf"   #合並好的pdf文件名
63     MergePDF(file_dir, outfile)
64     time2 = time.time()
65     print('總共耗時:%s s.' %(time2 - time1))
66 
67 main()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM