IRONSOFTWAREHOME

C# 中的 AI 驅動 PDF 處理:使用 IronPDF 概述、提取和分析文件

Ahmad Sohail
Ahmad Sohail
Updated: 2026年6月29日

C# 中的 AI 驅動 PDF 處理 使用 IronPDF,讓 .NET 開發者可以直接在現有的 PDF 工作流程中概述文件提取結構化資料,以及構建問題回答系統——使用基於 Microsoft Semantic Kernel 構建的 IronPdf.Extensions.AI 套件,無縫連接 Azure OpenAIOpenAI 模型。 無論您是在構建法律發現工具財務分析管線,還是文件智能平台,IronPDF 處理 PDF 提取和上下文準備,以便您可以專注於 AI 邏輯。

TL;DR: 快速入門指南

本教程涵蓋如何將 IronPDF 連接到 AI 服務以進行文件摘要、資料提取和 C# .NET 中的智能查詢。

  • 適用物件: .NET 開發人員構建文件智能應用程式——法律發現系統、財務分析工具、合規審查平台或需要從大量 PDF 文件中提取意義的任何應用程式。
  • 您將構建的內容: 單文件摘要、使用自定義結構提取結構化 JSON 資料、跨文件內容的問答系統、長文件的 RAG 管線和跨文件庫的批量 AI 處理工作流程。
  • 運行環境: 任何使用 Azure OpenAI 或 OpenAI API 金鑰的 .NET 6+ 環境。 AI 擴展整合了 Microsoft Semantic Kernel,並自動處理上下文窗口管理、分塊和編排。
  • 此方法使用時機: 當您的應用程式需要超越文字提取的 PDF 處理時——理解合同義務、摘要研究論文、提取財務表作為結構化資料,或大規模地回答使用者對文件內容的問題。
  • 技術上的重要性: 原始文字提取會丟失文件結構——表格崩潰,分欄佈局中斷,語義關係消失。 IronPDF 準備文件以供 AI 消耗,保留結構並管理標記限制,以便模型接收到乾淨、有組織的輸入。

只需幾行程式碼即可對 PDF 進行摘要:

  1. 1Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf

  2. 2Copy and run this code snippet.

    await IronPdf.AI.PdfAIEngine.Summarize("contract.pdf", "summary.txt", azureEndpoint, azureApiKey);
    C#
  3. 3Deploy to test on your live environment

    Start using IronPDF in your project today with a free trial
    arrow pointer

購買或註冊 30 天的 IronPDF 試用後,在應用程式開始時新增您的許可證金鑰。

IronPdf.License.LicenseKey = "KEY";
NuGetInstall with NuGet

PM > Install-Package IronPdf

Install IronPDF by running the command above in the NuGet Package Manager Console, or search for the package in the NuGet Package Manager.

目錄

AI + PDF 機會

為什麼 PDF 是最大的未開發資料源

PDFs 代表了現代企業中結構化業務知識的最大儲存庫之一。專業文件——合同、財務報表、合規報告、法律簡報和研究論文——主要以 PDF 格式儲存。 這些文件包含關鍵的業務情報:定義義務和責任的合同條款、推動投資決策的財務指標、確保合規的監管要求,以及指導戰略的研究結果。

然而,傳統的 PDF 處理方法受到嚴重限制。 基本文字提取工具可以從頁面拉取原始字元,但它們失去了關鍵上下文:表結構坍塌成混亂的文字,多欄佈局變得無意義,章節之間的語義關係消失。

突破來自 AI 理解上下文和結構的能力。 現代 LLMs 不僅能識別單詞,還能理解文件組織,識別合同條款或財務表格等模式,並能即使在複雜佈局中也能提取意義。 GPT-5 的統一推理系統及其實時路由器和 Claude Sonnet 4.5 的增強代理能力都顯示出較早型號顯著降低的幻想率,使其在專業文件分析中更可靠。

LLMs 如何理解文件結構

大型語言模型為 PDF 分析帶來了複雜的自然語言處理能力。 GPT-5 的混合架構特點是多個子模型(主,迷你,思考,納米)及其實時路由器,可以根據任務的複雜性動態選擇最合適的變體 - 簡單問題引導到更快速的模型,複雜的推理任務則動員整個機型。

Claude Opus 4.6 特別擅長長期執行的代理任務,具有直接在分割的作業上協調的代理團隊和一個 1M 標記上下文窗口,無需分塊即可處理整個文件庫。

AI 模型分析 PDF 文件結構和識別元素

這種背景知識使 LLMs 能夠執行需要真實理解的任務。 在分析合同時,LLM 可以識別不僅僅是包含"終止"字樣的段落,還能理解在什麼特定條件下允許終止,包括涉及的通知要求和由此產生的責任。 支持這一能力的技術基礎是驅動現代 LLMs 的 Transformer 架構,GPT-5 的上下文窗口支持多達 272,000 個輸入標記,Claude Sonnet 4.5 的 200K 標記窗口提供全面的文件覆蓋。

IronPDF 的內建 AI 整合

安裝 IronPDF 和 AI 擴展

開始使用 AI 驅動的 PDF 處理需要核心的 IronPDF 程式庫、AI 擴展包和 Microsoft Semantic Kernel 依賴項。

using NuGet 包管理器安裝 IronPDF:

PM > Install-Package IronPdf, IronPdf.Extensions.AI, Microsoft.SemanticKernel, Microsoft.SemanticKernel.Plugins.Memory

這些包共同提供了一套完整的解決方案。 IronPDF 處理所有與 PDF 相關的操作——文字提取、頁面渲染、格式轉換,而 AI 擴展則通過 Microsoft Semantic Kernel 管理與語言模型的整合。

Semantic Kernel 包含試驗性的 API。將 <NoWarn>$(NoWarn);SKEXP0001;SKEXP0010;SKEXP0050</NoWarn> 新增到您的 .csproj PropertyGroup 以抑制編譯警告。

配置您的 OpenAI/Azure API 金鑰

在您能夠利用 AI 功能之前,您需要配置存取 AI 服務提供商。 IronPDF 的 AI 擴展支持 OpenAI 和 Azure OpenAI。 Azure OpenAI 通常是企業應用程式的首選,因為它提供了增強的安全功能、合規憑證,以及將資料保持在特定地理區域內的能力。

要配置 Azure OpenAI,您需要從 Azure 入口獲取您的 Azure 端點 URL、API 金鑰以及聊天和嵌入模型的部署名稱。

初始化 AI 引擎

IronPDF 的 AI 擴展在底層使用 Microsoft Semantic Kernel。 在使用任何 AI 功能之前,您必須使用您的 Azure OpenAI 憑證初始化內核並配置文件處理的記憶體儲存。

using IronPdf;
using IronPdf.AI;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Memory;
using Microsoft.SemanticKernel.Connectors.OpenAI;

// Initialize IronPDF AI with Azure OpenAI credentials

// Azure OpenAI configuration
string azureEndpoint = "https://your-resource.openai.azure.com/";
string apiKey = "your-azure-api-key";
string chatDeployment = "gpt-4o";
string embeddingDeployment = "text-embedding-ada-002";

// Initialize Semantic Kernel with Azure OpenAI
var kernel = Kernel.CreateBuilder()
    .AddAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .AddAzureOpenAIChatCompletion(chatDeployment, azureEndpoint, apiKey)
    .Build();

// Create memory store for document embeddings
var memory = new MemoryBuilder()
    .WithMemoryStore(new VolatileMemoryStore())
    .WithAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .Build();

// Initialize IronPDF AI
IronDocumentAI.Initialize(kernel, memory);

Console.WriteLine("IronPDF AI initialized successfully with Azure OpenAI");

初始化將建立兩個關鍵組件:

  • 內核: 通過 Azure OpenAI 處理聊天完成和文字嵌入生成
  • 記憶體: 用於語義搜索和檢索操作的文件嵌入儲存

初始化後,您可以在您的應用程式中使用 AI 功能。 對於生產應用,強烈建議將憑證儲存在環境變數或 Azure Key Vault 中。

