azure-ai-formrecognizer-java

作者: microsoft

品牌重塑:Azure AI Form Recognizer 現已更名為 Azure AI Document Intelligence。新專案應使用 com.azure:azure-ai-documentintelligence。舊版 azure-ai-formrecognizer 套件僅支援 API 版本 2023-07-31。請參閱遷移指南。

npx skills add https://github.com/microsoft/skills --skill azure-ai-formrecognizer-java

Azure AI Document Intelligence SDK for Java

Rebranding: Azure AI Form Recognizer is now Azure AI Document Intelligence. New projects should use com.azure:azure-ai-documentintelligence. The legacy azure-ai-formrecognizer package targets API version 2023-07-31 only. See Migration Guide.

Before Implementation

Search microsoft-docs MCP for current API patterns:

  • Query: "azure-ai-documentintelligence Java SDK"
  • Verify: Parameters match installed SDK version (latest GA: 1.0.7)

Installation

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-ai-documentintelligence</artifactId>
    <version>1.0.0</version>
</dependency>

<!-- For DefaultAzureCredential -->
<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-identity</artifactId>
    <version>1.14.2</version>
</dependency>

Environment Variables

DOCUMENT_INTELLIGENCE_ENDPOINT=https://<resource>.cognitiveservices.azure.com/ # Required for all auth methods
AZURE_TOKEN_CREDENTIALS=prod  # Required only if DefaultAzureCredential is used in production

Authentication

DefaultAzureCredential (Recommended)

import com.azure.ai.documentintelligence.DocumentIntelligenceClient;
import com.azure.ai.documentintelligence.DocumentIntelligenceClientBuilder;
import com.azure.core.credential.TokenCredential;
import com.azure.identity.AzureIdentityEnvVars;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;

TokenCredential credential = new DefaultAzureCredentialBuilder()
    .requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
    .build();
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();

DocumentIntelligenceClient client = new DocumentIntelligenceClientBuilder()
    .endpoint(System.getenv("DOCUMENT_INTELLIGENCE_ENDPOINT"))
    .credential(credential)
    .buildClient();

API Key

import com.azure.core.credential.AzureKeyCredential;

DocumentIntelligenceClient client = new DocumentIntelligenceClientBuilder()
    .endpoint(System.getenv("DOCUMENT_INTELLIGENCE_ENDPOINT"))
    .credential(new AzureKeyCredential(System.getenv("DOCUMENT_INTELLIGENCE_KEY")))
    .buildClient();

Administration Client

import com.azure.ai.documentintelligence.DocumentIntelligenceAdministrationClient;
import com.azure.ai.documentintelligence.DocumentIntelligenceAdministrationClientBuilder;
import com.azure.core.credential.TokenCredential;
import com.azure.identity.AzureIdentityEnvVars;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;

TokenCredential credential = new DefaultAzureCredentialBuilder()
    .requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
    .build();
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();

DocumentIntelligenceAdministrationClient adminClient = new DocumentIntelligenceAdministrationClientBuilder()
    .endpoint(System.getenv("DOCUMENT_INTELLIGENCE_ENDPOINT"))
    .credential(credential)
    .buildClient();

Async Client

import com.azure.ai.documentintelligence.DocumentIntelligenceAsyncClient;
import com.azure.core.credential.TokenCredential;
import com.azure.identity.AzureIdentityEnvVars;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;

TokenCredential credential = new DefaultAzureCredentialBuilder()
    .requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
    .build();
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();

DocumentIntelligenceAsyncClient asyncClient = new DocumentIntelligenceClientBuilder()
    .endpoint(System.getenv("DOCUMENT_INTELLIGENCE_ENDPOINT"))
    .credential(credential)
    .buildAsyncClient();

Prebuilt Models

Model IDPurpose
prebuilt-readExtract text, lines, words, languages
prebuilt-layoutText, tables, selection marks, structure
prebuilt-receiptReceipt data extraction
prebuilt-invoiceInvoice field extraction
prebuilt-idDocumentID documents (passport, license)
prebuilt-tax.us.w2US W2 tax forms
prebuilt-healthInsuranceCard.usUS health insurance cards
prebuilt-contractContract field extraction

