How PHP uses Python for PDF file operation
Requirement: In PHP, the first 4 pages of the 8.pdf PDF file are captured to generate a new PDF file.
The detailed steps are as follows:
1. Install Python third-party library PyPDF2
Prerequisite: Python must be above 3.x version, need to upgrade PIP3, if necessary, the command is as follows: PIP3 install--upgrade pip
Pypdf since December 2010 has not been updated, PyPDF2 Pypdf, where the use of PyPDF2.
Install command: Pip install PyPDF2
2. Writing Python script: mypdf.py
from PyPDF2 import Pdffilereader, Pdffilewriterimport sysdef split_pdf (INFN, OUTFN): Pdf_output = Pdffilewri ter () Pdf_input = Pdffilereader (open (INFN, ' RB ')) # gets a PDF of how many pages Page_count = Pdf_input.getnumpages () print (PA Ge_count) # page of PDF page 1th to int (sys.argv[2]) page, output to a new file 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 ')) # get PDF Share how many pages Page_count = PD F_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] Outf n = '/bbs_pdf/outfn.pdf ' split_pdf (INFN, OUTFN)
The above script executes in Linux/usr/local/bin/python3/bbs_pdf/mypdf.py 8.pdf 4
The first 4 pages of the 8.pdf PDF file are captured.
3, in PHP call Python script implementation.
<?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>";}?>
The above steps enable the interception of PDF files using Python's third-party library in PHP. I personally develop the available, there are questions can leave a message, time to answer.
How PHP uses Python to manipulate PDF files (read-write, merge-split)