Guide · Amazon Bedrock · Document Processing

Bedrock Data Automation Document Processing — PDF, DOCX, Tables, and Forms for MCP Servers

Amazon Bedrock Data Automation supports seven document formats — but image-based PDFs (scanned documents) are processed differently from text PDFs, XLSX multi-sheet workbooks require extra output traversal, and the same-region S3 constraint silently produces ClientError rather than a helpful error message. Understanding which standard output components BDA generates for each document type, and how to navigate the output JSON to reach tables and form fields, is what separates a correct document processing MCP tool from one that works on demos but fails on real-world documents. For the BDA async invocation pattern see BDA overview; for custom field extraction with blueprints see BDA blueprints; for detailed output JSON structure and parsing see BDA output parsing.

TL;DR

BDA supports PDF, DOCX, XLSX, CSV, HTML, TXT, and XLS as document types. Standard output includes full text, Markdown representation, tables, key-value form fields, figures, and a summary. Image-based PDFs (no selectable text) are processed via OCR — quality depends on scan resolution. XLSX multi-sheet workbooks produce one page entry per sheet. All input and output buckets must be in the same AWS region as the BDA runtime endpoint.

Supported document types and limits

BDA processes seven document formats. Each has different extraction characteristics and constraints:

Format Extension Max size Notes
PDF .pdf 150 MB Text PDFs and image-based (scanned) PDFs both supported; quality differs
Word document .docx 50 MB Embedded images, tables, and tracked changes all processed
Excel workbook .xlsx 50 MB Multi-sheet workbooks produce one page output per sheet
Legacy Excel .xls 50 MB Older binary format; prefer .xlsx for newer workbooks
CSV .csv 10 MB Tabular data; output structured as a single-table document
HTML .html 10 MB Rendered HTML structure; embedded <table> elements extracted as tables
Plain text .txt 10 MB UTF-8 encoded; treated as a single-page document

BDA determines the document type from the content of the file, not just the file extension. A PDF saved with a .txt extension will be processed as a PDF. However, naming files with the correct extension avoids edge cases in the BDA content-detection step.

Page limits

For PDF documents, BDA processes up to 100 pages per job. Documents longer than 100 pages require chunking — split the PDF into 100-page segments and submit separate invocations, then merge the output JSON from each segment. The Bedrock batch inference pattern works well here: submit all chunks concurrently and process completions through an SQS queue.

For XLSX workbooks, the page limit is per sheet. A workbook with 50 sheets of 2 pages each processes all 50 sheets. A workbook with a single sheet of 101+ rows may hit the per-page row limit for tables — very large tables are truncated at the page boundary and continued on the next virtual page.

Staging documents in S3

BDA requires the input S3 URI to be in the same AWS region as the runtime endpoint. If your application stores documents in us-west-2 but your BDA runtime is in us-east-1, every job will fail with a ClientError citing an S3 access or geography error. The error message is not always obvious about the root cause.

The safest approach: use a staging bucket in the same region as your BDA runtime deployment, and copy files there before submitting a BDA job.

import { S3Client, CopyObjectCommand, HeadObjectCommand } from '@aws-sdk/client-s3';

const BDA_REGION = process.env.AWS_REGION ?? 'us-east-1';
const STAGING_BUCKET = process.env.BDA_STAGING_BUCKET!; // in BDA_REGION