Retired models: prebuilt-businessCard and prebuilt-document are retired in API version 2024-11-30. Use the legacy azure-ai-formrecognizer package for these.

Core Patterns

Analyze from File

import com.azure.ai.documentintelligence.models.*;
import com.azure.core.util.BinaryData;
import com.azure.core.util.polling.SyncPoller;
import java.io.File;

File document = new File("document.pdf");
BinaryData documentData = BinaryData.fromFile(document.toPath(), (int) document.length());

SyncPoller<AnalyzeOperationDetails, AnalyzeResult> poller =
    client.beginAnalyzeDocument("prebuilt-layout",
        new AnalyzeDocumentOptions(documentData));

AnalyzeResult result = poller.getFinalResult();

Analyze from URL

String documentUrl = "https://example.com/invoice.pdf";

SyncPoller<AnalyzeOperationDetails, AnalyzeResult> poller =
    client.beginAnalyzeDocument("prebuilt-invoice",
        new AnalyzeDocumentOptions(documentUrl));

AnalyzeResult result = poller.getFinalResult();

Extract Layout

AnalyzeResult result = poller.getFinalResult();

for (DocumentPage page : result.getPages()) {
    System.out.printf("Page has width: %.2f and height: %.2f, measured with unit: %s%n",
        page.getWidth(), page.getHeight(), page.getUnit());

    // Lines
    for (DocumentLine line : page.getLines()) {
        System.out.printf("Line '%s' is within bounding box %s.%n",
            line.getContent(), line.getPolygon());
    }

    // Selection marks
    for (DocumentSelectionMark mark : page.getSelectionMarks()) {
        System.out.printf("Selection mark is '%s' with confidence %.2f.%n",
            mark.getState(), mark.getConfidence());
    }
}

// Tables
for (DocumentTable table : result.getTables()) {
    System.out.printf("Table: %d rows x %d columns%n",
        table.getRowCount(), table.getColumnCount());
    for (DocumentTableCell cell : table.getCells()) {
        System.out.printf("Cell[%d,%d]: %s%n",
            cell.getRowIndex(), cell.getColumnIndex(), cell.getContent());
    }
}

Extract Document Fields

SyncPoller<AnalyzeOperationDetails, AnalyzeResult> poller =
    client.beginAnalyzeDocument("prebuilt-receipt",
        new AnalyzeDocumentOptions(receiptUrl));

AnalyzeResult result = poller.getFinalResult();

for (AnalyzedDocument doc : result.getDocuments()) {
    Map<String, DocumentField> fields = doc.getFields();

    DocumentField merchantName = fields.get("MerchantName");
    if (merchantName != null && merchantName.getType() == DocumentFieldType.STRING) {
        System.out.printf("Merchant: %s (confidence: %.2f)%n",
            merchantName.getValueString(), merchantName.getConfidence());
    }

    DocumentField transactionDate = fields.get("TransactionDate");
    if (transactionDate != null && transactionDate.getType() == DocumentFieldType.DATE) {
        System.out.printf("Date: %s%n", transactionDate.getValueDate());
    }
}

Analyze with Options

SyncPoller<AnalyzeOperationDetails, AnalyzeResult> poller =
    client.beginAnalyzeDocument("my-custom-model",
        new AnalyzeDocumentOptions(documentUrl)
            .setPages(Collections.singletonList("1-3"))
            .setLocale("en-US")
            .setDocumentAnalysisFeatures(Arrays.asList(DocumentAnalysisFeature.LANGUAGES))
            .setOutputContentFormat(DocumentContentFormat.TEXT));

Custom Models

Build Custom Model

String blobContainerUrl = "{SAS_URL_of_training_data}";

SyncPoller<DocumentModelBuildOperationDetails, DocumentModelDetails> poller =
    adminClient.beginBuildDocumentModel(
        new BuildDocumentModelOptions("my-custom-model", DocumentBuildMode.TEMPLATE)
            .setAzureBlobSource(new AzureBlobContentSource(blobContainerUrl)));

