在C#中使用AI处理PDF:总结、提取和分析文档与IronPDF

Ahmad Sohail
Ahmad Sohail
更新: 2026年9月5日

AI驱动的PDF处理通过IronPDF在C#中,让.NET开发者能够总结文档、提取结构化数据,并直接在现有PDF工作流基础上构建问答系统 - 使用基于微软语义内核构建的IronPdf.Extensions.AI包,以连接Azure OpenAI和OpenAI模型。 无论您是在构建法律发现工具、财务分析管道,还是在构建文档智能平台,IronPDF 都能处理 PDF 提取和上下文准备工作,让您专注于人工智能逻辑。

TL;DR:快速入门指南

本教程介绍如何在 C# .NET 中将 IronPDF 连接到人工智能服务,以进行文档汇总、数据提取和智能查询。

  • 适用于: 构建文档智能应用程序的.NET开发者 - 如法律调查系统、金融分析工具、合规审查平台,或任何需要从大量PDF文档中提取语义的应用程序。
  • 您将构建的内容:单文档摘要、使用自定义模式的结构化 JSON 数据提取、文档内容的问题解答、长文档的 RAG 管道以及跨文档库的批量人工智能处理工作流。
  • 运行环境:任何具有 Azure OpenAI 或 OpenAI API 密钥的 .NET 6+ 环境。 人工智能扩展与 Microsoft Semantic Kernel 集成,可自动处理上下文窗口管理、分块和协调。
  • 使用此方法的时机: 当您的应用程序需要处理PDF超越文本提取 - 例如理解合同义务、总结研究论文、将财务表格提取为结构化数据,或回答用户关于文档内容的大规模问题。
  • 技术上的重要性: 原始文本提取会丢失文档结构 - 表格会崩溃,多栏布局会破坏,语义关系消失。 IronPDF 通过保留结构和管理标记限制来为人工智能消费准备文档,因此模型会收到干净、有条理的输入。

用几行代码概括 PDF:

  1. 1使用 IronPDF 安装 NuGet Package Manager

    PM > Install-Package IronPdf

  2. 2复制并运行这段代码。

    await IronPdf.AI.PdfAIEngine.Summarize("contract.pdf", "summary.txt", azureEndpoint, azureApiKey);
  3. 3部署到您的生产环境中进行测试

    今天就用免费试用在您的项目中开始使用IronPDF
    arrow pointer

购买或注册 IronPDF 30 天试用版后,请在应用程序的开头添加许可证密钥。

IronPdf.License.LicenseKey = "KEY";
NuGet使用NuGet安装

PM > Install-Package IronPdf

通过在 NuGet 包管理器控制台中运行上述命令安装 IronPDF,或在 NuGet 包管理器中搜索该包。
目录

AI + PDF机会

PDF为何是最大的未开发数据来源

PDF是现代企业中结构化商业知识的最大储库之一。专业文档 - 如合同、财务报表、合规报告、法律简报和研究论文 - 主要以PDF格式存储。 这些文件包含重要的商业情报:定义义务和责任的合同条款、推动投资决策的财务指标、确保合规的监管要求以及指导战略的研究成果。

然而,传统的 PDF 处理方法受到严重限制。 基本的文本提取工具可以从页面中提取原始字符,但它们会丢失关键的上下文:表格结构会坍塌成杂乱无章的文本,多栏布局会变得毫无意义,章节之间的语义关系也会消失。

人工智能能够理解上下文和结构,这是一个突破。 现代LLM不仅只是看到文字 - 它们还能理解文档的组织结构,识别合同条款或财务表格等模式,甚至能从复杂布局中提取意义。 在本教程中引用的模型名称反映了在撰写时最新的领先一代; 根据提供商的演变替换相应的当前等效物。 例如,GPT-5的统一推理系统及其实时路由器和Claude Sonnet 4.5的增强代理能力均表明,与早期模型相比,幻想率大幅降低,使其在专业文档分析中更可靠。

