GEMINI LABJP
NANOLITE — Nano Banana 2 Lite is here: Google's fastest and most cost-efficient Gemini Image model, made for running lightweight image generation cheaplyOMNIFLASH — Gemini Omni Flash is in public preview, a natively multimodal model that lets enterprises and developers build custom, dynamic video workflowsAGENTS — Managed Agents expand with background: true for async server-side runs and polling, remote MCP server integration, and refreshing credentials across interactionsMEMORY — The Memory Bank IngestEvents API is generally available, decoupling event ingestion from memory generation so you can stream content continuouslyTHROUGHPUT — Provisioned Throughput now lets you submit up to seven pending orders for the same model and regionDEPRECATE — Image generation models shut down on August 17, and the Grok 4.1 family on the Gemini Enterprise Agent Platform on August 20NANOLITE — Nano Banana 2 Lite is here: Google's fastest and most cost-efficient Gemini Image model, made for running lightweight image generation cheaplyOMNIFLASH — Gemini Omni Flash is in public preview, a natively multimodal model that lets enterprises and developers build custom, dynamic video workflowsAGENTS — Managed Agents expand with background: true for async server-side runs and polling, remote MCP server integration, and refreshing credentials across interactionsMEMORY — The Memory Bank IngestEvents API is generally available, decoupling event ingestion from memory generation so you can stream content continuouslyTHROUGHPUT — Provisioned Throughput now lets you submit up to seven pending orders for the same model and regionDEPRECATE — Image generation models shut down on August 17, and the Grok 4.1 family on the Gemini Enterprise Agent Platform on August 20
Articles/API / SDK
API / SDK/2026-03-27Beginner

How to Analyze and Summarize PDFs with Gemini API — A Practical Python Guide

Learn how to extract text, summarize, and run Q&A on PDF files using the Gemini API in Python. A step-by-step guide covering File API uploads, multimodal processing, and structured data extraction.

gemini-api277pdf6python104multimodal44document-ai2file-api6summarization4

Why PDF Analysis Just Got a Whole Lot Easier

Working with PDFs is a universal pain point. Whether you're reviewing contracts, summarizing research papers, or extracting data from invoices, manual processing eats up valuable time.

With Gemini API's multimodal capabilities, you can feed PDF files directly as input and perform text extraction, summarization, and Q&A with just a few lines of Python code. There's no need for separate OCR tools or third-party libraries. Gemini understands both the text layer and the visual layout of each page, delivering context-aware responses that are remarkably accurate.

The full workflow follows — uploading PDFs via the File API, then summarization, structured data extraction, and interactive Q&A — each step paired with code you can run as-is.

Prerequisites and Setup

What You'll Need

  • Python 3.10 or later installed on your machine
  • A Google AI Studio API key (available for free at aistudio.google.com)
  • A PDF file to analyze (any PDF will work for following along)

Installing the SDK

pip install google-genai

Configuring Your API Key

import os
from google import genai
 
# Load API key from environment variable (recommended)
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
 
# Verify the connection
print("Gemini API client initialized successfully")

Set the environment variable in your terminal before running the script:

export GEMINI_API_KEY="YOUR_API_KEY"

For a detailed walkthrough on getting your API key and initial setup, check out the [Gemini API Quickstart Guide]((/articles/gemini-api/gemini-api-quickstart).

Uploading a PDF to the Gemini API

To work with PDFs in the Gemini API, you first need to upload the file using the File API. The uploaded file is temporarily stored on Google's servers and can then be referenced in your prompts.

import os
from google import genai
 
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
 
# Upload the PDF file
pdf_file = client.files.upload(
    file="report.pdf",  # Local path to your PDF
    config={"display_name": "Analysis Report"}
)
 
print(f"Upload complete: {pdf_file.name}")
print(f"URI: {pdf_file.uri}")
print(f"State: {pdf_file.state}")
 
# Expected output:
# Upload complete: files/xxxxxxxxxxxx
# URI: https://generativelanguage.googleapis.com/v1beta/files/xxxxxxxxxxxx
# State: State.ACTIVE

Uploaded files are retained on the server for up to 48 hours before being automatically deleted. If you need to process the same file again after that window, simply re-upload it.

Handling Large PDFs

The Gemini API supports file uploads up to 2GB. However, keep in mind that larger PDFs consume more tokens. Here are some practical guidelines:

  • Under 100 pages: Upload as-is with no issues
  • 100–300 pages: Use prompts that specify the target page range for better results
  • Over 300 pages: Consider splitting the PDF into smaller chunks before processing

For a deeper dive into the File API's capabilities, see the [File API Complete Guide]((/articles/gemini-api/files-api-guide).

Summarizing a PDF

Let's start with the most common use case: generating a summary of a PDF document.

import os
from google import genai
 
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
 
# Upload the PDF
pdf_file = client.files.upload(file="report.pdf")
 
# Generate a summary
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents=[
        pdf_file,  # The uploaded PDF
        "Please summarize this PDF in the following format:\n"
        "1. Overview (3 lines max)\n"
        "2. Key takeaways (up to 5 bullet points)\n"
        "3. Conclusion"
    ]
)
 
