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.pyfrom 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文件截取出来。
<?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文件的操作。本人亲自开发可用,有问题可留言,抽空予以解答。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。