需求:在PHP裏實現了把8.pdf的前4頁pdf文件截取出來生成新的pdf文件。php
詳細步驟以下:python
前提:python必須是3.x版本以上,必要時須要升級pip3,命令以下:pip3 install --upgrade pip
PyPDF 自 2010年 12月開始就不在更新了,PyPDF2 接棒 PyPDF, 在此使用PyPDF2。linux
安裝命令:pip install PyPDF2shell
from PyPDF2 import PdfFileReader, PdfFileWriter import sys def split_pdf(infn, outfn): pdf_output = PdfFileWriter() pdf_input = PdfFileReader(open(infn, 'rb')) # 獲取 pdf 共用多少頁 page_count = pdf_input.getNumPages() print(page_count) # 將 pdf 第1頁到int(sys.argv[2])頁的頁面,輸出到一個新的文件 for i in range(0, int(sys.argv[2])): pdf_output.addPage(pdf_input.getPage(i)) pdf_output.write(open(outfn, 'wb')) def merge_pdf(infnList, outfn): pdf_output = PdfFileWriter() for infn in infnList: pdf_input = PdfFileReader(open(infn, 'rb')) # 獲取 pdf 共用多少頁 page_count = pdf_input.getNumPages() print(page_count) for i in range(page_count): pdf_output.addPage(pdf_input.getPage(i)) pdf_output.write(open(outfn, 'wb')) if __name__ == '__main__': infn = '/bbs_pdf/'+ sys.argv[1] outfn = '/bbs_pdf/outfn.pdf' split_pdf(infn, outfn)
以上腳本在linux裏執行/usr/local/bin/python3 /bbs_pdf/mypdf.py 8.pdf 4
實現了把8.pdf的前4頁pdf文件截取出來。ide
<?php $output = shell_exec('/usr/local/bin/python3 /bbs_pdf/mypdf.py 8.pdf 4'); echo 1; $array = explode(',', $output); foreach ($array as $value) { #echo "\n"; echo $value; echo "<br>"; } ?>
經過以上步驟就實現了在PHP裏藉助python第三方庫實現截取pdf文件的操做。本人親自開發可用,有問題可留言,抽空予以解答。code