通过回调使用自定义 AI 模型
概述
从 SDK v4.1.0 开始,可通过 ConvertCallback 结构体中的函数指针字段插入自己的 AI 引擎进行 OCR、版面分析和表格识别。所有字段默认为 IntPtr.Zero,此时 SDK 使用内置 DocumentAI 模型。
每种 AI 能力使用触发器/获取器对:
| 能力 | 触发字段 | 结果获取字段 | 触发条件 |
|---|---|---|---|
| OCR | ocr | get_ocr_result | EnableOCR = true |
| 版面分析 | layout | get_layout_result | EnableAiLayout = true 或 EnableOCR = true |
| 表格识别 | table | get_table_result | EnableAiTableRecognition = true 且检测到表格 |
触发器接收 PNG 图像路径(IntPtr UTF-8 字符串),返回 bool;获取器返回 IntPtr 指向 UTF-8 JSON C 字符串。两者必须同时设置。
示例
csharp
using System;
using System.Runtime.InteropServices;
using ComPDF.Conversion;
class Program
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate bool TriggerDelegate(IntPtr imagePath);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate IntPtr GetterDelegate();
static string ocrResult = "{}", layoutResult = "{}", tableResult = "{}";
static bool MyOcr(IntPtr imagePath) { /* 运行 OCR */ return true; }
static IntPtr MyOcrResult() { return Marshal.StringToHGlobalAnsi(ocrResult); }
static bool MyLayout(IntPtr imagePath) { return true; }
static IntPtr MyLayoutResult() { return Marshal.StringToHGlobalAnsi(layoutResult); }
static bool MyTable(IntPtr imagePath) { return true; }
static IntPtr MyTableResult() { return Marshal.StringToHGlobalAnsi(tableResult); }
static void Main()
{
LibraryManager.LicenseVerify("LICENSE_KEY", "device_id", "app_id");
LibraryManager.Initialize("resource");
// 当回调覆盖所有能力时,无需调用 SetDocumentAIModel
ConvertCallback callback = new ConvertCallback();
callback.ocr = Marshal.GetFunctionPointerForDelegate((TriggerDelegate)MyOcr);
callback.get_ocr_result = Marshal.GetFunctionPointerForDelegate((GetterDelegate)MyOcrResult);
callback.layout = Marshal.GetFunctionPointerForDelegate((TriggerDelegate)MyLayout);
callback.get_layout_result = Marshal.GetFunctionPointerForDelegate((GetterDelegate)MyLayoutResult);
callback.table = Marshal.GetFunctionPointerForDelegate((TriggerDelegate)MyTable);
callback.get_table_result = Marshal.GetFunctionPointerForDelegate((GetterDelegate)MyTableResult);
WordOptions options = new WordOptions();
options.EnableOCR = true;
options.EnableAiLayout = true;
CPDFConversion.StartPDFToWord("input.pdf", "", "output.docx", options, callback);
}
}JSON 模式
OCR、版面分析和表格识别的 JSON 模式与 C SDK 相同,请参见 C 指南中的“通过回调使用自定义 AI 模型”。