2016-09-19 587 views
2

我有一些.pdf文件超過500頁,但我只需要在每個文件中的幾頁。有必要保存文檔的標題頁面。我確切地知道程序應該刪除的頁面的數量。如何使用安裝在MS Visual Studio上的Python 2.7環境來實現它?如何使用Python從pdf文件中刪除頁面?

回答

7

嘗試使用PyPDF2。一些示例代碼(改編自here)。

from PyPDF2 import PdfFileWriter, PdfFileReader 
pages_to_keep = [1, 2, 10] # page numbering starts from 0 
infile = PdfFileReader('source.pdf', 'rb') 
output = PdfFileWriter() 

for i in range(infile.getNumPages()): 
    if i in pages_to_keep: 
     p = infile.getPage(i) 
     output.addPage(p) 

with open('newfile.pdf', 'wb') as f: 
    output.write(f) 
+0

此代碼可以工作! – Alexander