環境
python == 3.10
PyPDF2 ==3.0.1
安裝
pip install PyPDF2
流程
- 將空白頁和內容頁讀取出來,看看內部結構有什么不同
- 以此為依據,遍歷整個PDF 文件,標記處有內容的頁面,寫入到另外一個PDF文件。
python 代碼
# 每一個頁都是一個字典對象,看第一層沒區別
# 參考文章中 第一層 keys 一樣, 但是 /Resources下結構有所不同,空白頁沒有"/XObject"鍵
# 我的第一層keys 不一樣, 但是 /Resources下結構一樣
# 另外 PyPDF2 版本不一樣,各個模塊有更新,自己看源碼進行更新,或者根據報錯提示進行更新from PyPDF2 import PdfReader, PdfWriterdef remove_pdf_blank_pages(path):pdfReader = PdfReader(open(path, 'rb'))writer = PdfWriter()pages = len(pdfReader.pages)# blank = pdfReader.pages[1]# full = pdfReader.pages[2]#print('*'*10)#print(blank.keys())# dict_keys(['/Type', '/Parent', '/Resources', '/MediaBox', '/Contents'])#print(full.keys())# dict_keys(['/Type', '/Parent', '/Resources', '/MediaBox', '/Annots', '/Tabs', '/StructParents', '/Contents'])#print(blank['/Resources'])#{'/Font': IndirectObject(600, 0, 139632281578944), '/XObject': {'/Im553': IndirectObject(553, 0, 139632281578944), '/Im7': IndirectObject(7, 0, 139632281578944)}, '/ProcSet': ['/PDF', '/Text', '/ImageC', '/ImageI', '/ImageB']}#print(full['/Resources'])#{'/Font': IndirectObject(600, 0, 139632281578944), '/XObject': {'/Im553': IndirectObject(553, 0, 139632281578944), '/Im7': IndirectObject(7, 0, 139632281578944)}, '/ProcSet': ['/PDF', '/Text', '/ImageC', '/ImageI', '/ImageB']}#print('*' * 10)for i in range(pages):page = pdfReader.pages[i]# if "/XObject" in page["/Resources"].keys() or "/Font" in page["/Resources"].keys():# writer.add_page(page)if "/StructParents" in page.keys() or "/Tabs" in page.keys() or "/Annots" in page.keys():writer.add_page(page)writer.write(open(path, 'wb'))
參考
使用Python批量刪除掃描PDF中的空白頁