LLM如何理解文档结构

大型语言模型为 PDF 分析带来了复杂的自然语言处理能力。 GPT-5的混合架构具有多个子模型(主模型、小型、思维、纳米模型)及一个实时路由器,可根据任务复杂性动态选择最佳变体 - 简单问题路由到更快的模型,而复杂推理任务则使用完整模型。

Claude Opus 4.6 尤其擅长长时间运行的代理任务,其代理团队可直接协调分段作业,100 万标记的上下文窗口可处理整个文档库,无需分块。

AI模型如何分析PDF文档结构并识别元素

这种对上下文的理解使 LLM 能够完成需要真正理解的任务。 在分析合同时,LLM不仅能识别包含 "终止 "一词的条款,还能理解允许终止的具体条件、涉及的通知要求以及由此产生的责任。 实现这一功能的技术基础是为现代 LLM 提供动力的转换器架构,GPT-5 的上下文窗口可支持多达 272,000 个输入令牌,而 Claude Sonnet 4.5 的 200K 令牌窗口可提供全面的文档覆盖。

IronPDF的内置AI集成

安装IronPDF和AI扩展

开始使用人工智能驱动的 PDF 处理需要 IronPDF 核心库、人工智能扩展包和 Microsoft Semantic Kernel 依赖项。

使用 NuGet 软件包管理器安装 IronPDF:

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

这些软件包可共同提供完整的解决方案。 IronPDF处理所有与PDF相关的操作 - 文本提取、页面渲染、格式转换 - 而AI扩展通过微软语义内核管理与语言模型的集成。

请注意: Semantic Kernel软件包包含实验性API。添加<NoWarn>$(NoWarn);SKEXP0001;SKEXP0010;SKEXP0050</NoWarn>到您的.csproj的PropertyGroup中以抑制编译器警告。

配置您的OpenAI/Azure API密钥

在利用人工智能功能之前,您需要配置访问人工智能服务提供商的权限。 IronPDF 的人工智能扩展支持 OpenAI 和 Azure OpenAI。 Azure OpenAI 通常是企业应用程序的首选,因为它提供了增强的安全功能、合规认证以及在特定地理区域内保存数据的能力。

要配置 Azure OpenAI,您需要从 Azure 门户获取用于聊天和嵌入模型的 Azure 端点 URL、API 密钥和部署名称。

初始化AI引擎

IronPDF 的人工智能扩展在引擎盖下使用 Microsoft Semantic Kernel。 在使用任何人工智能功能之前,您必须使用 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 处理聊天完成和文本嵌入生成
  • 内存:存储文档嵌入,用于语义搜索和检索操作

一旦通过IronDocumentAI.Initialize()初始化,您可以在整个应用程序中使用AI功能。 对于生产应用程序,强烈建议将凭证存储在环境变量或 Azure Key Vault 中。

IronPDF如何为AI上下文准备PDF

人工智能驱动的 PDF 处理中最具挑战性的一个方面是准备文档供语言模型使用。 虽然 GPT-5 支持多达 272,000 个输入标记,Claude Opus 4.6 现在也提供了 1M 标记上下文窗口,但一份法律合同或财务报告仍然很容易超过旧型号的限制。

IronPDF 的人工智能扩展通过智能文档准备处理这种复杂性。 当您调用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

人工智能驱动的 PDF 处理最强大的应用之一是从非结构化文档中提取结构化数据。 2026 年结构化提取成功的关键是使用具有结构化输出模式的 JSON 模式。 GPT-5 引入了改进的结构化输出,而 Claude Sonnet 4.5 则为可靠的数据提取提供了增强的工具协调功能。

输入


代码使用JSON模式提示调用pdf.Query(),然后使用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 年的现代人工智能模型支持结构化输出模式,可保证符合所提供模式的有效 JSON 响应。 这样就不需要对畸形响应进行复杂的错误处理。

合同条款识别

