C#におけるAI利用のPDF処理:IronPDFで文書を要約、抽出、分析する

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

AI駆動のPDF処理は、IronPDFでC#を使用して.NET開発者が既存のPDFワークフローを直接活用して文書を要約し、構造化データを抽出し、質疑応答システムを構築できるようにします。Microsoft Semantic Kernelに基づいて構築されたIronPdf.Extensions.AIパッケージを使用してAzure OpenAIおよびOpenAIモデルと接続します。 あなたが法的発見ツール、財務分析パイプライン、ドキュメントインテリジェンスプラットフォームを構築しているかどうかに関わらず、IronPDFはPDF抽出とコンテキストの準備を行いますので、あなたはAIロジックに集中することができます。

TL;DR: クイックスタート ガイド

このチュートリアルでは、C# .NETでドキュメントの要約、データ抽出、インテリジェントなクエリのためにIronPDFをAIサービスに接続する方法を説明します。

  • 対象者: ドキュメント インテリジェンス アプリケーションを構築する.NET開発者 - 法律発見システム、財務分析ツール、コンプライアンスレビュープラットフォーム、または大量のPDFドキュメントから意味を抽出する必要があるアプリケーションなど。
  • 構築するもの 単一ドキュメントの要約、カスタムスキーマによる構造化JSONデータ抽出、ドキュメントコンテンツに対する質問応答、長いドキュメントのためのRAGパイプライン、ドキュメントライブラリ全体にわたるバッチAI処理ワークフロー。
  • Where it runs: Azure OpenAIまたはOpenAI APIキーがある任意の.NET 6+環境。 AIエクステンションはMicrosoft Semantic Kernelと統合され、コンテキストウィンドウの管理、チャンキング、オーケストレーションを自動的に処理します。
  • 使用するタイミング: テキスト抽出を超えてPDFを処理する必要があるとき - 契約義務の理解、研究論文の要約、構造化データとしての財務表の抽出、またはドキュメントコンテンツに関するユーザーの質問にスケールで答えるとき。
  • 技術的な重要性: 生のテキスト抽出はドキュメントの構造を失い、テーブルが崩れ、多列レイアウトが壊れ、意味的な関係が消える。 IronPDFは構造を保持し、トークンの制限を管理することで、AIが消費するためのドキュメントを準備します。

わずか数行のコードでPDFを要約します:

  1. 1IronPDF を 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";
NuGetNuGet でインストール

PM > Install-Package IronPdf

NuGetパッケージマネージャーコンソールで上記のコマンドを実行するか、NuGetパッケージマネージャーでパッケージを検索して、IronPDFをインストールします。
目次

AI+PDFのチャンス

なぜPDFが最大の未活用データソースなのか

PDFは、現代の企業において最も大きな構造化されたビジネス知識のリポジトリの一つを表しています。プロフェッショナルなドキュメント - 契約書、財務諸表、コンプライアンスレポート、法律の概要、および研究論文 - のほとんどがPDF形式で保存されています。 これらの文書には、義務や負債を定義する契約用語、投資の意思決定を促す財務指標、コンプライアンスを保証する規制要件、戦略の指針となる調査結果など、重要なビジネス情報が含まれています。

しかし、PDF処理に対する従来のアプローチには大きな限界がありました。 基本的なテキスト抽出ツールは、ページから生の文字を抽出することはできますが、重要な文脈を失ってしまいます。表構造が崩れてごちゃごちゃしたテキストになったり、複数カラムのレイアウトが無意味になったり、セクション間の意味的な関係が消えてしまったりします。

画期的なのは、文脈と構造を理解するAIの能力です。 現代のLLMは単なる言葉を見るだけでなく、文書の組織を理解し、契約の条項や財務表のようなパターンを認識し、複雑なレイアウトからも意味を抽出できます。 このチュートリアルで言及されているモデル名は、執筆時に利用可能な主要な世代を反映しています; あなたのプロバイダーから進化するにつれて、それらの現在の同等物に置き換えてください。 例えば、GPT-5の統合推論システムはそのリアルタイムルーターとClaude Sonnet 4.5の強化されたエージェンティック機能はどちらも、初期のモデルと比較して大幅に減少した幻覚率を示し、プロフェッショナルな文書分析に信頼性をもたらします。

LLMsが文書構造を理解する方法

大規模な言語モデルは、PDF分析に高度な自然言語処理機能をもたらします。 GPT-5のハイブリッドアーキテクチャは、複数のサブモデル(メイン、ミニ、シンキング、ナノ)を特徴とし、リアルタイムルーターがタスクの複雑さに基づいて最適なバリアントを動的に選択します - 簡単な質問はより速いモデルにルートされ、複雑な推論タスクはフルモデルを活用します。

