新聞中心
有時候我們只需要pdf中的幾頁,或許還想把這幾頁內(nèi)容整合成新的pdf,那該怎么做呢?

創(chuàng)新互聯(lián)建站-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價比市中網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式市中網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋市中地區(qū)。費(fèi)用合理售后完善,10余年實體公司更值得信賴。
準(zhǔn)備工作:
安裝擴(kuò)展庫PyPDF2,參考命令
pip install PyPDF2
代碼如下:
from PyPDF2 import PdfFileReader, PdfFileWriter def split_pdf(filename, result, start=0, end=None): """從filename中提取[start,end)之間的頁碼內(nèi)容保存為result""" # 打開原始 pdf 文件 pdf_src = PdfFileReader(filename) if end is None: # 獲取頁數(shù) end = pdf_src.getNumPages() with open(result, "wb") as fp: # 創(chuàng)建空白pdf文件 pdf = PdfFileWriter() # 提取頁面內(nèi)容,寫入空白文件 for num in range(start, end): pdf.addPage(pdf_src.getPage(num)) # 寫入結(jié)果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, insplit_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]
雖然不影響,但是體驗不好啊 ,繼續(xù)解決吧
import sys if not sys.warnoptions: import warnings warnings.simplefilter("ignore")
上面代碼要加在最上面
關(guān)于PyPDF2的內(nèi)容,昨天有詳細(xì)講解過,不會的小伙伴可以查看:進(jìn)階PDF,就用Python(PyPDF2模塊)
(推薦操作系統(tǒng):windows7系統(tǒng)、Python 3.9.1,DELL G3電腦。)
當(dāng)前文章:創(chuàng)新互聯(lián)Python教程:Python中用PyPDF2拆分pdf提取頁面
瀏覽路徑:http://m.fisionsoft.com.cn/article/cogeijh.html


咨詢
建站咨詢