法律合同包含一些特别重要的特定类型条款:终止条款、责任限制、赔偿要求、知识产权转让和保密义务。 人工智能驱动的条款识别可自动进行分析,同时保持高准确性。

此示例使用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驱动的解析在处理财务文件方面表现出色,因为它理解上下文 - 区分历史结果与前景预测,识别数字是以千还是百万为单位,并理解不同指标之间的关系。

代码使用pdf.Query()及财务JSON架构将损益表数据、资产负债表指标及前瞻指导提取为结构化输出。

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 的人工智能集成完全支持自定义提取提示,允许您准确定义应该提取哪些信息以及信息的结构。

此示例展示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);
}

自定义提示将人工智能驱动的提取从通用工具转变为针对您的特定需求量身定制的专业解决方案。


我最喜欢的这种库是 IronPDF。它允许快速高效地操作 PDF 文件。它还具有许多有价值的功能,比如导出为 PDF/A 格式和数字签名 PDF 文档。

Milan Jovanovic

微软MVP

查看案例研究

IronOCR 意味着我们每年可以节省 $40,000 的人工处理成本,同时提高生产力,并释放资源用于高影响任务。我强烈推荐它。

Brent Matzelle

首席技术官,OPYN

查看案例研究

文档上的问答

构建PDF问答系统

问题解答系统使用户能够与 PDF 文档进行对话式交互,用自然语言提出问题并获得准确的上下文答案。 基本模式包括从 PDF 中提取文本,在提示中将文本与用户的问题相结合,然后请求人工智能给出答案。

输入


代码调用pdf.Memorize()对文档进行语义搜索索引,然后使用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 年有效问答的关键在于限制人工智能仅根据文档内容进行回答。 GPT-5 的 "安全完成 "训练方法和 Claude Sonnet 4.5 改进的对齐方式大大降低了幻听率。

长文档对上下文窗口的分块

现实世界中的大多数文档都超出了 AI 上下文窗口的范围。 有效的分块策略对于处理这些文档至关重要。 分块是指将文档分成足够小的片段,以适应上下文窗口,同时保持语义的连贯性。

此代码迭代pdf.Pages,创建具有可配置maxChunkTokens和overlapTokens的DocumentChunk对象以保持上下文连续性。

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文档的固定分块与语义分块

重叠的语块提供了跨边界的连续性,即使相关信息跨越语块边界,也能确保人工智能有足够的上下文。

RAG(检索增强生成)模式

检索-增强生成是 2026 年人工智能驱动的文档分析的一种强大模式。RAG 系统不是将整个文档提供给人工智能,而是首先检索特定查询的相关部分,然后将这些部分作为生成答案的上下文。

RAG 工作流程有三个主要阶段:文档准备(分块和创建嵌入)、检索(搜索相关块)和生成(使用检索到的块作为人工智能响应的上下文)。

代码通过在每个PDF上调用pdf.Memorize()索引多个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页面来源

对于专业应用,人工智能答案必须是可验证的。 引用方法包括在分块和检索过程中维护有关分块来源的元数据。 每个语块不仅存储文本内容,还存储其源页码、章节标题和在文档中的位置。

输入


代码使用带引用说明的pdf.Query(),然后调用带有正则表达式的ExtractCitedPages()解析页面引用,并使用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();
}

控制台输出

控制台输出显示带有页面引用的AI答案从PDF

引用将人工智能生成的答案从不透明性输出转化为透明、可验证的信息。 用户可以查看源材料来验证答案,并建立对人工智能辅助分析的信心。


批量AI处理

大规模处理文档库

企业文档处理通常涉及数千或数百万个 PDF。 可扩展批处理的基础是并行化。 IronPDF 是线程安全的,允许不受干扰地并发处理 PDF。

此代码使用可配置maxConcurrency的SemaphoreSlim来并行处理PDF,对每个PDF调用pdf.Summarize()并在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; } = "";