Claude Opus 4.6は、分割されたジョブを直接調整するエージェントチームと、チャンキングなしでドキュメントライブラリ全体を処理できる1Mトークンのコンテキストウィンドウを備え、特に長時間実行するエージェントタスクに優れています。

AIモデルがPDF文書構造を解析し要素を識別する方法

このように文脈を理解することで、LLMは真の理解力を必要とする作業を行うことができます。 契約書を分析する際、LLM は「契約解除」という単語を含む条項を特定するだけでなく、契約解除が認められる具体的な条件、関連する通知要件、およびその結果生じる責任を理解することができます。 GPT-5のコンテキストウィンドウは最大272,000の入力トークンをサポートし、Claude Sonnet 4.5の200Kトークンウィンドウは包括的なドキュメントカバレッジを提供します。

IronPDFの組み込みAI統合

IronPDFおよびAI拡張のインストール

AIによるPDF処理を始めるには、IronPDFライブラリのコア、AI拡張パッケージ、Microsoft Semantic Kernelの依存関係が必要です。

NuGetパッケージマネージャを使ってIronPDFをインストールしてください:

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

これらのパッケージは連携して完全なソリューションを提供します。 IronPDFはすべてのPDF関連の操作を処理します - テキスト抽出、ページレンダリング、フォーマット変換 - while 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");

初期化では、2つの重要なコンポーネントを作成します:

  • カーネル: Azure OpenAIを通してチャットの完了とテキスト埋め込み生成を処理します。
  • メモリ: セマンティック検索と検索操作のために、ドキュメントの埋め込みを保存します。

IronDocumentAI.Initialize()で初期化されると、アプリケーション全体でAI機能を使用できます。 本番アプリケーションでは、認証情報を環境変数または Azure Key Vault に保存することを強く推奨します。

IronPDFがAIコンテキストにPDFを準備する方法

AIを活用したPDF処理で最も困難な側面の1つは、言語モデルによって消費される文書を準備することです。 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とクロード・ソネット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処理の最も強力な用途の1つは、非構造化文書から構造化データを抽出することです。 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年の最新の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

ケーススタディを見る

ドキュメント上の質問に対する回答

PDF Q&Aシステムの構築

質問応答システムは、ユーザーが自然言語で質問し、文脈に沿った正確な回答を受け取ることで、PDF文書を会話形式で操作できるようにします。 基本的なパターンは、PDFからテキストを抽出し、プロンプトでユーザーの質問と組み合わせ、AIに回答を求めるというものです。

入力


コードは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年における効果的なQ&Aの鍵は、ドキュメントの内容のみに基づいて回答するようAIを制限することです。 GPT-5の "安全な補完 "トレーニングメソッドとクロード・ソネット4.5の改良されたアライメントにより、幻覚の発生率が大幅に減少しました。

コンテキストウィンドウのための長文書のチャンク化

ほとんどの実世界の文書は、AIのコンテキストウィンドウを超えます。 これらの文書を処理するには、効果的なチャンキング戦略が不可欠です。 チャンキングでは、意味的な一貫性を保ちながら、ドキュメントをコンテキストウィンドウに収まるような小さなセグメントに分割します。

このコードはpdf.Pagesをイテレーションして、DocumentChunkオブジェクトを作成し、文脈の連続性のためにmaxChunkTokensと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による文書分析の強力なパターンを示している。RAGシステムは、文書全体をAIに送り込むのではなく、まず与えられたクエリに関連する部分のみを検索し、次にそれらの部分を回答生成のためのコンテキストとして使用する。

RAGのワークフローには、文書の準備(チャンキングと埋め込みデータの作成)、検索(関連するチャンクの検索)、生成(検索されたチャンクをAI応答のコンテキストとして使用)の3つの主要フェーズがあります。

コードは各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ページからのソースの引用

プロフェッショナルな用途のため、AIの回答は検証可能でなければなりません。 引用のアプローチでは、チャンキングと検索時にチャンクのオリジンに関するメタデータを維持します。 各チャンクには、テキストコンテンツだけでなく、ソースのページ番号、セクションヘッダー、ドキュメント内での位置も格納されます。

入力


コードは引用の指示を伴う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が生成した回答を不透明な出力から透明で検証可能な情報に変換します。 ユーザーは、ソースを確認して回答を確認し、AI支援分析に対する自信を深めることができます。


AIバッチ処理

大規模なドキュメントライブラリの処理

企業の文書処理では、何千、何百万ものPDFが使用されることがよくあります。 スケーラブルなバッチ処理の基本は並列化です。 IronPDFはスレッドセーフであり、干渉することなくPDFの同時処理が可能です。

このコードは、maxConcurrencyを構成してSemaphoreSlimを使用し、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; } = "";

