> ## Documentation Index
> Fetch the complete documentation index at: https://developer.kodexa.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Native Documents

> Embed and retrieve binary files such as PDFs, images, and Word documents inside KDDB Kodexa Documents using the native documents API of the SDK.

Native documents allow you to embed binary files (PDFs, images, Word documents, spreadsheets, etc.) directly within a KDDB document. This is useful for preserving the original source files alongside the extracted content.

## Overview

Each native document stores:

* **filename**: The original filename
* **mimeType**: The MIME type (e.g., `application/pdf`)
* **data**: The raw binary content
* **checksum**: Optional integrity hash
* **size**: File size in bytes

## Creating Native Documents

Store a binary file within your document:

<CodeGroup>
  ```python Python theme={null}
  from kodexa_document import Document

  with Document() as doc:
      # Read a PDF file
      with open("invoice.pdf", "rb") as f:
          pdf_data = f.read()

      # Store it in the document
      doc_id = doc.create_native_document(
          filename="invoice.pdf",
          mime_type="application/pdf",
          data=pdf_data,
          checksum="sha256:abc123def..."  # Optional
      )

      print(f"Created native document with ID: {doc_id}")
  ```

  ```typescript TypeScript theme={null}
  import { Kodexa } from '@kodexa-ai/document-wasm-ts';

  async function storeFile() {
    await Kodexa.init();
    const doc = await Kodexa.createDocument();

    try {
      // Get file data (e.g., from file input)
      const fileInput = document.getElementById('file') as HTMLInputElement;
      const file = fileInput.files?.[0];

      if (file) {
        const arrayBuffer = await file.arrayBuffer();
        const data = new Uint8Array(arrayBuffer);

        // Store it in the document
        const nativeDoc = await doc.nativeDocuments.create({
          filename: file.name,
          mimeType: file.type,
          data: data,
          checksum: 'sha256:abc123def...'  // Optional
        });

        console.log(`Created native document with ID: ${nativeDoc?.id}`);
      }
    } finally {
      doc.dispose();
    }
  }
  ```
</CodeGroup>

## Retrieving Native Documents

### Get All Native Documents

<CodeGroup>
  ```python Python theme={null}
  with Document.from_kddb("processed.kddb") as doc:
      # Get all native documents (metadata only)
      native_docs = doc.get_native_documents()

      for native_doc in native_docs:
          print(f"ID: {native_doc['id']}")
          print(f"  Filename: {native_doc['filename']}")
          print(f"  MIME Type: {native_doc['mime_type']}")
          print(f"  Size: {native_doc['size']} bytes")
  ```

  ```typescript TypeScript theme={null}
  async function listNativeDocuments() {
    await Kodexa.init();
    const doc = await Kodexa.fromBlob(kddbBlob);

    try {
      // Get all native documents (metadata only)
      const nativeDocs = await doc.nativeDocuments.getAll();

      for (const nativeDoc of nativeDocs) {
        console.log(`ID: ${nativeDoc.id}`);
        console.log(`  Filename: ${nativeDoc.filename}`);
        console.log(`  MIME Type: ${nativeDoc.mimeType}`);
        console.log(`  Size: ${nativeDoc.size} bytes`);
      }
    } finally {
      doc.dispose();
    }
  }
  ```
</CodeGroup>

### Get by ID or Filename

<CodeGroup>
  ```python Python theme={null}
  with Document.from_kddb("processed.kddb") as doc:
      # Get by ID
      native_doc = doc.get_native_document_by_id(1)
      if native_doc:
          print(f"Found: {native_doc['filename']}")

      # Get by filename
      native_doc = doc.get_native_document_by_filename("invoice.pdf")
      if native_doc:
          print(f"Found: {native_doc['filename']}")

      # Get the first native document
      first = doc.get_first_native_document()
      if first:
          print(f"First document: {first['filename']}")
  ```

  ```typescript TypeScript theme={null}
  async function findNativeDocuments() {
    await Kodexa.init();
    const doc = await Kodexa.fromBlob(kddbBlob);

    try {
      // Get by ID
      const byId = await doc.nativeDocuments.getById(1);
      if (byId) {
        console.log(`Found: ${byId.filename}`);
      }

      // Get by filename
      const byName = await doc.nativeDocuments.getByFilename('invoice.pdf');
      if (byName) {
        console.log(`Found: ${byName.filename}`);
      }

      // Get the first native document
      const first = await doc.nativeDocuments.getFirst();
      if (first) {
        console.log(`First document: ${first.filename}`);
      }
    } finally {
      doc.dispose();
    }
  }
  ```
</CodeGroup>

### Retrieve Binary Data

The binary content is retrieved separately from metadata for efficiency:

<CodeGroup>
  ```python Python theme={null}
  with Document.from_kddb("processed.kddb") as doc:
      # Get the native document metadata
      native_doc = doc.get_native_document_by_filename("invoice.pdf")

      if native_doc:
          # Get the actual binary data
          data = doc.get_native_document_data(native_doc['id'])

          # Save to file
          with open("extracted_invoice.pdf", "wb") as f:
              f.write(data)

          print(f"Extracted {len(data)} bytes")
  ```

  ```typescript TypeScript theme={null}
  async function extractFile() {
    await Kodexa.init();
    const doc = await Kodexa.fromBlob(kddbBlob);

    try {
      // Get the native document metadata
      const nativeDoc = await doc.nativeDocuments.getByFilename('invoice.pdf');

      if (nativeDoc) {
        // Get the actual binary data
        const data = await doc.nativeDocuments.getData(nativeDoc.id);

        if (data) {
          // Create download link in browser
          const blob = new Blob([data], { type: nativeDoc.mimeType });
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = nativeDoc.filename;
          a.click();
          URL.revokeObjectURL(url);

          console.log(`Extracted ${data.length} bytes`);
        }
      }
    } finally {
      doc.dispose();
    }
  }
  ```
</CodeGroup>

## Deleting Native Documents

<CodeGroup>
  ```python Python theme={null}
  with Document.from_kddb("processed.kddb") as doc:
      # Delete a specific native document
      success = doc.delete_native_document(doc_id=1)
      print(f"Deleted: {success}")

      # Delete all native documents
      success = doc.delete_all_native_documents()
      print(f"Deleted all: {success}")
  ```

  ```typescript TypeScript theme={null}
  async function deleteNativeDocuments() {
    await Kodexa.init();
    const doc = await Kodexa.fromBlob(kddbBlob);

    try {
      // Delete a specific native document
      const deleted = await doc.nativeDocuments.delete(1);
      console.log(`Deleted: ${deleted}`);

      // Delete all native documents
      const deletedAll = await doc.nativeDocuments.deleteAll();
      console.log(`Deleted all: ${deletedAll}`);
    } finally {
      doc.dispose();
    }
  }
  ```
</CodeGroup>

## Common MIME Types

| File Type    | MIME Type                                                                 |
| ------------ | ------------------------------------------------------------------------- |
| PDF          | `application/pdf`                                                         |
| Word (docx)  | `application/vnd.openxmlformats-officedocument.wordprocessingml.document` |
| Excel (xlsx) | `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`       |
| PNG          | `image/png`                                                               |
| JPEG         | `image/jpeg`                                                              |
| JSON         | `application/json`                                                        |
| HTML         | `text/html`                                                               |
| Plain Text   | `text/plain`                                                              |
| CSV          | `text/csv`                                                                |
| ZIP          | `application/zip`                                                         |

## Use Cases

### Preserving Original Files

Store the original document alongside extracted content:

<CodeGroup>
  ```python Python theme={null}
  from kodexa_document import Document

  def process_invoice(pdf_path: str) -> Document:
      """Process an invoice and preserve the original PDF."""
      with Document() as doc:
          # Store the original PDF
          with open(pdf_path, "rb") as f:
              doc.create_native_document(
                  filename=pdf_path.split("/")[-1],
                  mime_type="application/pdf",
                  data=f.read()
              )

          # Build extracted content structure
          root = doc.create_node("document", "Invoice")
          doc.content_node = root

          # Add extracted data...
          vendor = doc.create_node("paragraph", "Vendor: Acme Corp", parent=root)
          vendor.tag("vendor-name")

          return doc
  ```

  ```typescript TypeScript theme={null}
  async function processInvoice(pdfBlob: Blob, filename: string) {
    await Kodexa.init();
    const doc = await Kodexa.createDocument();

    try {
      // Store the original PDF
      const data = new Uint8Array(await pdfBlob.arrayBuffer());
      await doc.nativeDocuments.create({
        filename: filename,
        mimeType: 'application/pdf',
        data: data
      });

      // Build extracted content structure
      const root = await doc.createNode('document');
      await root.setContent('Invoice');

      // Add extracted data...
      const vendor = await doc.createNode('paragraph');
      await vendor.setContent('Vendor: Acme Corp');
      await root.addChild(vendor);
      await vendor.tag('vendor-name');

      return doc;
    } catch (e) {
      doc.dispose();
      throw e;
    }
  }
  ```
</CodeGroup>

### Multiple Source Files

Store multiple related files:

<CodeGroup>
  ```python Python theme={null}
  with Document() as doc:
      # Store multiple related documents
      files = [
          ("contract.pdf", "application/pdf"),
          ("schedule_a.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
          ("signature.png", "image/png")
      ]

      for filename, mime_type in files:
          with open(filename, "rb") as f:
              doc.create_native_document(
                  filename=filename,
                  mime_type=mime_type,
                  data=f.read()
              )

      print(f"Stored {len(doc.get_native_documents())} files")
  ```

  ```typescript TypeScript theme={null}
  async function storeMultipleFiles(files: File[]) {
    await Kodexa.init();
    const doc = await Kodexa.createDocument();

    try {
      for (const file of files) {
        const data = new Uint8Array(await file.arrayBuffer());
        await doc.nativeDocuments.create({
          filename: file.name,
          mimeType: file.type,
          data: data
        });
      }

      const stored = await doc.nativeDocuments.getAll();
      console.log(`Stored ${stored.length} files`);

      return doc;
    } catch (e) {
      doc.dispose();
      throw e;
    }
  }
  ```
</CodeGroup>