可靠的错误处理在大规模处理中至关重要。 生产系统采用指数式回退重试逻辑、失败文档的单独错误日志记录以及可恢复处理。

成本管理与代币使用

人工智能应用程序接口费用通常按令牌收取。 2026 年,GPT-5 的价格为每百万输入代币 1.25 美元,每百万输出代币 10 美元,而 Claude Sonnet 4.5 的价格为每百万输入代币 3 美元,每百万输出代币 15 美元。 主要的成本优化策略是尽量减少不必要的标记使用。

OpenAI 的批量 API 提供 50% 的令牌费用折扣,以换取更长的处理时间(最长 24 小时)。 对于隔夜处理或定期分析,批处理可节省大量成本。

代码使用pdf.ExtractAllText()提取文本,创建JSONL批量请求,通过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 的哈希值一起存储,从而避免对未更改的文档进行不必要的重新处理。

DocumentCacheManager类使用ComputeFileHash()与SHA256检测更改,将结果存储在具有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%用于重复模式 - 这对于大规模操作而言是显著的成本节约。


真实的使用案例

法律发现与合同分析

法律取证传统上需要大量初级律师手动审阅成千上万页的文件。 人工智能驱动的发现转变了这一流程,能够快速识别相关文件、自动审查特权并提取关键证据事实。

IronPDF 的人工智能集成实现了复杂的法律工作流程:特权检测、相关性评分、问题识别和关键日期提取。 律师事务所报告称,发现审查时间缩短了 70-80%,使他们能够以较小的团队处理较大的案件。

2026 年,随着 GPT-5 和 Claude Sonnet 4.5 的准确性提高和幻听率降低,法律专业人士可以信赖人工智能辅助分析,做出越来越关键的决策。

财务报告分析

金融分析师花费大量时间从收益报告、美国证券交易委员会文件和分析师演示文稿中提取数据。 人工智能驱动的金融文档处理可自动完成提取工作,使分析人员能够专注于解释而非数据收集。

此示例处理多个10-K文档,使用带有CompanyFinancials JSON模式的pdf.Query()提取并比较公司间的收入、利润率和风险因素。

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; } = "";

投资公司使用人工智能分析技术每天处理成千上万份文件,使分析师能够监控更广泛的市场覆盖范围,更快地应对新出现的机遇。

研究论文总结

学术研究每年产生数百万篇论文。 由人工智能驱动的摘要可帮助研究人员快速评估论文相关性、了解关键研究结果并确定需要详细阅读的论文。 有效的研究总结必须明确研究问题、解释研究方法、总结主要发现并提出适当的注意事项,并将结果置于上下文中。

研究机构使用人工智能摘要维护机构知识库,自动处理新出版物。 2026 年,随着 GPT-5 科学推理能力的提高和 Claude Sonnet 4.5 分析能力的增强,学术总结的准确性将达到新的水平。

政府文档处理

政府机构制作大量文档集合 - 如规定、公众评论、环境影响声明、法院文件、审计报告。 人工智能驱动的文档处理通过合规性分析、环境影响评估和立法跟踪,使政府信息具有可操作性。

公众评论分析面临独特挑战 - 大型监管提案可能收到数十万条评论。 人工智能系统可以按主题对评论进行分类,识别共同的主题,检测协调的活动,并提取值得机构回应的实质性论点。

2026 代人工智能模型为政府文件处理带来了前所未有的能力,支持民主透明和知情决策。


故障排除与技术支持

快速解决常见错误

  • 首次呈现速度慢?正常。 Chrome 2-3秒内初始化,然后加速。
  • 云问题? 至少使用 Azure B1 或同等资源。
  • 缺少资产?设置基本路径或嵌入为 base64。
  • 缺少元素?为 JavaScript 的执行添加 RenderDelay。
  • 内存问题?更新到最新的 IronPDF 版本以修复性能问题。
  • 表格字段问题?确保名称唯一并更新到最新版本。

