Skip to main content
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:
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}")
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();
  }
}

Retrieving Native Documents

Get All Native Documents

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")
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();
  }
}

Get by ID or Filename

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']}")
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();
  }
}

Retrieve Binary Data

The binary content is retrieved separately from metadata for efficiency:
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")
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();
  }
}

Deleting Native Documents

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}")
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();
  }
}

Common MIME Types

File TypeMIME Type
PDFapplication/pdf
Word (docx)application/vnd.openxmlformats-officedocument.wordprocessingml.document
Excel (xlsx)application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
PNGimage/png
JPEGimage/jpeg
JSONapplication/json
HTMLtext/html
Plain Texttext/plain
CSVtext/csv
ZIPapplication/zip

Use Cases

Preserving Original Files

Store the original document alongside extracted content:
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
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;
  }
}

Multiple Source Files

Store multiple related files:
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")
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;
  }
}