print(response.text)
 
# Expected output:
# ## Overview
# This report analyzes AI market trends for 2026...
#
# ## Key Takeaways
# - The generative AI market grew 45% year-over-year...
# - Multimodal AI adoption is accelerating rapidly...
# ...

By specifying an output format in your prompt, you get consistently structured summaries every time. This is especially useful for repetitive workflows — save your prompt as a template and reuse it across different documents.

Choosing the Right Model

Different Gemini models suit different PDF analysis needs:

  • Gemini 2.5 Flash: Fast and cost-effective. Ideal for everyday summarization and data extraction tasks
  • Gemini 2.5 Pro: Better suited for complex analysis and longer PDFs. Choose this for tasks like comparing contract clauses where precision matters
  • Gemini 3.1 Pro: The latest model with significantly enhanced reasoning. Scoring 77.1% on ARC-AGI-2, it excels at complex document analysis

Extracting Structured Data from PDFs

Beyond summarization, Gemini can extract specific data from PDFs and return it in a structured format. This is particularly powerful for invoices, reports, and forms.

import os
import json
from google import genai
 
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
 
pdf_file = client.files.upload(file="invoice.pdf")
 
# Extract data as structured JSON
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents=[
        pdf_file,
        "Extract the following information from this invoice as JSON:\n"
        "- company_name: the issuing company\n"
        "- invoice_number: the invoice number\n"
        "- date: the issue date\n"
        "- total_amount: the total amount\n"
        "- items: an array of line items (name, quantity, unit_price, subtotal)\n"
        "Return only valid JSON."
    ],
    config={
        "response_mime_type": "application/json"
    }
)
 
# Parse the JSON response
data = json.loads(response.text)
print(json.dumps(data, indent=2))
 
# Expected output:
# {
#   "company_name": "Acme Corporation",
#   "invoice_number": "INV-2026-0342",
#   "date": "2026-03-15",
#   "total_amount": "$1,250.00",
#   "items": [
#     {
#       "name": "Consulting Services",
#       "quantity": 1,
#       "unit_price": "$1,000.00",
#       "subtotal": "$1,000.00"
#     }
#   ]
# }

Setting response_mime_type to application/json guarantees that Gemini returns valid JSON. This dramatically reduces parsing errors in production pipelines and is one of the most practical techniques for real-world applications.

Running Q&A Against a PDF

You can also ask natural language questions about a PDF's content and get direct answers. This is incredibly useful for quickly finding information in manuals, specifications, or lengthy reports.

import os
from google import genai
 
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
 
pdf_file = client.files.upload(file="user_manual.pdf")
 
# Ask multiple questions
questions = [
    "What operating systems does this manual say are supported?",
    "Briefly describe the initial setup steps.",
    "What is the most common troubleshooting issue mentioned?"
]
 
for q in questions:
    response = client.models.generate_content(
        model="gemini-2.5-flash",
        contents=[pdf_file, q]
    )
    print(f"Q: {q}")
    print(f"A: {response.text}\n")
 
# Expected output:
# Q: What operating systems does this manual say are supported?
# A: The supported operating systems listed in this manual are
#    Windows 11, macOS 14 or later, and Ubuntu 22.04 LTS.
#
# Q: Briefly describe the initial setup steps.
# A: 1. Download the application...

Once uploaded, the same PDF can be referenced across multiple requests in the same session, making it efficient to run a series of questions without re-uploading.

Batch Processing Multiple PDFs