IronPDF 如何為 AI 上下文準備 PDFs

AI 驅動的 PDF 處理最具挑戰性的方面之一是準備文件以供語言模型消耗。 雖然 GPT-5 支持多達 272,000 個輸入標記,而 Claude Opus 4.6 現在提供了 1M 標記上下文窗口,但單個法律合同或財務報表仍然可以輕鬆超過舊模型的限制。

IronPDF 的 AI 擴展通過智能文件準備處理了這一複雜性。 當您調用 AI 方法時,IronPDF 首先從 PDF 中提取文字,同時保留結構資訊——識別段落,保留表結構,並保持各部分之間的關係。

對於超過上下文限制的文件,IronPDF 在語義斷點處實現了戰略性的分塊——文件結構中的自然分割,如章節標題、換頁或段落邊界。


文件摘要

單文件摘要

文件摘要通過將長文字壓縮為易於理解的見解來提供即時價值。 Summarize 方法處理整個工作流:提取文字,準備以供 AI 消費,從語言模型中請求摘要,並保存結果。

輸入


程式碼使用 PdfDocument.FromFile() 載入 PDF,調用 pdf.Summarize() 生成簡明摘要,然後將結果保存到文字文件。

using IronPdf;
using IronPdf.AI;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Memory;
using Microsoft.SemanticKernel.Connectors.OpenAI;

// Summarize a PDF document using IronPDF AI

// Azure OpenAI configuration
string azureEndpoint = "https://your-resource.openai.azure.com/";
string apiKey = "your-azure-api-key";
string chatDeployment = "gpt-4o";
string embeddingDeployment = "text-embedding-ada-002";

// Initialize Semantic Kernel
var kernel = Kernel.CreateBuilder()
    .AddAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .AddAzureOpenAIChatCompletion(chatDeployment, azureEndpoint, apiKey)
    .Build();

var memory = new MemoryBuilder()
    .WithMemoryStore(new VolatileMemoryStore())
    .WithAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .Build();

IronDocumentAI.Initialize(kernel, memory);

// Load and summarize PDF
var pdf = PdfDocument.FromFile("sample-report.pdf");
string summary = await pdf.Summarize();

Console.WriteLine("Document Summary:");
Console.WriteLine(summary);

File.WriteAllText("report-summary.txt", summary);
Console.WriteLine("\nSummary saved to report-summary.txt");

控制台輸出

C# 中的控制台輸出顯示 PDF 文件摘要結果

摘要過程使用複雜的提示以確保高質量的結果。 2026 年的 GPT-5 和 Claude Sonnet 4.5 具有顯著改進的指令遵循能力,確保摘要抓住關鍵資訊,同時保持簡潔和易讀。

有關文件摘要技術和高級選項的詳細說明,請參閱我們的操作指南

多文件綜合

許多現實世界的場景要求合成跨多個文件的資訊。 法律團隊可能需要識別合同組合中的常見條款,或財務分析師可能想要比較跨季度報告的指標。

多文件合成的方法涉及單獨處理每個文件以提取關鍵資訊,然後聚合這些見解以進行最終的合成。

該範例遍歷多個 PDF,對每個 PDF 調用 pdf.Summarize(),然後使用 pdf.Query() 與綜合的摘要生成統一的合成。

using IronPdf;
using IronPdf.AI;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Memory;
using Microsoft.SemanticKernel.Connectors.OpenAI;

// Synthesize insights across multiple related documents (e.g., quarterly reports into annual summary)

// Azure OpenAI configuration
string azureEndpoint = "https://your-resource.openai.azure.com/";
string apiKey = "your-azure-api-key";
string chatDeployment = "gpt-4o";
string embeddingDeployment = "text-embedding-ada-002";

// Initialize Semantic Kernel
var kernel = Kernel.CreateBuilder()
    .AddAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .AddAzureOpenAIChatCompletion(chatDeployment, azureEndpoint, apiKey)
    .Build();

var memory = new MemoryBuilder()
    .WithMemoryStore(new VolatileMemoryStore())
    .WithAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .Build();

IronDocumentAI.Initialize(kernel, memory);

// Define documents to synthesize
string[] documentPaths = {
    "Q1-report.pdf",
    "Q2-report.pdf",
    "Q3-report.pdf",
    "Q4-report.pdf"
};

var documentSummaries = new List<string>();

// Summarize each document
foreach (string path in documentPaths)
{
    var pdf = PdfDocument.FromFile(path);
    string summary = await pdf.Summarize();
    documentSummaries.Add($"=== {Path.GetFileName(path)} ===\n{summary}");
    Console.WriteLine($"Processed: {path}");
}

// Combine and synthesize across all documents
string combinedSummaries = string.Join("\n\n", documentSummaries);

var synthesisDoc = PdfDocument.FromFile(documentPaths[0]);

string synthesisQuery = @"Based on the quarterly summaries below, provide an annual synthesis:
ll trends across quarters
chievements and challenges
over-year patterns

s:
inedSummaries;

string synthesis = await synthesisDoc.Query(synthesisQuery);

Console.WriteLine("\n=== Annual Synthesis ===");
Console.WriteLine(synthesis);

File.WriteAllText("annual-synthesis.txt", synthesis);

這種模式有效地擴展到大型文件集。 通過平行處理文件和管理中間結果,您可以在分析數百或數千份文件的同時保持連貫的合成。

執行摘要生成

執行摘要需要不同於標準摘要的方法。 執行摘要必須識別最具業務關鍵的資訊,突出關鍵決策或建議,並以適合領導層審閱的格式呈現結果。

程式碼使用 pdf.Query() 與結構化提示,要求業務語言中的關鍵決策、重要發現、財務影響和風險評估。

using IronPdf;
using IronPdf.AI;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Memory;
using Microsoft.SemanticKernel.Connectors.OpenAI;

// Generate executive summary from strategic documents for C-suite leadership

// Azure OpenAI configuration
string azureEndpoint = "https://your-resource.openai.azure.com/";
string apiKey = "your-azure-api-key";
string chatDeployment = "gpt-4o";
string embeddingDeployment = "text-embedding-ada-002";

// Initialize Semantic Kernel
var kernel = Kernel.CreateBuilder()
    .AddAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .AddAzureOpenAIChatCompletion(chatDeployment, azureEndpoint, apiKey)
    .Build();

var memory = new MemoryBuilder()
    .WithMemoryStore(new VolatileMemoryStore())
    .WithAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .Build();

IronDocumentAI.Initialize(kernel, memory);

var pdf = PdfDocument.FromFile("strategic-plan.pdf");

string executiveQuery = @"Create an executive summary for C-suite leadership. Include:

cisions Required:**
ny decisions needing executive approval

al Findings:**
5 most important findings (bullet points)

ial Impact:**
e/cost implications if mentioned

ssessment:**
riority risks identified

ended Actions:**
ate next steps

er 500 words. Use business language appropriate for board presentation.";

string executiveSummary = await pdf.Query(executiveQuery);

File.WriteAllText("executive-summary.txt", executiveSummary);
Console.WriteLine("Executive summary saved to executive-summary.txt");

生成的執行摘要優先採取行動資訊而不是全面覆蓋,提供決策者所需的準確資訊,而不會造成過度細節。


智能資料提取

將結構化資料提取到 JSON

AI 驅動的PDF處理最強大的應用之一是從非結構化文件中提取結構化資料。 2026年成功的結構化提取的關鍵是使用具有結構化輸出模式的JSON結構。 GPT-5引入了改進的結構化輸出,而Claude Sonnet 4.5則提供了增強的工具編排,以實現可靠的資料提取。

輸入


程式碼使用帶有JSON結構提示的JsonSerializer.Deserialize()解析和驗證提取的發票資料。

using IronPdf;
using IronPdf.AI;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Memory;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using System.Text.Json;

// Extract structured invoice data as JSON from PDF

