🛡️ 500+ Free Excel, VBA, Outlook & Python Guides — Tested & Copy-Ready Explore 150+ VBA Macros →

Extract Data from Image & PDF using Gemini API in Python

Python - Extract Data from Image & PDF using Gemini API

Consider you have a folder with 50 scanned invoices. Some are PDF, some are photos taken from mobile. You need the invoice number, date, vendor name & amount from each one in an Excel sheet.

Earlier, this needed an OCR software & lot of cleanup, because OCR gives the full text & you still have to find which number is the invoice amount. Gemini can read the image or PDF & understand it. So, we can just ask "What is the total amount in this invoice?" & get the answer directly.

In this page, you will get the Python code to send an image or PDF to Gemini, get the details as JSON & finally process a full folder of files into a CSV file.

Also Read: How to use Gemini API in Python - Send Prompt & Get Response

Prerequisites

  1. Python 3.9 or above installed in your computer.
  2. Gemini Python library. Install it with pip install -U google-genai
  3. A Gemini API key saved in GEMINI_API_KEY environment variable. Steps are here: How to Get Free Gemini API Key.

If you have not used Gemini from Python before, first try the basic code in the previous article. Once that works, this one is just a small addition.

Python Code to Send Image to Gemini API

Only difference from a normal text prompt is, the contents now has 2 items. First the image bytes, then the question about the image.

# Send an image to Gemini & ask a question about it
from google import genai
from google.genai import types

client = genai.Client()

# Gemini model to use. Change this when Google releases a newer model.
modelName = "gemini-3.8-flash"

# Read the image file as bytes
imagePath = "C:/Users/hp/Downloads/invoice.jpg"
with open(imagePath, "rb") as imageFile:
    imageBytes = imageFile.read()

response = client.models.generate_content(
    model=modelName,
    contents=[
        types.Part.from_bytes(data=imageBytes, mime_type="image/jpeg"),
        "Extract the invoice number, invoice date, vendor name & total amount from this image."
    ]
)

print(response.text)

The mime_type tells Gemini what type of file it is. Use "image/jpeg" for .jpg files, "image/png" for .png & "image/webp" for .webp files.

It is not only for invoices. You can ask anything about the image. "Describe this photo", "Read the text in this screenshot", "Convert this table image into CSV" etc., all work fine.

Send PDF File to Gemini

PDF works the same way. Just change the mime type to "application/pdf". Gemini reads all the pages, including scanned pages & tables.

from google import genai
from google.genai import types

client = genai.Client()

pdfPath = "C:/Users/hp/Documents/annual-report.pdf"
with open(pdfPath, "rb") as pdfFile:
    pdfBytes = pdfFile.read()

response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents=[
        types.Part.from_bytes(data=pdfBytes, mime_type="application/pdf"),
        "Summarize this document in 5 bullet points."
    ]
)

print(response.text)

Note: This method sends the file along with the request. The total request size has to be below 20 MB. For bigger files, upload the file first & then refer it in the prompt, as shown below. A PDF can be up to 50 MB or 1000 pages.

from google import genai

client = genai.Client()

# Upload the file to Gemini (stored for 48 hours)
uploadedFile = client.files.upload(file="C:/Users/hp/Documents/big-manual.pdf")

response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents=[uploadedFile, "List all the chapter names in this document."]
)

print(response.text)

Get the Details as JSON - Not as Paragraph

When we want to save the details in Excel or CSV, a paragraph answer is not useful. We need each value separately. For this, tell Gemini to reply in JSON using response_mime_type. Then the reply can be loaded directly with Python json module.

import json
from google import genai
from google.genai import types

client = genai.Client()

with open("C:/Users/hp/Downloads/invoice.jpg", "rb") as imageFile:
    imageBytes = imageFile.read()

prompt = """Read this invoice & return JSON with these keys:
invoice_number, invoice_date, vendor_name, total_amount.
Use empty string if a value is not found."""

response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents=[types.Part.from_bytes(data=imageBytes, mime_type="image/jpeg"), prompt],
    config=types.GenerateContentConfig(response_mime_type="application/json")
)

invoiceData = json.loads(response.text)
print("Invoice No : " + str(invoiceData.get("invoice_number")))
print("Amount     : " + str(invoiceData.get("total_amount")))

The reply will look something similar to this one.

{
  "invoice_number": "INV-2026-0457",
  "invoice_date": "14-11-2026",
  "vendor_name": "Sri Lakshmi Traders",
  "total_amount": "18,450.00"
}

Process All Images & PDFs in a Folder to CSV

Now lets put everything together. This code reads every image & PDF file from a folder, sends it to Gemini & writes the details as one row per file in a CSV file. You can open the CSV in Excel directly.

import os           # To list files in folder
import csv          # To write the output CSV file
import json         # To read Gemini JSON reply
import time         # To wait between API calls
import mimetypes    # To find file type from extension
from google import genai
from google.genai import types

client = genai.Client()
modelName = "gemini-3.8-flash"

folderPath = "C:/Users/hp/Documents/Invoices"
outputCsv = "C:/Users/hp/Documents/invoice_details.csv"
fieldNames = ["invoice_number", "invoice_date", "vendor_name", "total_amount"]

prompt = """Read this invoice & return JSON with these keys:
invoice_number, invoice_date, vendor_name, total_amount.
Use empty string if a value is not found."""

allowedTypes = ("application/pdf", "image/jpeg", "image/png", "image/webp")

with open(outputCsv, "w", newline="", encoding="utf-8") as csvFile:
    writer = csv.writer(csvFile)
    writer.writerow(["file_name"] + fieldNames)

    for fileName in os.listdir(folderPath):
        filePath = os.path.join(folderPath, fileName)
        mimeType, _ = mimetypes.guess_type(filePath)

        # Skip files that are not image or PDF
        if mimeType not in allowedTypes:
            continue

        with open(filePath, "rb") as inputFile:
            fileBytes = inputFile.read()

        try:
            response = client.models.generate_content(
                model=modelName,
                contents=[types.Part.from_bytes(data=fileBytes, mime_type=mimeType), prompt],
                config=types.GenerateContentConfig(response_mime_type="application/json")
            )
            data = json.loads(response.text)
            if isinstance(data, list):      # Sometimes reply comes as a list
                data = data[0] if data else {}
            writer.writerow([fileName] + [data.get(k, "") for k in fieldNames])
            print("Processed : " + fileName)
        except Exception as e:
            writer.writerow([fileName] + ["ERROR: " + str(e)] + [""] * (len(fieldNames) - 1))
            print("Failed    : " + fileName + " - " + str(e))

        # Small wait to stay within free tier rate limit
        time.sleep(3)

print("Completed. Output file : " + outputCsv)

If one file fails, the code writes the error in that row & moves to the next file. So, one bad file will not stop the whole process.

To know more about listing files & writing CSV in Python, refer these articles: List files in directory with extension & Python CSV read & write.

Things to Know

  • Always cross check amounts: Gemini is very good at reading invoices, but it can still make mistakes, especially with blurred photos or hand written numbers. For accounts work, verify the totals before using them.
  • Confidential documents: In free tier, Google can use the content you send to improve their products. Do not send salary slips, ID cards, bank statements etc., with a free key.
  • Image quality matters: Take mobile photos in good light & keep the document flat. A clear image gives much better results than a dark or tilted one.
  • Error 429: Too many requests. Increase the time.sleep value. Check the free tier rate limits for details.

The same code works for other documents too. Change the prompt & the field names for visiting cards, purchase orders, resumes or any form, & you have your own data entry tool.