การดึงข้อมูลจากฟอร์ม PDF โดยใช้ Python

บทความนี้แนะนำวิธีการ ดึงข้อมูลจากฟอร์ม PDF โดยใช้ Python โดยมีรายละเอียดทั้งหมดเกี่ยวกับการตั้งค่า IDE รายการขั้นตอน และโค้ดตัวอย่างสำหรับการเข้าถึงข้อมูลฟิลด์ฟอร์ม โค้ดตัวอย่างจะสร้าง PDF ทดสอบที่มีฟิลด์และค่า และดึงข้อมูลจากฟิลด์ทั้งหมด

ขั้นตอนในการดึงข้อมูลจากฟิลด์ฟอร์ม PDF โดยใช้ Python

  1. ตั้งค่าสภาพแวดล้อมสำหรับการใช้ Aspose.PDF สำหรับ Python ผ่าน .NET เพื่อดึงข้อมูลฟอร์ม
  2. สร้างหรือโหลดไฟล์ PDF เข้าไปในออบเจ็กต์ Document ที่มีฟิลด์ข้อมูลที่มีข้อมูล
  3. ดึงฟิลด์ทั้งหมดจากคุณสมบัติ form ของเอกสาร PDF ที่โหลด
  4. วนรอบฟิลด์ทั้งหมดและเข้าถึงแต่ละฟิลด์
  5. แสดงชื่อเต็มของฟิลด์และค่าของมัน

ขั้นตอนเหล่านี้อธิบายวิธี ดึงข้อมูลจาก PDF ที่สามารถกรอกได้โดยใช้ Python สร้างหรือโหลดไฟล์ PDF ที่มีฟิลด์และค่า และเข้าถึงคอลเลกชันของฟิลด์จากคุณสมบัติ Form ในไฟล์ PDF วนรอบฟิลด์ทั้งหมดและเข้าถึงชื่อเต็มและค่าสำหรับการประมวลผล

โค้ดสำหรับการดึงฟิลด์ฟอร์มจาก PDF โดยใช้ Python

import aspose.pdf as pdf
from aspose.pdf import Document, License, Rectangle
from aspose.pdf.forms import TextBoxField
def main():
# Load Aspose PDF license
license = License()
license.set_license("license.lic")
# Generate PDF with input fields
create_pdf_with_fields()
# Open and process the generated PDF file
pdf_document = Document("UserForm.pdf")
# Retrieve and display form fields
form_fields = pdf_document.form.fields
for form_field in form_fields:
print("Field Name:", form_field.full_name)
print("Field Content:", form_field.value)
def create_pdf_with_fields():
# Instantiate new PDF document
pdf_file = Document()
for page_index in range(1, 4): # 3 pages
new_page = pdf_file.pages.add()
for field_index in range(1, 5): # 4 fields per page
# Define a text input field
input_field = TextBoxField(new_page, Rectangle(120, field_index * 90, 320,(field_index + 1) * 90,True))
input_field.partial_name = f"inputField_{page_index}_{field_index}"
input_field.value = f"Data Entry {page_index}-{field_index}"
# Attach field to the document form
pdf_file.form.add(input_field, page_index)
# Save document to disk
pdf_file.save("UserForm.pdf")
main()

โค้ดนี้ได้แสดงวิธี ดึงข้อมูลจากฟอร์ม PDF เราใช้คอลเลกชัน Document.form.fields ซึ่งมีฟิลด์ทั้งหมดใน PDF คุณสามารถกรองฟิลด์จากหน้าที่เจาะจงโดยใช้ page_index ในออบเจ็กต์ Field ที่เข้าถึงจากคอลเลกชัน

บทความนี้สอนเรากระบวนการอ่านข้อมูลฟอร์ม PDF หากคุณต้องการทำให้ไฟล์ PDF แบนราบ ดูบทความเกี่ยวกับ วิธีทำให้ PDF แบนราบใน Python

 ไทย