DocumentModelDetails model = poller.getFinalResult();
System.out.printf("Model ID: %s%n", model.getModelId());
System.out.printf("Created: %s%n", model.getCreatedOn());

model.getDocumentTypes().forEach((docType, details) -> {
    details.getFieldSchema().forEach((field, schema) -> {
        System.out.printf("Field: %s (%s)%n", field, schema.getType());
    });
});

Manage Models

// Resource limits
DocumentIntelligenceResourceDetails resourceDetails = adminClient.getResourceDetails();
System.out.printf("Models: %d / %d%n",
    resourceDetails.getCustomDocumentModels().getCount(),
    resourceDetails.getCustomDocumentModels().getLimit());

// List models
PagedIterable<DocumentModelDetails> models = adminClient.listModels();
for (DocumentModelDetails model : models) {
    System.out.printf("Model: %s, Created: %s%n",
        model.getModelId(), model.getCreatedOn());
}

// Get model
DocumentModelDetails model = adminClient.getModel("model-id");

// Delete model
adminClient.deleteModel("model-id");

Document Classification

Build Classifier

Map<String, ClassifierDocumentTypeDetails> docTypes = new HashMap<>();
docTypes.put("invoice", new ClassifierDocumentTypeDetails()
    .setAzureBlobSource(new AzureBlobContentSource(containerUrl).setPrefix("invoices/")));
docTypes.put("receipt", new ClassifierDocumentTypeDetails()
    .setAzureBlobSource(new AzureBlobContentSource(containerUrl).setPrefix("receipts/")));

SyncPoller<DocumentClassifierBuildOperationDetails, DocumentClassifierDetails> poller =
    adminClient.beginBuildClassifier(
        new BuildDocumentClassifierOptions("my-classifier", docTypes));

DocumentClassifierDetails classifier = poller.getFinalResult();

Classify Document

SyncPoller<AnalyzeOperationDetails, AnalyzeResult> poller =
    client.beginClassifyDocument("my-classifier",
        new ClassifyDocumentOptions(documentUrl));

AnalyzeResult result = poller.getFinalResult();
for (AnalyzedDocument doc : result.getDocuments()) {
    System.out.printf("Classified as: %s (confidence: %.2f)%n",
        doc.getDocumentType(), doc.getConfidence());
}

Error Handling

import com.azure.core.exception.HttpResponseException;

try {
    client.beginAnalyzeDocument("prebuilt-receipt",
        new AnalyzeDocumentOptions("invalid-url"));
} catch (HttpResponseException e) {
    System.out.printf("Status: %d, Error: %s%n",
        e.getResponse().getStatusCode(), e.getMessage());
}

Migration from azure-ai-formrecognizer

Old (formrecognizer v4.x)New (documentintelligence v1.x)
DocumentAnalysisClientDocumentIntelligenceClient
DocumentAnalysisClientBuilderDocumentIntelligenceClientBuilder
DocumentModelAdministrationClientDocumentIntelligenceAdministrationClient
beginAnalyzeDocumentFromUrl(modelId, url)beginAnalyzeDocument(modelId, new AnalyzeDocumentOptions(url))
beginAnalyzeDocument(modelId, data)beginAnalyzeDocument(modelId, new AnalyzeDocumentOptions(data))
SyncPoller<OperationResult, AnalyzeResult>SyncPoller<AnalyzeOperationDetails, AnalyzeResult>
field.getValueAsString()field.getValueString()
field.getValueAsDate()field.getValueDate()
field.getValueAsDouble()field.getValueNumber()
field.getValueAsList()field.getValueList()
field.getValueAsMap()field.getValueObject()
mark.getSelectionMarkState()mark.getState()
adminClient.beginBuildDocumentModel(url, mode, prefix, options, ctx)adminClient.beginBuildDocumentModel(new BuildDocumentModelOptions(id, mode).setAzureBlobSource(...))
adminClient.getResourceDetails().getCustomDocumentModelCount()adminClient.getResourceDetails().getCustomDocumentModels().getCount()
FORM_RECOGNIZER_ENDPOINTDOCUMENT_INTELLIGENCE_ENDPOINT

Reference Files