async function stageDocumentForBda(
  sourceS3Uri: string,
  destinationKey: string,
): Promise<string> {
  // Parse source URI
  const source = new URL(sourceS3Uri.replace('s3://', 'https://'));
  const sourceBucket = source.hostname;
  const sourceKey = source.pathname.replace(/^\//, '');

  // Determine source bucket region
  const sourceBucketRegion = await getBucketRegion(sourceBucket);

  if (sourceBucketRegion === BDA_REGION) {
    // Already in the right region — use directly
    return sourceS3Uri;
  }

  // Different region — copy to staging bucket
  const sourceS3 = new S3Client({ region: sourceBucketRegion });
  await sourceS3.send(new CopyObjectCommand({
    Bucket: STAGING_BUCKET,
    Key: destinationKey,
    CopySource: `${sourceBucket}/${sourceKey}`,
  }));

  return `s3://${STAGING_BUCKET}/${destinationKey}`;
}

async function getBucketRegion(bucket: string): Promise<string> {
  // HeadBucket with LocationConstraint returns bucket region
  const s3 = new S3Client({ region: 'us-east-1' });
  try {
    const response = await s3.send(new HeadObjectCommand({ Bucket: bucket, Key: '_' }));
    // The response header x-amz-bucket-region reveals the actual region
    // For SDK v3, this is accessible via the middleware response headers
    return 'us-east-1'; // simplification — use custom middleware to read header
  } catch {
    return 'us-east-1'; // fallback
  }
}

S3 object naming considerations

BDA uses the S3 object key to determine the filename for display in output metadata. Keys with special characters (spaces, Unicode, URL-encoded sequences) are handled but can complicate downstream parsing of the output manifest. Use sanitized keys: replace spaces with hyphens, limit to alphanumeric characters, hyphens, underscores, and forward slashes.

function sanitizeS3Key(filename: string, prefix: string): string {
  const safe = filename
    .replace(/[^a-zA-Z0-9._-]/g, '-')  // replace special chars with hyphen
    .replace(/-+/g, '-')               // collapse consecutive hyphens
    .toLowerCase();
  return `${prefix}/${Date.now()}-${safe}`;
}

Standard output components

When you invoke BDA without a custom blueprint (or with a blueprint that does not suppress standard output), BDA generates a structured output JSON for each document with the following components:

// Standard output JSON top-level shape (abbreviated)
// Full output fetched from S3 after GetDataAutomationStatusCommand returns "Success"
{
  "metadata": {
    "content_type": "application/pdf",
    "document_class": {
      "type": "INVOICE"           // BDA's document type classification
    },
    "total_pages": 3
  },
  "document": {
    "statistics": {
      "pages": 3,
      "tables": 2,
      "figures": 0,
      "key_value_pairs": 8
    },
    "representation": {
      "text": "INVOICE\nInvoice Number: INV-2024-001\n...",
      "markdown": "# INVOICE\n\n**Invoice Number:** INV-2024-001\n..."
    },
    "summary": "An invoice from Acme Supplies to TechCorp for $4,250.00 dated January 15, 2024...",
    "pages": [ /* per-page data */ ],
    "tables": [ /* all tables across all pages */ ],
    "key_value_pairs": [ /* form fields */ ],
    "figures": [ /* figure descriptions */ ]
  }
}

Extracting tables

Tables in the BDA output are structured with a header row and data rows. Each row is an array of cell values. The title field (if extracted) gives the table caption or the nearest header above the table in the document.

interface BdaTable {
  title?: string;
  headers: string[];
  rows: Array<Array<string | null>>;
  page_index?: number;  // 0-based page number where table appears
  footnotes?: string[];
}

function extractTables(documentOutput: DocumentOutput): BdaTable[] {
  const tables: BdaTable[] = [];

  for (const table of documentOutput.document?.tables ?? []) {
    if (!table.cells) continue;

    // BDA tables use a cells array with row/column indices
    // Find the number of rows and columns
    const maxRow = Math.max(...table.cells.map((c: TableCell) => c.row_index ?? 0));
    const maxCol = Math.max(...table.cells.map((c: TableCell) => c.column_index ?? 0));

    // Build a 2D array — null for missing cells
    const grid: Array<Array<string | null>> = Array.from(
      { length: maxRow + 1 },
      () => Array(maxCol + 1).fill(null)
    );
    for (const cell of table.cells) {
      grid[cell.row_index][cell.column_index] = cell.content ?? null;
    }

    const headers = grid[0]?.map(h => h ?? '') ?? [];
    const rows = grid.slice(1);

    tables.push({
      title: table.title,
      headers,
      rows,
      page_index: table.page_index,
    });
  }

  return tables;
}

// Example: convert BDA table to plain objects keyed by header names
function tableToObjects(table: BdaTable): Array<Record<string, string | null>> {
  return table.rows.map(row =>
    Object.fromEntries(table.headers.map((header, i) => [header, row[i] ?? null]))
  );
}

// Usage for an invoice line items table:
// tableToObjects(tables[0]) might return:
// [
//   { "Description": "Consulting services", "Qty": "10", "Unit Price": "$150.00", "Total": "$1,500.00" },
//   { "Description": "Software license", "Qty": "1", "Unit Price": "$500.00", "Total": "$500.00" },
// ]

Extracting key-value pairs (forms)

BDA identifies field-label patterns throughout the document and extracts them as key-value pairs. This covers explicit form fields ("Name: John Smith"), labeled data in invoices ("Invoice Date: 2024-01-15"), and section headers followed by content ("Payment Terms: Net 30"). The extraction uses semantic understanding — "Due Date" and "Payment Due" are both recognized as the same concept and normalized in the output.

interface BdaKeyValuePair {
  key: {
    content: string;    // e.g. "Invoice Date"
    page_index?: number;
    bounding_box?: BoundingBox;
  };
  value: {
    content: string;    // e.g. "January 15, 2024"
    page_index?: number;
    bounding_box?: BoundingBox;
  };
  confidence?: number;  // 0.0–1.0
}

// Build a flat key-value map from BDA output
function extractFormFields(
  documentOutput: DocumentOutput,
  minConfidence = 0.7,
): Record<string, string> {
  const fields: Record<string, string> = {};

  for (const kvp of documentOutput.document?.key_value_pairs ?? []) {
    const confidence = kvp.confidence ?? 1.0;
    if (confidence < minConfidence) continue;

    const key = kvp.key?.content?.trim();
    const value = kvp.value?.content?.trim();

    if (key && value) {
      // Normalize key: lowercase, replace whitespace with underscore
      const normalizedKey = key.toLowerCase().replace(/\s+/g, '_').replace(/[^a-z0-9_]/g, '');
      fields[normalizedKey] = value;
    }
  }

  return fields;
}

// Example output for an invoice:
// {
//   "invoice_number": "INV-2024-001",
//   "invoice_date": "January 15, 2024",
//   "due_date": "February 14, 2024",
//   "total_amount": "$4,250.00",
//   "payment_terms": "Net 30",
//   "bill_to": "TechCorp Inc."
// }

Key-value pair extraction is probabilistic — BDA assigns a confidence score to each pair. Low-confidence pairs often indicate ambiguous layout (a value that runs over two lines, or a table cell mistaken for a form field). Filter by confidence >= 0.7 for production use, and fall back to custom blueprints for documents where field-level confidence is consistently low.

Handling image-based PDFs (scanned documents)

BDA handles image-based PDFs — scanned documents without selectable text — via built-in OCR. The output format is identical to text PDF output, but extraction quality is highly dependent on scan quality. BDA applies orientation correction, deskew, and contrast normalization before OCR, so moderately degraded scans usually produce usable text. Severely degraded scans (low DPI, heavy JPEG compression, handwritten fields mixed with printed text) will produce garbled text in some sections.

The metadata.document_class field in the output does not explicitly indicate whether OCR was applied. For MCP server tools that need to know whether a PDF was text-based or image-based, check whether the document.representation.text field contains typical OCR artifacts (broken hyphenation, single-character tokens for punctuation, non-ASCII characters).

function detectLikelyOcrArtifacts(text: string): boolean {
  // Heuristics that suggest OCR-processed content
  const indicators = [
    /\b[a-z]\b(?:\s+[a-z]\b){3,}/i,  // multiple single-character "words"
    /\d{1,2}[\-\/]\d{1,2}[\-\/]\d{2,4}\s*\n\s*\d/,  // date with line break mid-field
    /[|]{2,}/,                          // double pipes from table OCR
    /[^\x00-\x7F]{3,}/,                 // clusters of non-ASCII chars
  ];
  return indicators.some(pattern => pattern.test(text));
}

// Log OCR warning for downstream consumers
function processDocumentOutput(output: DocumentOutput): void {
  const text = output.document?.representation?.text ?? '';
  if (detectLikelyOcrArtifacts(text)) {
    console.warn('Document appears to have been OCR-processed — verify field accuracy');
  }
}

When to use Textract instead of BDA

For scanned document processing where OCR accuracy is the primary concern, consider Amazon Textract alongside BDA. Textract is specifically optimized for OCR and returns character-level confidence scores, bounding box coordinates, and geometric information (useful for forms with non-standard layouts). BDA is preferable when you need LLM-driven semantic understanding (summarization, generative field extraction, document classification) in addition to basic OCR. The two services are complementary: Textract for precision OCR, BDA for semantic understanding and structured field extraction. See Textract for MCP servers and Textract table extraction for the Textract approach.

XLSX multi-sheet workbook processing

When BDA processes an Excel workbook with multiple sheets, it generates one page entry per sheet in the output. Each sheet becomes a page with its own tables, text, and key-value pairs. The page_index field (0-based) maps to sheet index in the original workbook order.

function extractAllSheetsFromXlsx(output: DocumentOutput): Map<number, SheetData> {
  const sheets = new Map<number, SheetData>();

  for (const page of output.document?.pages ?? []) {
    const sheetIndex = page.page_index ?? 0;
    const tables = page.tables ?? [];
    const text = page.representation?.text ?? '';

    sheets.set(sheetIndex, {
      sheetIndex,
      text,
      tables: tables.map(t => ({
        title: t.title,
        headers: extractTableHeaders(t),
        rows: extractTableRows(t),
      })),
    });
  }

  return sheets;
}

// Extract the first column of Sheet 1 as a string array
function firstColumnValues(output: DocumentOutput): string[] {
  const firstPage = output.document?.pages?.[0];
  const firstTable = firstPage?.tables?.[0];
  if (!firstTable?.cells) return [];

  return firstTable.cells
    .filter((c: TableCell) => c.column_index === 0 && c.row_index > 0)  // skip header row
    .sort((a: TableCell, b: TableCell) => a.row_index - b.row_index)
    .map((c: TableCell) => c.content ?? '');
}

MCP tool: analyze_document

The following MCP tool wraps BDA document processing into a single agent-callable function. It submits the job, polls for completion, parses the output, and returns a structured summary with text, tables, and form fields. For production use, replace the inline polling with the two-tool (submit + poll) pattern described in the BDA overview.

import {
  BedrockDataAutomationRuntimeClient,
  InvokeDataAutomationAsyncCommand,
  GetDataAutomationStatusCommand,
} from '@aws-sdk/client-bedrock-data-automation-runtime';
import { S3Client, GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3';
import { randomUUID } from 'node:crypto';

const runtime = new BedrockDataAutomationRuntimeClient({ region: process.env.AWS_REGION! });
const s3 = new S3Client({ region: process.env.AWS_REGION! });

export interface DocumentAnalysisResult {
  documentType: string;
  pageCount: number;
  summary: string;
  fullText: string;
  markdownText: string;
  tables: Array<{ title?: string; rowCount: number; headers: string[] }>;
  formFields: Record<string, string>;
  warnings: string[];
}

export async function analyzeDocumentTool(params: {
  s3_uri: string;
  include_full_text?: boolean;
}): Promise<DocumentAnalysisResult> {
  const { s3_uri, include_full_text = false } = params;
  const jobId = randomUUID();
  const warnings: string[] = [];

  // 1. Stage document if needed (same-region requirement)
  const stagedUri = await ensureSameRegion(s3_uri, jobId);

  // 2. Submit BDA job
  const submitResp = await runtime.send(new InvokeDataAutomationAsyncCommand({
    inputConfiguration: { s3Uri: stagedUri },
    outputConfiguration: {
      s3Uri: `s3://${process.env.BDA_OUTPUT_BUCKET}/docs/${jobId}/`,
    },
    dataAutomationProfileArn: process.env.BDA_PROFILE_ARN!,
    clientToken: `analyze-doc-${jobId}`,
  }));

  const invocationArn = submitResp.invocationArn!;

  // 3. Poll for completion
  let outputUri: string | undefined;
  const start = Date.now();
  while (Date.now() - start < 240_000) {  // 4-minute timeout
    await new Promise(r => setTimeout(r, 6_000));  // 6s poll interval
    const status = await runtime.send(
      new GetDataAutomationStatusCommand({ invocationArn })
    );

    if (status.status === 'Success') {
      outputUri = status.outputConfiguration?.s3Uri;
      break;
    }
    if (status.status === 'ClientError' || status.status === 'ServiceError') {
      throw new Error(`BDA job failed (${status.status}): ${status.errorMessage}`);
    }
  }

  if (!outputUri) throw new Error('BDA job timed out');

  // 4. Fetch and parse output
  const output = await fetchDocumentOutput(outputUri);
  const doc = output.document ?? {};

  // 5. Build result
  const tables = (doc.tables ?? []).map((t: BdaTableRaw) => ({
    title: t.title,
    rowCount: (t.cells ?? []).filter((c: TableCell) => c.row_index > 0).length,
    headers: extractTableHeaders(t),
  }));

  const formFields: Record<string, string> = {};
  for (const kvp of doc.key_value_pairs ?? []) {
    if ((kvp.confidence ?? 1.0) >= 0.7 && kvp.key?.content && kvp.value?.content) {
      const key = kvp.key.content.toLowerCase().replace(/\s+/g, '_').replace(/[^a-z0-9_]/g, '');
      formFields[key] = kvp.value.content;
    }
  }

  return {
    documentType: output.metadata?.document_class?.type ?? 'UNKNOWN',
    pageCount: output.metadata?.total_pages ?? 0,
    summary: doc.summary ?? '',
    fullText: include_full_text ? (doc.representation?.text ?? '') : '',
    markdownText: include_full_text ? (doc.representation?.markdown ?? '') : '',
    tables,
    formFields,
    warnings,
  };
}

async function fetchDocumentOutput(outputS3Uri: string): Promise<BdaDocumentOutput> {
  const url = new URL(outputS3Uri.replace('s3://', 'https://'));
  const bucket = url.hostname;
  const prefix = url.pathname.replace(/^\//, '');

  const getResp = await s3.send(new GetObjectCommand({
    Bucket: bucket,
    Key: `${prefix}document_output.json`,
  }));
  return JSON.parse(await getResp.Body!.transformToString('utf-8'));
}

Key gotchas