大規模では信頼性のあるエラーハンドリングが重要です。 本番システムでは、指数関数バックオフによる再試行ロジック、失敗したドキュメントの個別のエラーログ、および再開可能な処理が実装されています。

コスト管理とトークン使用

AI API のコストは通常、トークンごとに課金されます。 2026年、GPT-5の価格は入力トークン100万個あたり125ドル、出力トークン100万個あたり10ドルで、クロード・ソネット4.5の価格は入力トークン100万個あたり3ドル、出力トークン100万個あたり15ドルです。 主なコスト最適化戦略は、不要なトークンの使用を最小限に抑えることです。

OpenAIのバッチAPIは、処理時間が長い(最大24時間)代わりに、トークンのコストを50%割引します。 夜間処理や定期的な分析では、バッチ処理により大幅なコスト削減が可能です。

コードは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クラスはSHA256を用いたComputeFileHash()を使用して変更を検出し、その結果を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; }

GPT-5とClaude Sonnet 4.5は、パターンが繰り返される場合に効果的なトークン消費を50-90%削減できる自動プロンプトキャッシングを2026年にも提供します - これは大規模な操作において顕著なコスト節約をもたらします。


実際の利用例

法的発見と契約分析

法的証拠開示では、従来、数十万ページを手作業で確認する若手弁護士の軍隊が必要でした。 AIを活用した証拠開示は、このプロセスを一変させ、関連文書の迅速な特定、自動特権審査、重要な証拠事実の抽出を可能にします。

IronPDFのAI統合により、特権の検出、関連性のスコアリング、問題の特定、重要な日付の抽出といった高度な法務ワークフローが可能になります。 法律事務所では、証拠開示のレビュー時間が70~80%短縮され、小規模なチームで大規模なケースに対応できるようになったと報告しています。

2026年にGPT-5とクロード・ソネット4.5の精度が向上し、幻覚率が減少することで、法律の専門家は、ますます重要な意思決定においてAI支援分析を信頼できるようになります。

財務レポート分析

金融アナリストは、決算報告書、SEC提出書類、アナリスト向けプレゼンテーションからデータを抽出するのに膨大な時間を費やしています。 AIを活用した金融文書処理は、この抽出を自動化し、アナリストがデータ収集ではなく解釈に集中できるようにします。

この例は複数の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; } = "";

投資会社は、AI を活用した分析によって毎日何千もの文書を処理し、アナリストがより広範な市場カバレッジを監視し、新たなビジネスチャンスに迅速に対応できるようにしています。

研究論文の要約

学術研究では、年間数百万件の論文が作成されています。 AIを活用した要約は、研究者が論文の関連性を迅速に評価し、重要な発見を理解し、詳しく読む価値のある論文を特定するのに役立ちます。 効果的な研究の要約は、研究課題を特定し、方法論を説明し、適切な注意書きを添えて主要な調査結果を要約し、結果を文脈の中に配置する必要があります。

研究機関では、AI要約を使用して機関の知識ベースを維持し、新しい出版物を自動的に処理しています。 2026年、GPT-5の科学的推論の向上とクロード・ソネット4.5の分析機能の強化により、学術的要約は新たなレベルの精度に到達します。

政府ドキュメントの処理

政府機関は広範な文書コレクションを作成します - 規則、公的コメント、環境影響声明、裁判資料、監査レポート。 AIを活用した文書処理により、規制遵守分析、環境影響評価、立法追跡など、政府の情報を実用的なものにします。

公的コメントの分析では独特の課題が生じます - 大規模な規制提案が数十万件のコメントを受け取ることがあります。 AIシステムは、トピックごとにコメントを分類し、共通のテーマを特定し、協調的なキャンペーンを検出し、機関の対応を保証する実質的な主張を抽出することができます。

2026年世代のAIモデルは、政府の文書処理に前例のない能力をもたらし、民主主義の透明性と情報に基づいた政策立案を支援します。


トラブルシューティングとテクニカル サポート

一般的なエラーの迅速な解決

  • 最初のレンダリングは遅いですか普通です。 Chromeは2-3秒で初期化され、その後速度が向上します。
  • クラウドの問題 少なくともAzure B1または同等のリソースを使用してください。
  • Missing assets? ベースパスを設定するか、base64として埋め込んでください。
  • 不足している要素 JavaScriptの実行にRenderDelayを追加してください。
  • メモリの問題パフォーマンスを修正するためにIronPDFの最新バージョンにアップデートしてください。
  • フォームフィールドの問題 一意の名前を確保し、最新バージョンに更新してください。

IronPDFを開発したエンジニアから24/5のサポートを受ける

IronPDFは、24/5のエンジニアサポートを提供しています(プレミアムサポートを利用することで24/7に拡張可能)。 HTMLからPDFへの変換やAIの統合でお困りですか? お問い合わせ