In real-world scenarios, you'll often need to process multiple PDFs at once. Here's a script that summarizes all PDFs in a given directory:

import os
import glob
from google import genai
 
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
 
# Batch upload and process all PDFs in a folder
pdf_dir = "./documents/"
pdf_paths = glob.glob(os.path.join(pdf_dir, "*.pdf"))
 
results = []
 
for path in pdf_paths:
    filename = os.path.basename(path)
    print(f"Processing: {filename}")
 
    # Upload
    pdf_file = client.files.upload(file=path)
 
    # Generate summary
    response = client.models.generate_content(
        model="gemini-2.5-flash",
        contents=[
            pdf_file,
            "Summarize this PDF in 100 words or fewer."
        ]
    )
 
    results.append({
        "filename": filename,
        "summary": response.text
    })
    print(f"  -> {response.text[:80]}...\n")
 
# Display results
print("=" * 60)
print(f"Processed {len(results)} PDF files in total")
for r in results:
    print(f"\n📄 {r['filename']}")
    print(f"   {r['summary']}")

When processing a large number of files, keep in mind the API rate limits. There's a cap on requests per minute, so adding time.sleep() between requests can help avoid throttling. For truly large-scale batch processing, consider using the [Gemini Batch Processing API]((/articles/gemini-api/gemini-batch-processing-api) for up to 50% cost savings.

Common Errors and Troubleshooting

File Size Errors

While the File API supports uploads up to 2GB, there's also a token limit for each request. PDFs with a very high page count may trigger a "token limit exceeded" error. If this happens, split the PDF into smaller sections or narrow your prompt to target specific pages.

Scanned PDFs (Image-Only)

Gemini handles scanned PDFs without a text layer by analyzing pages as images through its multimodal capabilities. However, accuracy may decrease with low-resolution scans or handwritten text. Pre-processing scanned images to increase resolution can significantly improve results.

"File Not Found" Errors

Uploaded files are automatically deleted after 48 hours. For long-running batch jobs, design your pipeline to re-upload files just before processing to avoid stale file references.

Summary

Analyzing PDFs with the Gemini API is remarkably straightforward — upload a file via the File API, send a prompt, and you're done. No OCR libraries or complex preprocessing required. From text extraction and summarization to structured data extraction and interactive Q&A, the API handles a wide range of document processing tasks with ease.

Start by experimenting with a PDF you already have on hand. You'll be surprised at what a few lines of code can accomplish. For those looking to explore more advanced techniques — high-precision table extraction, automated contract review, and cross-document analysis — the [Gemini Multimodal Document Processing Advanced Guide]((/articles/gemini-api/gemini-document-processing-advanced) is an excellent next step.

If you'd like to deepen your understanding of the topics covered in this article,

Share

Thank You for Reading

Gemini Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • Copy-paste ready implementation code
  • New advanced guides published daily
  • $5/mo or $10 for lifetime access
View Membership →

If you found this article helpful, a small tip ($1.50) would mean a lot to us. Your support helps keep this site ad-free and covers server and hosting costs.

Related Articles

API / SDK2026-07-12
When a Whole Chapter Vanished From My Long-PDF Summary — Field Notes on Auditing Coverage
Chapter-wise summarize-then-merge works well on long PDFs, but a lost extraction or a merge step can drop an entire chapter while the pipeline finishes without a single error. This walks through catching those silent drops with one number—coverage—and re-running only the chapters that fell out.
API / SDK2026-06-28
Mixing Text and Images in One File Search Skewed My Results Toward Images — Rebalancing by Modality After Retrieval
When you put text and images in a single File Search store with gemini-embedding-2, results can quietly skew toward one modality. Here is how to measure that skew and even it out after retrieval, using per-modality normalization and quota-based merging — with working code.
API / SDK2026-05-31
Why Gemini API Throws 'Unsupported MIME type' and How to Fix It
The 'Unsupported MIME type' error from the Gemini API has three distinct causes: a misspelled MIME string, an octet-stream upload, and a genuinely unsupported format. Here is how to tell them apart with code that actually works.
📚RECOMMENDED BOOKS
Build a Large Language Model (From Scratch)
Sebastian Raschka
LLM Dev
Prompt Engineering for LLMs
Berryman & Ziegler
Prompting
AI Engineering
Chip Huyen
AI Eng
* Contains affiliate links
See all →