En este artículo, vamos a ver cómo podemos automatizar el archivo pdf con la ayuda de módulo PyPDF2 en Python?
módulos utilizados:
En esta secuencia de comandos, utilizaremos módulo PyPDF2 que nos proporcionará varias funciones tales como para extraer los datos y leer el archivo PDF y dividir el archivo y escribir un nuevo archivo.
Descargar PyPDF2:
- general Vía: pip instalar PyPDF2
- Usuarios PyCharm: Ir al intérprete de Python proyecto e instalarlo desde allí.
Varios función proporcionada por PyPDF2:
- PyPDF2.PdfFileReader () : Esta función lee nuestra pdf y class nosotros un valor de datos que vamos a almacenar en una variable (toma de Let como Pdf_Data ).
- Pdf_Data.isEncrypted : Esta función nos ayudará a comprobar si el archivo está cifrado pdf.
- Pdf_Data.decrypt ( “& lt; contraseña & gt;”) : Esta función nos ayudará a descifrar el archivo PDF y en el interior de esta función, tenemos que poner la contraseña y nuestro archivo pdf conseguirán descifrado.
- Pdf_Data.numPages : Esta función nos class el número de páginas contienen nuestra pdf.
- Pdf_Data.getPage (0) : Esta función nos return los datos de la primera página, aquí 0 parece ser la primera página y de 1 a ser la segunda página, las cosas van a ir como la indexación en Python.
- Pdf_Writer = PyPDF2.PdfFileWriter () : Esta función creará una variable que nos ayudará a crear un nuevo archivo PDF.
- Pdf_Writer.addPage (& lt; & gt Los Datos página;) : Esta función se sumará la página PDF en el archivo PDF recién creado.
Nota: El texto La extracción puede hacerse sólo con los archivos PDF que tienen texto .
código Python para leer el archivo y extraer el texto
# import the modules
import PyPDF2
# open the file and read the content
# open the file
Pdf_Open=open("/home/abhinav/Downloads/CS_Defination-converted.pdf","rb")
# read the file and store the content
Pdf_Data=PyPDF2.PdfFileReader(Pdf_Open)
# get the number of pages
print(Pdf_Data.numPages)
# Lets extract the data for the first page
# we will use getPage command to get the page
# using 0 for 1st page
First_page=Pdf_Data.getPage(0)
# printing the text
print(First_page.extractText())
Salida:
Este es el texto extraído del pdf que hemos dado en la entrada. De esta manera, podemos extraer el texto del pdf.
Ahora vamos a crear un archivo PDF y añadiremos el inicio y la última página del pdf por encima de la usada en ese archivo.
vamos a ver el código,
# import the modules
import PyPDF2
# open the file and read the content
# open the file
Pdf_Open=open("/home/abhinav/Downloads/Abhinav_Gangrade.pdf","rb")
# read the file and store the content
Pdf_Data=PyPDF2.PdfFileReader(Pdf_Open)
# get the number of pages
print(Pdf_Data.numPages)
# Create a pdf writer
pdf_writer=PyPDF2.PdfFileWriter()
# we will take the first page of the above pdf
first_page=Pdf_Data.getPage(0)
# we will take the last page of the above pdf
# as the last page will be Total number of pages-1
last_page=Pdf_Data.getPage((Pdf_Data.numPages)-1)
# adding page to the new pdf
pdf_writer.addPage(first_page)
pdf_writer.addPage(last_page)
# create a blank file
New_pdf=open("/home/abhinav/Downloads/Hello.pdf","wb")
# add the content to the blank file
pdf_writer.write(New_pdf)
# Now close the file
en el código anterior, podemos crear un nuevo PDF con la ayuda de un PDF existente, y después de eso, hemos tomado la primera y la última página del PDF existente y combinar ellos y lo escribieron en el nuevo PDF. De esta manera, podemos crear un pdf con la ayuda de los archivos PDF existentes.