FileContents
references/examples.mdComplete code examples for all scenarios

來自 microsoft 的更多技能

oss-growth
microsoft
開源增長駭客角色
official
microsoft-foundry
microsoft
端到端部署、評估與管理 Foundry 代理:Docker 建置、ACR 推送、託管/提示代理建立、容器啟動、批次評估、持續評估、提示最佳化工作流程、agent.yaml、從追蹤資料集整理。用途:將代理部署至 Foundry、託管代理、建立代理、調用代理、評估代理、執行批次評估、持續評估、持續監控、持續評估狀態、最佳化提示、改善提示、提示最佳化器、最佳化代理指令、改善代理...
officialdevelopmentdevops
azure-ai
microsoft
用於 Azure AI:搜尋、語音、OpenAI、文件智慧。協助搜尋、向量/混合搜尋、語音轉文字、文字轉語音、轉錄、OCR。適用情境:AI 搜尋、查詢搜尋、向量搜尋、混合搜尋、語意搜尋、語音轉文字、文字轉語音、轉錄、OCR、將文字轉換為語音。
officialdevelopmentapi
azure-deploy
microsoft
對已準備好的應用程式執行 Azure 部署,這些應用程式需具備現有的 .azure/deployment-plan.md 與基礎架構檔案。當使用者要求建立新應用程式時,請勿使用此技能——應改用 azure-prepare。此技能會執行 azd up、azd deploy、terraform apply 及 az deployment 命令,並內建錯誤復原機制。需具備來自 azure-prepare 的 .azure/deployment-plan.md,以及來自 azure-validate 的驗證狀態。適用時機:「執行 azd up」、「執行 azd deploy」、「執行部署」……
officialdevopsaws
azure-storage
microsoft
Azure Storage Services 包括 Blob 儲存體、檔案共用、佇列儲存體、表格儲存體和 Data Lake。回答關於儲存存取層(熱、冷、凍結、封存)、各層使用時機及層級比較的問題。提供物件儲存、SMB 檔案共用、非同步訊息、NoSQL 鍵值及大數據分析。包含生命週期管理。用於:blob 儲存體、檔案共用、佇列儲存體、表格儲存體、data lake、上傳檔案、下載 blob、儲存帳戶、存取層...
officialdevelopmentdatabase
azure-diagnostics
microsoft
在 Azure 上使用 AppLens、Azure Monitor、資源健康狀態和安全分類來偵錯 Azure 生產問題。適用時機:偵錯生產問題、疑難排解應用程式服務、應用程式服務高 CPU、應用程式服務部署失敗、疑難排解容器應用程式、疑難排解函數、疑難排解 AKS、kubectl 無法連線、kube-system/CoreDNS 失敗、Pod 擱置、CrashLoop、節點未就緒、升級失敗、分析記錄、KQL、深入解析、映像提取失敗、冷啟動問題、健康狀態探查失敗...
officialdevopsdevelopment
azure-prepare
microsoft
準備 Azure 應用程式以進行部署(基礎架構 Bicep/Terraform、azure.yaml、Dockerfile)。用於建立/現代化或建立+部署;不適用於跨雲端遷移(請使用 azure-cloud-migrate)。請勿用於:copilot-sdk 應用程式(請使用 azure-hosted-copilot-sdk)。適用時機:「建立應用程式」、「建置 Web 應用程式」、「建立 API」、「建立無伺服器 HTTP API」、「建立前端」、「建立後端」、「建置服務」、「現代化應用程式」、「更新應用程式」、「新增驗證」、「新增快取」、「託管於 Azure」、「建立並...」
officialdevelopmentdevops
azure-validate
microsoft
部署前驗證 Azure 就緒狀態。對設定、基礎架構(Bicep 或 Terraform)、RBAC 角色指派、受控身分權限及先決條件進行深度檢查,再進行部署。適用時機:驗證我的應用程式、檢查部署就緒狀態、執行預檢檢查、驗證設定、確認是否可部署、驗證 azure.yaml、驗證 Bicep、部署前測試、疑難排解部署錯誤、驗證 Azure Functions、驗證函式應用程式、驗證無伺服器...
officialdevopstesting