Files
ctbjrj/pdfbt/SelfTest.cs
T

100 lines
4.3 KiB
C#

// ============================================================
// SelfTest:命令行自检(--selftest <pdf> [outdir])
// 无 UI 验证:pdfium 渲染 → PNG 落盘;OCR 工作进程识别 → JSON 落盘
// 用法:pdfbt.exe --selftest test.pdf .
// 返回码:0 成功;1 失败
// ============================================================
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace pdfbt
{
internal static class SelfTest
{
public static int Run(string[] args)
{
string pdf = args[1];
string outDir = args.Length >= 3 ? args[2] : ".";
var log = new StringBuilder();
int exit = 0;
try
{
// 1) pdfium 渲染
string renderPath = Path.Combine(outDir, "selftest_render.png");
Bitmap page;
using (var doc = new PdfDocument())
{
doc.Open(pdf, null);
log.AppendLine("[render] 打开成功: " + pdf + " 页数=" + doc.PageCount);
page = doc.RenderPage(0, 1.5f);
if (page == null) throw new Exception("渲染返回 null");
}
using (page)
{
page.Save(renderPath, ImageFormat.Png);
log.AppendLine("[render] 已保存: " + renderPath +
" (" + page.Width + "x" + page.Height + ")");
// 2) OCR(渲染图上半区)
var crop = new Bitmap(page.Width, page.Height / 2,
System.Drawing.Imaging.PixelFormat.Format24bppRgb);
using (var g = Graphics.FromImage(crop))
{
g.DrawImage(page, new Rectangle(0, 0, crop.Width, crop.Height),
new Rectangle(0, 0, page.Width, page.Height / 2), GraphicsUnit.Pixel);
}
using (var ocr = new OcrClient())
{
var items = ocr.RecognizeAsync(crop, 180000).Result;
var json = new StringBuilder();
json.AppendLine("{");
json.AppendLine(" \"count\": " + (items == null ? 0 : items.Count) + ",");
json.AppendLine(" \"items\": [");
if (items != null)
{
for (int i = 0; i < items.Count; i++)
{
var it = items[i];
var b = it.Bounds;
json.AppendLine(" {\"text\": \"" +
(it.Text ?? "").Replace("\\", "\\\\").Replace("\"", "\\\"") +
"\", \"score\": " + it.Score.ToString("0.000") +
", \"bounds\": [" + b.X.ToString("0") + "," + b.Y.ToString("0") +
"," + b.Width.ToString("0") + "," + b.Height.ToString("0") + "]}" +
(i < items.Count - 1 ? "," : ""));
}
}
json.AppendLine(" ]");
json.AppendLine("}");
string ocrPath = Path.Combine(outDir, "selftest_ocr.json");
File.WriteAllText(ocrPath, json.ToString(), new UTF8Encoding(false));
log.AppendLine("[ocr] 识别 " + (items == null ? 0 : items.Count) +
" 条,已保存: " + ocrPath);
if (items != null)
{
foreach (var it in items)
log.AppendLine(" - " + it.Text);
}
}
}
}
catch (Exception ex)
{
log.AppendLine("[FAIL] " + ex);
exit = 1;
}
string resultPath = Path.Combine(outDir, "selftest_result.txt");
File.WriteAllText(resultPath, log.ToString(), new UTF8Encoding(false));
Console.Out.WriteLine(log.ToString());
return exit;
}
}
}