// Azure OpenAI configuration
string azureEndpoint = "https://your-resource.openai.azure.com/";
string apiKey = "your-azure-api-key";
string chatDeployment = "gpt-4o";
string embeddingDeployment = "text-embedding-ada-002";

// Initialize Semantic Kernel
var kernel = Kernel.CreateBuilder()
    .AddAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .AddAzureOpenAIChatCompletion(chatDeployment, azureEndpoint, apiKey)
    .Build();

var memory = new MemoryBuilder()
    .WithMemoryStore(new VolatileMemoryStore())
    .WithAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .Build();

IronDocumentAI.Initialize(kernel, memory);

var pdf = PdfDocument.FromFile("sample-invoice.pdf");

// Define JSON schema for extraction
string extractionQuery = @"Extract invoice data and return as JSON with this exact structure:

voiceNumber"": ""string"",
voiceDate"": ""YYYY-MM-DD"",
eDate"": ""YYYY-MM-DD"",
ndor"": {
""name"": ""string"",
""address"": ""string"",
""taxId"": ""string or null""

stomer"": {
""name"": ""string"",
""address"": ""string""

neItems"": [
{
    ""description"": ""string"",
    ""quantity"": number,
    ""unitPrice"": number,
    ""total"": number
}

btotal"": number,
xRate"": number,
xAmount"": number,
tal"": number,
rrency"": ""string""


NLY valid JSON, no additional text.";

string jsonResponse = await pdf.Query(extractionQuery);

// Parse and save JSON
try
{
    var invoiceData = JsonSerializer.Deserialize<JsonElement>(jsonResponse);
    string formattedJson = JsonSerializer.Serialize(invoiceData, new JsonSerializerOptions { WriteIndented = true });

    Console.WriteLine("Extracted Invoice Data:");
    Console.WriteLine(formattedJson);

    File.WriteAllText("invoice-data.json", formattedJson);
}
catch (JsonException)
{
    Console.WriteLine("Unable to parse JSON response");
    File.WriteAllText("invoice-raw-response.txt", jsonResponse);
}

生成的JSON文件的部分截圖

從PDF中提取的發票資料作為結構化JSON

2026年的現代AI模型支持結構化輸出模式,確保有效的JSON響應符合提供的結構。 這消除了複雜的錯誤處理需求在惡意回應周圍。

合同條款識別

法律合同包含特定型別的條款,這些條款具有特別的重要性:終止條款、責任限制、賠償要求、智慧財產權分配和保密義務。 AI 驅動的條款識別自動化了此分析,同時保持高精准度。

此範例使用 pdf.Query() 以及以條款為重點的JSON結構提取合同型別、當事方、關鍵日期和個別條款風險等級。

using IronPdf;
using IronPdf.AI;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Memory;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using System.Text.Json;

// Analyze contract clauses and identify key terms, risks, and critical dates

// Azure OpenAI configuration
string azureEndpoint = "https://your-resource.openai.azure.com/";
string apiKey = "your-azure-api-key";
string chatDeployment = "gpt-4o";
string embeddingDeployment = "text-embedding-ada-002";

// Initialize Semantic Kernel
var kernel = Kernel.CreateBuilder()
    .AddAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .AddAzureOpenAIChatCompletion(chatDeployment, azureEndpoint, apiKey)
    .Build();

var memory = new MemoryBuilder()
    .WithMemoryStore(new VolatileMemoryStore())
    .WithAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .Build();

IronDocumentAI.Initialize(kernel, memory);

var pdf = PdfDocument.FromFile("contract.pdf");

// Define JSON schema for contract analysis
string clauseQuery = @"Analyze this contract and identify key clauses. Return JSON:

ntractType"": ""string"",
rties"": [""string""],
fectiveDate"": ""string"",
auses"": [
{
    ""type"": ""Termination|Liability|Indemnification|Confidentiality|IP|Payment|Warranty|Other"",
    ""title"": ""string"",
    ""summary"": ""string"",
    ""riskLevel"": ""Low|Medium|High"",
    ""keyTerms"": [""string""]
}

iticalDates"": [
{
    ""description"": ""string"",
    ""date"": ""string""
}

erallRiskAssessment"": ""Low|Medium|High"",
commendations"": [""string""]


: termination rights, liability caps, indemnification, IP ownership, confidentiality, payment terms.
NLY valid JSON.";

string analysisJson = await pdf.Query(clauseQuery);

try
{
    var analysis = JsonSerializer.Deserialize<JsonElement>(analysisJson);
    string formatted = JsonSerializer.Serialize(analysis, new JsonSerializerOptions { WriteIndented = true });

    Console.WriteLine("Contract Clause Analysis:");
    Console.WriteLine(formatted);

    File.WriteAllText("contract-analysis.json", formatted);

    // Display high-risk clauses
    Console.WriteLine("\n=== High Risk Clauses ===");
    foreach (var clause in analysis.GetProperty("clauses").EnumerateArray())
    {
        if (clause.GetProperty("riskLevel").GetString() == "High")
        {
            Console.WriteLine($"- {clause.GetProperty("type")}: {clause.GetProperty("summary")}");
        }
    }
}
catch (JsonException)
{
    Console.WriteLine("Unable to parse contract analysis");
    File.WriteAllText("contract-analysis-raw.txt", analysisJson);
}

此功能將合約審查從一個順序的手動過程轉變為一個自動化的可擴展工作流程。 法律團隊可以快速識別數百份合同中的高風險條款。

財務資料解析

財務文件包含嵌入在復雜敘述和表格中的關鍵量化資料。 AI 驅動的解析在財務文件方面表現卓越,因為它理解背景 - 區分歷史結果和前瞻預測,辨別數字是以千為單位還是以百萬為單位,以及理解不同指標之間的關係。

程式碼使用帶有金融JSON結構的 pdf.Query() 提取收益報告資料、資產負債表指標和前瞻性指導意見,生成結構化輸出。

using IronPdf;
using IronPdf.AI;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Memory;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using System.Text.Json;

// Extract financial metrics from annual reports and earnings documents

// Azure OpenAI configuration
string azureEndpoint = "https://your-resource.openai.azure.com/";
string apiKey = "your-azure-api-key";
string chatDeployment = "gpt-4o";
string embeddingDeployment = "text-embedding-ada-002";

// Initialize Semantic Kernel
var kernel = Kernel.CreateBuilder()
    .AddAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .AddAzureOpenAIChatCompletion(chatDeployment, azureEndpoint, apiKey)
    .Build();

var memory = new MemoryBuilder()
    .WithMemoryStore(new VolatileMemoryStore())
    .WithAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .Build();

IronDocumentAI.Initialize(kernel, memory);

var pdf = PdfDocument.FromFile("annual-report.pdf");

// Define JSON schema for financial extraction (numbers in millions)
string financialQuery = @"Extract financial metrics from this document. Return JSON:

portPeriod"": ""string"",
mpany"": ""string"",
rrency"": ""string"",
comeStatement"": {
""revenue"": number,
""costOfRevenue"": number,
""grossProfit"": number,
""operatingExpenses"": number,
""operatingIncome"": number,
""netIncome"": number,
""eps"": number

lanceSheet"": {
""totalAssets"": number,
""totalLiabilities"": number,
""shareholdersEquity"": number,
""cash"": number,
""totalDebt"": number

yMetrics"": {
""revenueGrowthYoY"": ""string"",
""grossMargin"": ""string"",
""operatingMargin"": ""string"",
""netMargin"": ""string"",
""debtToEquity"": number

idance"": {
""nextQuarterRevenue"": ""string"",
""fullYearRevenue"": ""string"",
""notes"": ""string""



 for unavailable data. Numbers in millions unless stated.
NLY valid JSON.";

string financialJson = await pdf.Query(financialQuery);

try
{
    var financials = JsonSerializer.Deserialize<JsonElement>(financialJson);
    string formatted = JsonSerializer.Serialize(financials, new JsonSerializerOptions { WriteIndented = true });

    Console.WriteLine("Extracted Financial Data:");
    Console.WriteLine(formatted);

    File.WriteAllText("financial-data.json", formatted);
}
catch (JsonException)
{
    Console.WriteLine("Unable to parse financial data");
    File.WriteAllText("financial-raw.txt", financialJson);
}

提取的結構化資料可以直接餵入財務模型、時間序列資料庫或分析平台,從而使指標能夠在報告期間自動追踪。

自定義提取提示

許多組織根據其特定領域、文件格式或業務流程有獨特的提取需求。 IronPDF 的AI整合完全支持自定義抽取提示,允許您定義要提取的資訊以及應如何構建。

此範例顯示使用研究焦點結構從學術論文中提取方法論、信心等級和限制的pdf.Query()

using IronPdf;
using IronPdf.AI;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Memory;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using System.Text.Json;

// Extract structured research metadata from academic papers

// Azure OpenAI configuration
string azureEndpoint = "https://your-resource.openai.azure.com/";
string apiKey = "your-azure-api-key";
string chatDeployment = "gpt-4o";
string embeddingDeployment = "text-embedding-ada-002";

// Initialize Semantic Kernel
var kernel = Kernel.CreateBuilder()
    .AddAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .AddAzureOpenAIChatCompletion(chatDeployment, azureEndpoint, apiKey)
    .Build();

var memory = new MemoryBuilder()
    .WithMemoryStore(new VolatileMemoryStore())
    .WithAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .Build();

IronDocumentAI.Initialize(kernel, memory);

var pdf = PdfDocument.FromFile("research-paper.pdf");

// Define JSON schema for research paper extraction
string researchQuery = @"Extract structured information from this research paper. Return JSON:

tle"": ""string"",
thors"": [""string""],
stitution"": ""string"",
blicationDate"": ""string"",
stract"": ""string"",
searchQuestion"": ""string"",
thodology"": {
""type"": ""Quantitative|Qualitative|Mixed Methods"",
""approach"": ""string"",
""sampleSize"": ""string"",
""dataCollection"": ""string""

yFindings"": [
{
    ""finding"": ""string"",
    ""significance"": ""string"",
    ""confidence"": ""High|Medium|Low""
}

mitations"": [""string""],
tureWork"": [""string""],
ywords"": [""string""]


 extracting verifiable claims and noting uncertainty.
NLY valid JSON.";

string extractionResult = await pdf.Query(researchQuery);

try
{
    var research = JsonSerializer.Deserialize<JsonElement>(extractionResult);
    string formatted = JsonSerializer.Serialize(research, new JsonSerializerOptions { WriteIndented = true });

    Console.WriteLine("Research Paper Extraction:");
    Console.WriteLine(formatted);

    File.WriteAllText("research-extraction.json", formatted);

    // Display key findings with confidence levels
    Console.WriteLine("\n=== Key Findings ===");
    foreach (var finding in research.GetProperty("keyFindings").EnumerateArray())
    {
        string confidence = finding.GetProperty("confidence").GetString() ?? "Unknown";
        Console.WriteLine($"[{confidence}] {finding.GetProperty("finding")}");
    }
}
catch (JsonException)
{
    Console.WriteLine("Unable to parse research extraction");
    File.WriteAllText("research-raw.txt", extractionResult);
}

自定義提示將AI驅動的提取從通用工具轉變為專業化的解決方案,專門為您的特殊需求量身定制。


我最喜歡的程式庫是IronPDF。它允許快速高效地操作PDF文件。它還有許多有價值的功能,例如導出到PDF/A格式和數位簽署PDF文件。

Milan Jovanovic

Microsoft MVP

查看案例研究

IronOCR意味著我們每年可以從手動處理中節省$40,000,同時提高生產力,釋放資源以進行高影響的任務。我會強烈推薦它。

Brent Matzelle

首席技術官,OPYN

查看案例研究

IronSuite在我們的運營中扮演著至關重要的角色。這些工具增加了包括建立平面圖和改善庫存管理在內的業務效率。

David Jones

首席軟體工程師,Agorus Build

查看案例研究

文件問答系統

構建PDF問答系統

問答系統使使用者可以以對話方式與PDF文件交互,以自然語言提出問題並獲得准確的、具有上下文的答案。 基本模式是從PDF中提取文字,將其與使用者的問題結合在一個提示中,並從AI中請求答案。

輸入


程式碼調用pdf.Query()進入互動迴圈,以回答使用者問題。

using IronPdf;
using IronPdf.AI;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Memory;
using Microsoft.SemanticKernel.Connectors.OpenAI;

// Interactive Q&A system for querying PDF documents

// Azure OpenAI configuration
string azureEndpoint = "https://your-resource.openai.azure.com/";
string apiKey = "your-azure-api-key";
string chatDeployment = "gpt-4o";
string embeddingDeployment = "text-embedding-ada-002";

// Initialize Semantic Kernel
var kernel = Kernel.CreateBuilder()
    .AddAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .AddAzureOpenAIChatCompletion(chatDeployment, azureEndpoint, apiKey)
    .Build();

var memory = new MemoryBuilder()
    .WithMemoryStore(new VolatileMemoryStore())
    .WithAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .Build();

IronDocumentAI.Initialize(kernel, memory);

var pdf = PdfDocument.FromFile("sample-legal-document.pdf");

// Memorize document to enable persistent querying
await pdf.Memorize();

Console.WriteLine("PDF Q&A System - Type 'exit' to quit\n");
Console.WriteLine($"Document loaded and memorized: {pdf.PageCount} pages\n");

// Interactive Q&A loop
while (true)
{
    Console.Write("Your question: ");
    string? question = Console.ReadLine();

    if (string.IsNullOrWhiteSpace(question) || question.ToLower() == "exit")
        break;

    string answer = await pdf.Query(question);

    Console.WriteLine($"\nAnswer: {answer}\n");
    Console.WriteLine(new string('-', 50) + "\n");
}

Console.WriteLine("Q&A session ended.");

控制台輸出

C#中顯示PDF問答系統控制台輸出

2026年有效Q&A的關鍵是約束AI以僅根據文件內容回答。 GPT-5的"安全完成"訓練方法和Claude Sonnet 4.5的改進布局顯著降低了幻想率。

分塊長文件以配合上下文窗口

大多數現實世界的文件超過AI上下文窗口。 有效的分塊策略對於處理這些文件至關重要。 分塊涉及將文件分割成足夠小的段以適合上下文窗口,同時保留語義一致性。

此程式碼遍歷overlapTokens

using IronPdf;

// Split long documents into overlapping chunks for RAG systems

var pdf = PdfDocument.FromFile("long-document.pdf");

// Chunking configuration
int maxChunkTokens = 4000;      // Leave room for prompts and responses
int overlapTokens = 200;        // Overlap for context continuity
int approxCharsPerToken = 4;    // Rough estimate for tokenization

int maxChunkChars = maxChunkTokens * approxCharsPerToken;
int overlapChars = overlapTokens * approxCharsPerToken;

var chunks = new List<DocumentChunk>();
var currentChunk = new System.Text.StringBuilder();
int chunkStartPage = 1;
int currentPage = 1;

for (int i = 0; i < pdf.PageCount; i++)
{
    string pageText = pdf.Pages[i].Text;
    currentPage = i + 1;

    if (currentChunk.Length + pageText.Length > maxChunkChars && currentChunk.Length > 0)
    {
        chunks.Add(new DocumentChunk
        {
            Text = currentChunk.ToString(),
            StartPage = chunkStartPage,
            EndPage = currentPage - 1,
            ChunkIndex = chunks.Count
        });

        // Create overlap with previous chunk for continuity
        string overlap = currentChunk.Length > overlapChars
            ? currentChunk.ToString().Substring(currentChunk.Length - overlapChars)
            : currentChunk.ToString();

        currentChunk.Clear();
        currentChunk.Append(overlap);
        chunkStartPage = currentPage - 1;
    }

    currentChunk.AppendLine($"\n--- Page {currentPage} ---\n");
    currentChunk.Append(pageText);
}

if (currentChunk.Length > 0)
{
    chunks.Add(new DocumentChunk
    {
        Text = currentChunk.ToString(),
        StartPage = chunkStartPage,
        EndPage = currentPage,
        ChunkIndex = chunks.Count
    });
}

Console.WriteLine($"Document chunked into {chunks.Count} segments");
foreach (var chunk in chunks)
{
    Console.WriteLine($"  Chunk {chunk.ChunkIndex + 1}: Pages {chunk.StartPage}-{chunk.EndPage} ({chunk.Text.Length} chars)");
}

// Save chunk metadata for RAG indexing
File.WriteAllText("chunks-metadata.json", System.Text.Json.JsonSerializer.Serialize(
    chunks.Select(c => new { c.ChunkIndex, c.StartPage, c.EndPage, Length = c.Text.Length }),
    new System.Text.Json.JsonSerializerOptions { WriteIndented = true }
));


ic class DocumentChunk

public string Text { get; set; } = "";
public int StartPage { get; set; }
public int EndPage { get; set; }
public int ChunkIndex { get; set; }

比較固定分塊與語義分塊的PDF文件

重迭的塊提供跨邊界的連續性,確保AI即使在相關資訊超過塊邊界時,也有足夠的上下文。

RAG(檢索增強生成)模式

檢索增強生成代表了一個2026年AI驅動文件分析的強大模式。與其把整個文件餵給AI,RAG系統先檢索針對特定查詢的相關部分,然後使用那些部分作為生成答案的背景。

RAG工作流有三個主要階段:文件準備(分塊和建立嵌入),檢索(搜尋相關塊),和生成(使用檢索到的塊作為AI回答的上下文)

程式碼在每個PDF上調用pdf.Query()從組合文件記憶體中檢索答案。

using IronPdf;
using IronPdf.AI;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Memory;
using Microsoft.SemanticKernel.Connectors.OpenAI;

// Retrieval-Augmented Generation (RAG) system for querying across multiple indexed documents

// Azure OpenAI configuration
string azureEndpoint = "https://your-resource.openai.azure.com/";
string apiKey = "your-azure-api-key";
string chatDeployment = "gpt-4o";
string embeddingDeployment = "text-embedding-ada-002";

// Initialize Semantic Kernel
var kernel = Kernel.CreateBuilder()
    .AddAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .AddAzureOpenAIChatCompletion(chatDeployment, azureEndpoint, apiKey)
    .Build();

var memory = new MemoryBuilder()
    .WithMemoryStore(new VolatileMemoryStore())
    .WithAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .Build();

IronDocumentAI.Initialize(kernel, memory);

// Index all documents in folder
string[] documentPaths = Directory.GetFiles("documents/", "*.pdf");

Console.WriteLine($"Indexing {documentPaths.Length} documents...\n");

// Memorize each document (creates embeddings for retrieval)
foreach (string path in documentPaths)
{
    var pdf = PdfDocument.FromFile(path);
    await pdf.Memorize();
    Console.WriteLine($"Indexed: {Path.GetFileName(path)} ({pdf.PageCount} pages)");
}

Console.WriteLine("\n=== RAG System Ready ===\n");

// Query across all indexed documents
string query = "What are the key compliance requirements for data retention?";

Console.WriteLine($"Query: {query}\n");

var searchPdf = PdfDocument.FromFile(documentPaths[0]);
string answer = await searchPdf.Query(query);

Console.WriteLine($"Answer: {answer}");

// Interactive query loop
Console.WriteLine("\n--- Enter questions (type 'exit' to quit) ---\n");

while (true)
{
    Console.Write("Question: ");
    string? userQuery = Console.ReadLine();

    if (string.IsNullOrWhiteSpace(userQuery) || userQuery.ToLower() == "exit")
        break;

    string response = await searchPdf.Query(userQuery);
    Console.WriteLine($"\nAnswer: {response}\n");
}

RAG系統在處理大文件集方面表現卓越——法律案例資料庫,技術文件庫,研究檔案。 通過僅檢索相關部分,它們在有效地維持反應質量的同時,實現了幾乎無限大的文件大小。

在PDF頁面中引用來源

對於專業應用,AI答案必須可驗證。 引用方法涉及在分塊和檢索過程中保持塊來源的元資料。 每個塊不僅儲存文字內容,還包括其來源頁碼、章節標題和在文件中的位置。

輸入


程式碼使用pdf.Pages[pageNum - 1].Text驗證來源。

using IronPdf;
using IronPdf.AI;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Memory;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using System.Text.RegularExpressions;

// Answer questions with page citations and source verification

// Azure OpenAI configuration
string azureEndpoint = "https://your-resource.openai.azure.com/";
string apiKey = "your-azure-api-key";
string chatDeployment = "gpt-4o";
string embeddingDeployment = "text-embedding-ada-002";

// Initialize Semantic Kernel
var kernel = Kernel.CreateBuilder()
    .AddAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .AddAzureOpenAIChatCompletion(chatDeployment, azureEndpoint, apiKey)
    .Build();

var memory = new MemoryBuilder()
    .WithMemoryStore(new VolatileMemoryStore())
    .WithAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .Build();

IronDocumentAI.Initialize(kernel, memory);

var pdf = PdfDocument.FromFile("sample-legal-document.pdf");
await pdf.Memorize();

string question = "What are the termination conditions in this agreement?";

// Request citations in query
string citationQuery = $@"{question}

T: Include specific page citations in your answer using the format (Page X) or (Pages X-Y).
e information that appears in the document.";

string answerWithCitations = await pdf.Query(citationQuery);

Console.WriteLine("Question: " + question);
Console.WriteLine("\nAnswer with Citations:");
Console.WriteLine(answerWithCitations);

// Extract cited page numbers using regex
var citedPages = ExtractCitedPages(answerWithCitations);
Console.WriteLine($"\nCited pages: {string.Join(", ", citedPages)}");

// Verify citations with page excerpts
Console.WriteLine("\n=== Source Verification ===");
foreach (int pageNum in citedPages.Take(3))
{
    if (pageNum <= pdf.PageCount && pageNum > 0)
    {
        string pageText = pdf.Pages[pageNum - 1].Text;
        string excerpt = pageText.Length > 200 ? pageText.Substring(0, 200) + "..." : pageText;
        Console.WriteLine($"\nPage {pageNum} excerpt:\n{excerpt}");
    }
}

// Extract page numbers from citation format (Page X) or (Pages X-Y)
List<int> ExtractCitedPages(string text)
{
    var pages = new HashSet<int>();
    var matches = Regex.Matches(text, @"\(Pages?\s*(\d+)(?:\s*-\s*(\d+))?\)", RegexOptions.IgnoreCase);

    foreach (Match match in matches)
    {
        int startPage = int.Parse(match.Groups[1].Value);
        pages.Add(startPage);

        if (match.Groups[2].Success)
        {
            int endPage = int.Parse(match.Groups[2].Value);
            for (int p = startPage; p <= endPage; p++)
                pages.Add(p);
        }
    }
    return pages.OrderBy(p => p).ToList();
}

控制台輸出

顯示PDF中AI答案的頁面引用的控制台輸出

引用將AI生成的答案從不透明輸出轉化為透明的、可驗證的資訊。 使用者可以查看來源材料以驗證答案並建立對AI輔助分析的信心。


批量 AI 處理

大規模處理文件庫

企業文件處理通常涉及數千或數百萬條PDF。 可擴展批處理的基礎是平行化。 IronPDF是執行緒安全的,允許不受干擾地並行進行PDF處理。

此程式碼使用具有可配置的ConcurrentBag中追踪結果。

using IronPdf;
using IronPdf.AI;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Memory;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using System;
using System.Collections.Concurrent;
using System.Text;

// Process multiple documents in parallel with rate limiting

// Azure OpenAI configuration
string azureEndpoint = "https://your-resource.openai.azure.com/";
string apiKey = "your-azure-api-key";
string chatDeployment = "gpt-4o";
string embeddingDeployment = "text-embedding-ada-002";

// Initialize Semantic Kernel
var kernel = Kernel.CreateBuilder()
    .AddAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .AddAzureOpenAIChatCompletion(chatDeployment, azureEndpoint, apiKey)
    .Build();

var memory = new MemoryBuilder()
    .WithMemoryStore(new VolatileMemoryStore())
    .WithAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .Build();

IronDocumentAI.Initialize(kernel, memory);

// Configure parallel processing with rate limiting
int maxConcurrency = 3;
string inputFolder = "documents/";
string outputFolder = "summaries/";

Directory.CreateDirectory(outputFolder);

string[] pdfFiles = Directory.GetFiles(inputFolder, "*.pdf");
Console.WriteLine($"Processing {pdfFiles.Length} documents...\n");

var results = new ConcurrentBag<ProcessingResult>();
var semaphore = new SemaphoreSlim(maxConcurrency);

var tasks = pdfFiles.Select(async filePath =>
{
    await semaphore.WaitAsync();
    var result = new ProcessingResult { FilePath = filePath };

    try
    {
        var stopwatch = System.Diagnostics.Stopwatch.StartNew();

        var pdf = PdfDocument.FromFile(filePath);
        string summary = await pdf.Summarize();

        string outputPath = Path.Combine(outputFolder,
            Path.GetFileNameWithoutExtension(filePath) + "-summary.txt");
        await File.WriteAllTextAsync(outputPath, summary);

        stopwatch.Stop();
        result.Success = true;
        result.ProcessingTime = stopwatch.Elapsed;
        result.OutputPath = outputPath;

        Console.WriteLine($"[OK] {Path.GetFileName(filePath)} ({stopwatch.ElapsedMilliseconds}ms)");
    }
    catch (Exception ex)
    {
        result.Success = false;
        result.ErrorMessage = ex.Message;
        Console.WriteLine($"[ERROR] {Path.GetFileName(filePath)}: {ex.Message}");
    }
    finally
    {
        semaphore.Release();
        results.Add(result);
    }
}).ToArray();

await Task.WhenAll(tasks);

// Generate processing report
var successful = results.Where(r => r.Success).ToList();
var failed = results.Where(r => !r.Success).ToList();

var report = new StringBuilder();
report.AppendLine("=== Batch Processing Report ===");
report.AppendLine($"Successful: {successful.Count}");
report.AppendLine($"Failed: {failed.Count}");

if (successful.Any())
{
    var avgTime = TimeSpan.FromMilliseconds(successful.Average(r => r.ProcessingTime.TotalMilliseconds));
    report.AppendLine($"Average processing time: {avgTime.TotalSeconds:F1}s");
}

if (failed.Any())
{
    report.AppendLine("\nFailed documents:");
    foreach (var fail in failed)
        report.AppendLine($"  - {Path.GetFileName(fail.FilePath)}: {fail.ErrorMessage}");
}

string reportText = report.ToString();
Console.WriteLine($"\n{reportText}");
File.WriteAllText(Path.Combine(outputFolder, "processing-report.txt"), reportText);


s ProcessingResult

public string FilePath { get; set; } = "";
public bool Success { get; set; }
public TimeSpan ProcessingTime { get; set; }
public string OutputPath { get; set; } = "";
public string ErrorMessage { get; set; } = "";

穩健的錯誤處理在大規模環境中至關重要。 生產系統實現具有指數回退的重試邏輯,為失敗的文件設置單獨的錯誤日誌,並支援可恢復處理。

成本管理和標記使用

AI API成本通常每個標記收費。 2026年,GPT-5的價格為每百萬輸入標記1.25美元,並且每百萬輸出標記為10美元,而Claude Sonnet 4.5則為3美元每百萬輸入標記和15美元每百萬輸出標記。 主要成本優化策略是減少不必要的標記使用。

OpenAI的批API提供50%的標記成本折扣,以換取更長的處理時間(最多24小時)。 對於夜間處理或定期分析,批處理可提供實質性費用減省。

程式碼使用HttpClient上傳至OpenAI文件端點,並提交到批API。

using IronPdf;
using System.Text.Json;
using System.Net.Http.Headers;

// Use OpenAI Batch API for 50% cost savings on large-scale document processing

string openAiApiKey = "your-openai-api-key";
string inputFolder = "documents/";

// Prepare batch requests in JSONL format
var batchRequests = new List<string>();
string[] pdfFiles = Directory.GetFiles(inputFolder, "*.pdf");

Console.WriteLine($"Preparing batch for {pdfFiles.Length} documents...\n");

foreach (string filePath in pdfFiles)
{
    var pdf = PdfDocument.FromFile(filePath);
    string pdfText = pdf.ExtractAllText();

    // Truncate to stay within batch API limits
    if (pdfText.Length > 100000)
        pdfText = pdfText.Substring(0, 100000) + "\n[Truncated...]";

    var request = new
    {
        custom_id = Path.GetFileNameWithoutExtension(filePath),
        method = "POST",
        url = "/v1/chat/completions",
        body = new
        {
            model = "gpt-4o",
            messages = new[]
            {
                new { role = "system", content = "Summarize the following document concisely." },
                new { role = "user", content = pdfText }
            },
            max_tokens = 1000
        }
    };

    batchRequests.Add(JsonSerializer.Serialize(request));
}

// Create JSONL file
string batchFilePath = "batch-requests.jsonl";
File.WriteAllLines(batchFilePath, batchRequests);
Console.WriteLine($"Created batch file with {batchRequests.Count} requests");

// Upload file to OpenAI
using var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", openAiApiKey);

using var fileContent = new MultipartFormDataContent();
fileContent.Add(new ByteArrayContent(File.ReadAllBytes(batchFilePath)), "file", "batch-requests.jsonl");
fileContent.Add(new StringContent("batch"), "purpose");

var uploadResponse = await httpClient.PostAsync("https://api.openai.com/v1/files", fileContent);
var uploadResult = JsonSerializer.Deserialize<JsonElement>(await uploadResponse.Content.ReadAsStringAsync());
string fileId = uploadResult.GetProperty("id").GetString()!;
Console.WriteLine($"Uploaded file: {fileId}");

// Create batch job (24-hour completion window for 50% discount)
var batchJobRequest = new
{
    input_file_id = fileId,
    endpoint = "/v1/chat/completions",
    completion_window = "24h"
};

var batchResponse = await httpClient.PostAsync(
    "https://api.openai.com/v1/batches",
    new StringContent(JsonSerializer.Serialize(batchJobRequest), System.Text.Encoding.UTF8, "application/json")
);

var batchResult = JsonSerializer.Deserialize<JsonElement>(await batchResponse.Content.ReadAsStringAsync());
string batchId = batchResult.GetProperty("id").GetString()!;

Console.WriteLine($"\nBatch job created: {batchId}");
Console.WriteLine("Job will complete within 24 hours");
Console.WriteLine($"Check status: GET https://api.openai.com/v1/batches/{batchId}");

File.WriteAllText("batch-job-id.txt", batchId);
Console.WriteLine("\nBatch ID saved to batch-job-id.txt");

在生產中監控標記使用至關重要。 許多組織發現它們的文件有80%可以用較小、較便宜的模型處理,僅在複雜情況下保留昂貴的模型。

快取和增量處理

對於逐漸更新的文件集合,智能快取和增量處理策略可以大幅降低成本。 文件級快取與源PDF哈希一起儲存結果,防止不必要的重複處理未更改的文件。

LastAccessed CacheEntry物件中。

using IronPdf;
using IronPdf.AI;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Memory;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text.Json;

// Cache AI processing results using file hashes to avoid reprocessing unchanged documents

// Azure OpenAI configuration
string azureEndpoint = "https://your-resource.openai.azure.com/";
string apiKey = "your-azure-api-key";
string chatDeployment = "gpt-4o";
string embeddingDeployment = "text-embedding-ada-002";

// Initialize Semantic Kernel
var kernel = Kernel.CreateBuilder()
    .AddAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .AddAzureOpenAIChatCompletion(chatDeployment, azureEndpoint, apiKey)
    .Build();

var memory = new MemoryBuilder()
    .WithMemoryStore(new VolatileMemoryStore())
    .WithAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .Build();

IronDocumentAI.Initialize(kernel, memory);

// Configure caching
string cacheFolder = "ai-cache/";
string documentsFolder = "documents/";

Directory.CreateDirectory(cacheFolder);

var cacheManager = new DocumentCacheManager(cacheFolder);

// Process documents with caching
string[] pdfFiles = Directory.GetFiles(documentsFolder, "*.pdf");
int cached = 0, processed = 0;

foreach (string filePath in pdfFiles)
{
    string fileName = Path.GetFileName(filePath);
    string fileHash = cacheManager.ComputeFileHash(filePath);

    var cachedResult = cacheManager.GetCachedResult(fileName, fileHash);

    if (cachedResult != null)
    {
        Console.WriteLine($"[CACHE HIT] {fileName}");
        cached++;
        continue;
    }

    Console.WriteLine($"[PROCESSING] {fileName}");
    var pdf = PdfDocument.FromFile(filePath);
    string summary = await pdf.Summarize();

    cacheManager.CacheResult(fileName, fileHash, summary);
    processed++;
}

Console.WriteLine($"\nProcessing complete: {cached} cached, {processed} newly processed");
Console.WriteLine($"Cost savings: {(cached * 100.0 / Math.Max(1, cached + processed)):F1}% served from cache");


ash-based cache manager with JSON index
s DocumentCacheManager

private readonly string _cacheFolder;
private readonly string _indexPath;
private Dictionary<string, CacheEntry> _index;

public DocumentCacheManager(string cacheFolder)
{
    _cacheFolder = cacheFolder;
    _indexPath = Path.Combine(cacheFolder, "cache-index.json");
    _index = LoadIndex();
}

private Dictionary<string, CacheEntry> LoadIndex()
{
    if (File.Exists(_indexPath))
    {
        string json = File.ReadAllText(_indexPath);
        return JsonSerializer.Deserialize<Dictionary<string, CacheEntry>>(json) ?? new();
    }
    return new Dictionary<string, CacheEntry>();
}

private void SaveIndex()
{
    string json = JsonSerializer.Serialize(_index, new JsonSerializerOptions { WriteIndented = true });
    File.WriteAllText(_indexPath, json);
}

// SHA256 hash to detect file changes
public string ComputeFileHash(string filePath)
{
    using var sha256 = SHA256.Create();
    using var stream = File.OpenRead(filePath);
    byte[] hash = sha256.ComputeHash(stream);
    return Convert.ToHexString(hash);
}

public string? GetCachedResult(string fileName, string currentHash)
{
    if (_index.TryGetValue(fileName, out var entry))
    {
        if (entry.FileHash == currentHash && File.Exists(entry.CachePath))
        {
            entry.LastAccessed = DateTime.UtcNow;
            SaveIndex();
            return File.ReadAllText(entry.CachePath);
        }
    }
    return null;
}

public void CacheResult(string fileName, string fileHash, string result)
{
    string cachePath = Path.Combine(_cacheFolder, $"{Path.GetFileNameWithoutExtension(fileName)}-{fileHash[..8]}.txt");
    File.WriteAllText(cachePath, result);

    _index[fileName] = new CacheEntry
    {
        FileHash = fileHash,
        CachePath = cachePath,
        CreatedAt = DateTime.UtcNow,
        LastAccessed = DateTime.UtcNow
    };

    SaveIndex();
}


s CacheEntry

public string FileHash { get; set; } = "";
public string CachePath { get; set; } = "";
public DateTime CreatedAt { get; set; }
public DateTime LastAccessed { get; set; }

2026年的GPT-5和Claude Sonnet 4.5還具備自動提示快取,能將重複模式下的有效標記消耗減少50-90%——對於大型操作來說是一個巨大的成本節約。


實際使用案例

法律發現和合同分析

法律發現傳統上需要大批的初級律師手工審閱數十萬頁。 AI 驅動的發現變革了這一過程,能快速識別相關文件、自動化權限審查、以及提取關鍵證據事實。

IronPDF 的 AI 整合能夠支持複雜的法律工作流程:權利檢測、相關性評分、問題識別和關鍵日期提取。 律師事務所報告發現審查時間縮短了70-80%,使他們能夠更小團隊處理更大案件。

隨著2026年GPT-5和Claude Sonnet 4.5改進的準確性和降低的幻想率,法律專家可以信任AI輔助分析進行越來越關鍵的決策。

財務報告分析

財務分析師花費大量時間從收益報告、證券交易委員會申報文件和分析師演講中提取資料。 AI 驅動的財務文件處理自動化了這种提取,讓分析者能專注于解釋而不是資料收集。

此範例處理多個10-K文件,使用CompanyFinancials提取並比較不同公司之間的收入、利潤和風險因素。

using IronPdf;
using IronPdf.AI;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Memory;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using System.Collections.Generic;
using System.Text.Json;
using System.Text;

// Compare financial metrics across multiple company filings for sector analysis

// Azure OpenAI configuration
string azureEndpoint = "https://your-resource.openai.azure.com/";
string apiKey = "your-azure-api-key";
string chatDeployment = "gpt-4o";
string embeddingDeployment = "text-embedding-ada-002";

// Initialize Semantic Kernel
var kernel = Kernel.CreateBuilder()
    .AddAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .AddAzureOpenAIChatCompletion(chatDeployment, azureEndpoint, apiKey)
    .Build();

var memory = new MemoryBuilder()
    .WithMemoryStore(new VolatileMemoryStore())
    .WithAzureOpenAITextEmbeddingGeneration(embeddingDeployment, azureEndpoint, apiKey)
    .Build();

IronDocumentAI.Initialize(kernel, memory);

// Analyze company filings
string[] companyFilings = {
    "filings/company-a-10k.pdf",
    "filings/company-b-10k.pdf",
    "filings/company-c-10k.pdf"
};

var sectorData = new List<CompanyFinancials>();

foreach (string filing in companyFilings)
{
    Console.WriteLine($"Analyzing: {Path.GetFileName(filing)}");

    var pdf = PdfDocument.FromFile(filing);

    // Define JSON schema for 10-K extraction (numbers in millions USD)
    string extractionQuery = @"Extract key financial metrics from this 10-K filing. Return JSON:

mpanyName"": ""string"",
scalYear"": ""string"",
venue"": number,
venueGrowth"": number,
ossMargin"": number,
eratingMargin"": number,
tIncome"": number,
s"": number,
talDebt"": number,
shPosition"": number,
ployeeCount"": number,
yRisks"": [""string""],
idance"": ""string""


in millions USD. Growth/margins as percentages.
NLY valid JSON.";

    string result = await pdf.Query(extractionQuery);

    try
    {
        var financials = JsonSerializer.Deserialize<CompanyFinancials>(result);
        if (financials != null)
            sectorData.Add(financials);
    }
    catch
    {
        Console.WriteLine($"  Warning: Could not parse financials for {filing}");
    }
}

// Generate sector comparison report
var report = new StringBuilder();
report.AppendLine("=== Sector Analysis Report ===\n");

report.AppendLine("Revenue Comparison (millions USD):");
foreach (var company in sectorData.OrderByDescending(c => c.Revenue))
    report.AppendLine($"  {company.CompanyName}: ${company.Revenue:N0} ({company.RevenueGrowth:+0.0;-0.0}% YoY)");

report.AppendLine("\nProfitability Margins:");
foreach (var company in sectorData.OrderByDescending(c => c.OperatingMargin))
    report.AppendLine($"  {company.CompanyName}: {company.GrossMargin:F1}% gross, {company.OperatingMargin:F1}% operating");

report.AppendLine("\nFinancial Health (Debt vs Cash):");
foreach (var company in sectorData)
{
    double netDebt = company.TotalDebt - company.CashPosition;
    string status = netDebt < 0 ? "Net Cash" : "Net Debt";
    report.AppendLine($"  {company.CompanyName}: {status} ${Math.Abs(netDebt):N0}M");
}

string reportText = report.ToString();
Console.WriteLine($"\n{reportText}");
File.WriteAllText("sector-analysis-report.txt", reportText);

// Save full JSON data
string outputJson = JsonSerializer.Serialize(sectorData, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText("sector-analysis.json", outputJson);

Console.WriteLine("Analysis saved to sector-analysis.json and sector-analysis-report.txt");


s CompanyFinancials

public string CompanyName { get; set; } = "";
public string FiscalYear { get; set; } = "";
public double Revenue { get; set; }
public double RevenueGrowth { get; set; }
public double GrossMargin { get; set; }
public double OperatingMargin { get; set; }
public double NetIncome { get; set; }
public double Eps { get; set; }
public double TotalDebt { get; set; }
public double CashPosition { get; set; }
public int EmployeeCount { get; set; }
public List<string> KeyRisks { get; set; } = new();
public string Guidance { get; set; } = "";

投資公司使用AI驅動的分析每天能處理數千份文件,使分析師能够监控更大的市場覆蓋範圍,快速應對出現的機會。

研究論文摘要

學術研究每年生成數百萬篇論文。 AI驅動的調格有助於研究者快速評估論文的相關性,理解關鍵成果,並找出值得詳細閱讀的文章。 有效的研究總結必須確定研究問題,解釋方法,總結關鍵發現(附適當注意事項),並將結果放在背景中。

研究機構使用AI總結來維護機構知識庫,能夠自動處理新發布的出版物。 隨著2026年GPT-5 改良的科學推理和Claude Sonnet 4.5 增強的分析能力,學術總結達到了新的精確度。

政府文件處理

政府機構生成大量文件,包括規範、公共評論、環境影響聲明、法院文件及審計報告。 AI駐腕的文件處理使政府資訊可操作,通過監管合規分析、環境影響評估和法律追踪來實現。

公共評論分析帶來了獨特的挑戰 - 主要監管提案可能收到數十萬條評論。 AI系統可以按主題分類評論,識別共同主題,檢測協調的活動,並提取需要代理商響應的實質性論點。

2026年一代的AI模型帶來了前所未有的能力在政府文件處理上,支持民主透明性和知情決策。


故障排除與技術支持

常見錯誤的快速修復

  • 首次渲染慢? 正常。 Chrome 啓動需2-3秒,然後加速。
  • 雲端問題? 至少使用Azure B1或同等資源。
  • 資產丟失? 設置基本路徑或嵌入為 base64。
  • 元素丟失? 新增RenderDelay以執行JavaScript。
  • 記憶體問題? 更新到最新IronPDF版本以獲得性能修復。
  • 表單域問題? 確保唯一名稱並更新到最新版本。

直接從開發IronPDF的工程師獲得幫助,24/7

IronPDF 提供24/7的工程師支持。 在進行HTML到PDF轉換或AI整合時遇到困難嗎? 聯絡我們:


下一步

現在您了解了AI驅動的PDF處理,下一步是探索IronPDF更廣泛的功能。 OpenAI整合指南提供了更深入的摘要化、查詢和記錄模式的介紹,而文字和圖像提取教程說明了如何在AI分析前對PDF進行預處理。 對於文件組裝工作流程,學習如何合併和拆分PDF以進行批量處理。

當您準備好擴展超越AI功能時,完整的PDF編輯教程介紹了水印、頁首、頁尾、表單和註釋。 關於替代AI整合方法,ChatGPT C#教程顯示了不同的模式。 生產部署在Azure部署指南中涵蓋WebApps和Functions,而C# PDF建立教程涵蓋了從HTML、URL和原始內容生成PDFs.

準備開始了嗎? 開始您的免費30天試用以在生產中進行無水印測試,具有靈活的授權,可隨著團隊擴展。 對AI整合或任何IronPDF功能有疑問,我們的工程支援團隊隨時提供幫助。

Frequently Asked Questions

在C#中使用AI進行PDF處理有哪些好處?

AI驅動的PDF處理在C#中允許高級功能,如文件總結、資料提取到JSON和構建問答系統。它提高了處理大量文件的效率和準確性。

IronPDF如何整合AI來總結文件?

IronPDF通過利用GPT-5和Claude等模型來整合AI,這些模型可以分析和總結文件,使您能更容易地從大文字中衍生見解並快速理解。

RAG模式在AI驅動的PDF處理中扮演什麼角色?

RAG(檢索和生成)模式在AI驅動的PDF處理中被用來提高資訊檢索和生成的質量,使文件分析更加準確並具有上下文相關性。

如何使用IronPDF從PDF中提取結構化資料?

IronPDF允許將PDF中的結構化資料提取到像JSON這樣的格式,促進不同應用和系統之間的資料無縫整合和分析。

IronPDF可以使用AI處理大型文件庫嗎?

是的,IronPDF可以通過使用AI模型來高效處理大型文件庫,自動化諸如總結和資料提取等任務,這在OpenAI和Azure OpenAI整合的幫助下表現良好。

IronPDF支持哪種AI模型用於PDF處理?

IronPDF支持如GPT-5和Claude這樣的高級AI模型,這些模型被用於諸如文件總結和問答系統構建等任務,增強了整體的處理能力。

IronPDF如何促進問答系統的構建?

IronPDF通過處理和分析文件來提取相關資訊,然後可以使用這些資訊生成對使用者查詢的準確響應,從而幫助構建問答系統。

AI驅動的PDF處理在C#中的主要使用場景是什麼?

主要使用場景包括文件總結、結構化資料提取、問答系統開發,以及使用如OpenAI整合的AI來處理大規模文件處理任務。

IronPDF能否與Azure OpenAI一起用於文件處理?

是的,IronPDF可與Azure OpenAI整合以增強文件處理任務,提供可擴展的解決方案,以總結、提取和分析PDF文件。

IronPDF如何藉由AI提高文件分析?

IronPDF通過使用AI模型來自動化和增強諸如總結、資料提取和資訊檢索等任務,提高了文件處理的效率和準確性。

Ahmad Sohail
Full Stack Developer

Ahmad is a full-stack developer with a strong foundation in C#, Python, and web technologies. He has a deep interest in building scalable software solutions and enjoys exploring how design and functionality meet in real-world applications.

...
Read More

準備開始了嗎?

Nuget Downloads 20,389,208版本:2026.7剛剛發布

立即獲取您的免費30天試用密鑰
不需要信用卡或建立賬戶

免費試用IronPDF

5分鐘內設定完成

C# PDF DLL

下載DLL

立即下載

或者點擊此處下載Windows安裝程式。

  1. 下載並解壓IronPDF到類似~/Libs的位置,位於您的解決方案目錄中
  2. 在Visual Studio解決方案資源管理器,右鍵點選參考。選擇瀏覽,"IronPdf.dll"
C# 用於PDF的NuGet程式庫

使用NuGet安裝

                  Install-Package IronPdf
                
nuget.org/packages/IronPdf/
  1. 在解決方案資源管理器,右鍵點選參考,管理NuGet包
  2. 選擇瀏覽並搜尋"IronPdf"
  3. 選擇套件並安裝

授權從$999

有問題嗎?聯絡我們的開發團隊。

Key in blue circle

立即免費取得 30 天試用金鑰

bullet_checked無需信用卡或建立帳號
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
預訂您的免費現場演示
Booking Badge related to IronPDF Product Demo

受到全球數百萬工程師的信任

Iron Software的客戶標誌
獲取您的無義務諮詢
填寫以下表格或電子郵件sales@ironsoftware.com
您的詳細資訊將始終保密
受到全球數百萬工程師的信任
Iron Software的客戶標誌
立即獲取您的30天試用金鑰
無需信用卡或帳戶建立