php如何利用python實現對pdf檔案的操作(讀寫、合并分割)

來源:互聯網
上載者:User

標籤:PHP實現pdf檔案截取   PHP調用python指令碼   

php如何利用python實現對pdf檔案的操作

需求:在PHP裡實現了把8.pdf的前4頁pdf檔案截取出來產生新的pdf檔案。

詳細步驟如下:

1. 安裝python第三方庫PyPDF2

前提:python必須是3.x版本以上,必要時需要升級pip3,命令如下:pip3 install --upgrade pip
PyPDF 自 2010年 12月開始就不在更新了,PyPDF2 接棒 PyPDF, 在此使用PyPDF2。

安裝命令:pip install PyPDF2

2、編寫python指令碼:mypdf.py
from PyPDF2 import PdfFileReader, PdfFileWriterimport sysdef 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檔案截取出來。

3、在PHP裡調用python指令碼實現。
<?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檔案的操作。本人親自開發可用,有問題可留言,抽空予以解答。

php如何利用python實現對pdf檔案的操作(讀寫、合并分割)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.