這個小知識來自公眾號【python小屋】
問題描述:
給定一個PDF文件,對其進行任意切分,提取其中任意頁面,保存為新的PDF文件。
准備工作:
安裝擴展庫PyPDF2,參考命令
pip install PyPDF2
參考代碼:
from PyPDF2 import PdfFileReader, PdfFileWriter def split_pdf(filename, result, start=0, end=None): """從filename中提取[start,end)之間的頁碼內容保存為result""" # 打開原始 pdf 文件 pdf_src = PdfFileReader(filename) if end is None: # 獲取頁數 end = pdf_src.getNumPages() with open(result, "wb") as fp: # 創建空白pdf文件 pdf = PdfFileWriter() # 提取頁面內容,寫入空白文件 for num in range(start, end): pdf.addPage(pdf_src.getPage(num)) # 寫入結果pdf pdf.write(fp) fn = r"G:\a001\第九天.pdf" split_pdf(fn, "1.pdf", 0, 3) split_pdf(fn, "2.pdf", 1, 3) split_pdf(fn, "3.pdf", 2, 3)
遇見的問題:
Traceback (most recent call last): File "G:/a001/pdf.py", line 22, in <module> split_pdf(fn, "1.pdf", 0, 3) File "G:/a001/pdf.py", line 7, in split_pdf pdf_src = PdfFileReader(filename) File "E:\project_luffy\luffy\lib\site-packages\PyPDF2\pdf.py", line 1084, in __init__ self.read(stream) File "E:\project_luffy\luffy\lib\site-packages\PyPDF2\pdf.py", line 1901, in read raise utils.PdfReadError("Could not find xref table at specified location") PyPDF2.utils.PdfReadError: Could not find xref table at specified location
還沒有找到好的解決問題的辦法,但是我在操作過程中 換了一個新的pdf文件 就成功了 猜測是你的pdf文件出了問題
遇見的問題二:
在解決了上面的問題之后,程序可以正常的使用 但是還會出一個問題
PdfReadWarning: Xref table not zero-indexed. ID numbers for objects will be corrected. [pdf.py:1736]
雖然不影響,但是體驗不好啊 ,繼續解決吧
import sys if not sys.warnoptions: import warnings warnings.simplefilter("ignore")
上面代碼要加在最上面