Exstraksi Tabel dari PDF ke CSV

Dapat kiriman file tabel data dalam bentuk PDF berpassword. Padahal kita mempunyai kebutuhan untuk mengambil data untuk dimasukkan ke Google Address Book,

Jika kita mendapatkan file demikian maka kita akan melakukan lankah berikut:

  1. Mendecrypt file pdf dengan password yang diberikan menggunakan PyPDF2
  2.  Melakukan scrapping tabel dan mengkonverinya ke csv

Silahkan …

# Decrypt password-protected PDF in Python.
# 
# Requirements:
# pip install PyPDF2
# pip install camelot-py[cv]

from PyPDF2 import PdfFileReader, PdfFileWriter
# import camelot
import camelot.io as camelot

def decrypt_pdf(input_path, output_path, password):
  with open(input_path, 'rb') as input_file, \
    open(output_path, 'wb') as output_file:
    reader = PdfFileReader(input_file)
    reader.decrypt(password)

    writer = PdfFileWriter()

    for i in range(reader.getNumPages()):
      writer.addPage(reader.getPage(i))

    writer.write(output_file)


# Decrypt PDF
decrypt_pdf('encrypt.pdf', 'decrypted.pdf', 'password')
file_path = "decrypted.pdf"
pdf_archive = camelot.read_pdf(file_path, pages="1", flavor="stream")

# Save to Excel
for page, pdf_table in enumerate(pdf_archive):             
    df = pdf_archive[page].df
    # check print(df)
    df.to_excel('decrypted.xlsx', index=False)
    

Menggunakan camelot memang simpel, tapi kadang hasilnya tidak perfect. Tapi lumayanlah hasilnya daripada ketik manual 🙂

Exstract Table di Pdf dengan Python Camelot

Berikut untuk ekstraksi data dari table pdf ke csv

1
2
3
4
5
6
import camelot
file_path = "durenan-malasan-8.pdf"
pdf_archive = camelot.read_pdf(file_path, pages="1", flavor="stream")
for page, pdf_table in enumerate(pdf_archive):           
    # print(pdf_archive[page].df)
    pdf_archive[page].to_csv('test.csv')

Untuk informasi lebih lanjut silahkan mengunuungi situsnya di dini.