次のステップ

AIを活用したPDF処理についてご理解いただけたと思いますので、次のステップとしてIronPDFの幅広い機能をご紹介します。 OpenAI統合ガイドは要約、クエリ、記憶パターンの深いカバーを提供し、テキストと画像の抽出チュートリアルではAI分析前にPDFを前処理する方法を紹介しています。 文書組み立てワークフローに関しては、PDFをマージおよび分割する方法を学んでバッチ処理します。

AI機能を超えて拡張する準備ができたら、完全なPDF編集チュートリアルでは、透かし、ヘッダー、フッター、フォーム、注釈について網羅しています。 代替のAI統合アプローチについては、ChatGPT C#チュートリアルが異なるパターンを示しています。 プロダクションデプロイメントに関しては、AzureデプロイメントガイドではWebAppsとFunctionsのためにカバーされ、C# PDF作成チュートリアルではHTML、URL、 生のコンテンツからPDFを生成する方法を網羅しています。

始める準備はできましたか? 無料の30日間トライアルを開始して、透かしなしで製品をテストし、チームに合わせて拡張する柔軟なライセンス。 AI統合または任意のIronPDF機能についての質問がある場合、当社のエンジニアリングサポートチームが支援します。

よくある質問

IronPDFを使用したC#でのAI搭載PDF処理の主な特徴は何ですか?

IronPDFとC#を使用したAI搭載のPDF処理により、IronPdf.Extensions.AIパッケージを使用して、ドキュメントを要約し、構造化データを抽出し、質疑応答システムを構築することができます。また、Azure OpenAIやOpenAIモデルと統合されています。

IronPDFはドキュメントの要約をどのように処理しますか?

IronPDFは、PDFからテキストを抽出し、AI消費の準備を行い、GPT-5のような言語モデルを使用して簡潔な要約を生成することでドキュメントの要約を行います。開発者は数行のコードでPDFを要約できます。

IronPDFは複数文書の統合に使用できますか?

はい、IronPDFはそれぞれのドキュメントを個別に要約し、その洞察を統合して統一された統合を行うことで複数の文書統合をサポートしています。これは、複数のレポート間での指標比較や契約内の共通条項の識別などに役立ちます。

IronPDFを使用してAIでのPDFデータ抽出を行う利点は何ですか?

IronPDFを使用したAI搭載のデータ抽出により、請求書や財務報告書のような非構造化文書から構造化データをJSON形式に抽出できます。OpenAIモデルを使用してデータが正確に抽出され、文書のコンテキストと形式が保持されるようにします。

IronPDFのAI拡張は長いPDF文書をどのように処理しますか?

IronPDFのAI拡張では、長い文書をコンテキストウィンドウに収まる管理可能なセグメントに分割するチャンクング戦略をサポートしています。これにより、関連情報が保持され、AIモデルによって正確に処理されることが保証されます。

IronPDFは法定文書の分析にどのような能力を提供しますか?

IronPDFは、終了条件、責任、支払条件などの契約条項の特定と分析のための機能を提供します。AIを使用して文書レビューのプロセスを自動化し、法的発見に伴う手作業の負担を大幅に軽減します。

IronPDFを使用してバッチドキュメントライブラリを効率的に処理できますか?

はい、IronPDFはバッチ処理結果をキャッシュするサポートとエラーハンドリングを含めて並行してPDFを処理することにより、バッチドキュメントライブラリを効率的に管理することができます。

IronPDFはAI生成された回答の検証可能性をどのように保証しますか?

IronPDFはPDFページから直接ソースを引用することをサポートし、特定のセクションを参照することでユーザーがAI生成の回答を検証できるようにします。この透明性は、AI支援の文書分析に対する信頼を維持するのに役立ちます。

IronPDFを使用したAI搭載のPDF処理の実世界での使用例は何ですか?

実世界での使用例には、法的調査と契約の分析、財務報告書の分析、コンプライアンスの検証、およびPDFに保存された大量の専門文書からの実行可能な洞察の抽出が含まれます。

IronPDFはMicrosoft Semantic Kernelとどのように統合してAIの機能を強化しますか?

IronPDFはAzure OpenAIとチャット補完やテキスト埋め込み生成といったAI機能を統合するためにMicrosoft Semantic Kernelを使用します。この統合により、.NETアプリケーション内でのAIタスクの処理が簡素化されます。

Ahmadは、C#、Python、およびウェブ技術に強い基盤を持つフルスタック開発者です。彼はスケーラブルなソフトウェアソリューションの構築に深い関心を持ち、デザインと機能が実際のアプリケーションでどのように融合するかを探求することを楽しんでいます。

もっと読む

準備はできましたか?

NuGetダウンロード数 22,321,142バージョン:2026.11ちょうどリリースされました