从构建IronPDF的工程师那里获得帮助,24/5

IronPDF提供24/5工程师支持(通过高级支持可提供24/7)。 在将 HTML 转换为 PDF 或集成 AI 时遇到困难? 请联系我们:


下一步

现在您已经了解了人工智能驱动的 PDF 处理,下一步就是探索 IronPDF 更广泛的功能。 OpenAI集成指南提供了关于总结、查询和记忆化模式的更深入覆盖,而文本和图像提取教程显示了如何在AI分析之前对PDF进行预处理。 对于文档组装工作流,学习如何合并和拆分PDF以进行批处理。

当您准备扩展到超出AI功能时,完整的PDF编辑教程涵盖了水印、标题、页脚、表单和注释。 对于替代的AI集成方法,ChatGPT C#教程展示了不同的模式。 生产部署在Azure部署指南中涵盖了WebApps和功能,C# PDF创建教程涵盖了从HTML、URL和原始内容生成PDF。

准备好开始了吗? 开始您的免费30天试用以在生产中无水印测试,并享有随您的团队扩展的灵活许可。 对于AI集成或任何IronPDF功能的疑问,我们的工程支持团队随时为您提供帮助。

常见问题

AI驱动的C#中的PDF处理与IronPDF的关键特性是什么?

AI驱动的C#中的PDF处理与IronPDF让开发者可以使用IronPdf.Extensions.AI包来总结文档、提取结构化数据及构建问答系统。它与Azure OpenAI和OpenAI模型集成。

IronPDF如何处理文档摘要?

IronPDF通过从PDF中提取文本,为AI消费准备,并使用如GPT-5等语言模型生成简明摘要来处理文档摘要。开发者只需几行代码即可汇总PDF。

IronPDF可以用于多文档合成吗?

可以,IronPDF支持通过分别总结每个文档并聚合这些见解来进行多文档合成。这适用于比较多个报告中的指标或识别合同中的常见条款等应用。

使用AI为IronPDF进行PDF数据提取的优势是什么?

使用AI支持的数据提取,IronPDF能够从诸如发票和财务报告的不结构化文档中提取结构化数据至JSON格式。它使用OpenAI模型确保数据提取的准确性,同时保持文档的上下文和格式。

IronPDF的AI扩展如何处理长PDF文档?

IronPDF的AI扩展支持切割策略,将长文档分割成适合上下文窗口的可管理片段。这样可以确保相关信息得到保留并被AI模型准确处理。

IronPDF为法律文档分析提供了哪些功能?

IronPDF提供识别和分析合同条款功能,如终止条件、责任和付款条款。它使用AI自动化文件审阅过程,大大减少了法律发现中的人工工作量。

IronPDF可以有效处理批量文档库吗?

可以,IronPDF可以通过并行处理来处理文档库中的批量操作,并支持错误处理和结果缓存。这使大规模文档处理任务的管理更加高效。

IronPDF如何确保AI生成答案的可验证性?

IronPDF支持直接从PDF页面引用来源,允许用户通过参考特定部分来验证AI生成的答案。这种透明性有助于维护对AI辅助文档分析的信任。

AI驱动的PDF处理与IronPDF的一些实际应用案例是什么?

实际应用案例包括法律发现和合同分析、财务报告分析、合规性验证,以及从大量存储于PDF的专业文档中提取可操作的洞察。

IronPDF如何与Microsoft Semantic Kernel集成以增强AI能力?

IronPDF利用Microsoft Semantic Kernel与Azure OpenAI集成了如聊天完成和文本嵌入生成等AI功能。此集成简化了.NET应用程序中复杂AI任务的处理。

Ahmad 是一名全栈开发人员,拥有扎实的 C#、Python 和 Web 技术基础。他对构建可扩展的软件解决方案深感兴趣,并喜欢探索设计和功能在实际应用中如何结合。

阅读更多

准备开始了吗?

NuGet 下载量 22,321,142版本:2026.11刚刚发布