这是我的过程。我首先必须栅格化 PDF(这可能不是您的要求)
1.) 安装 Ghostcript 9.26 from here 更高版本不支持下一步
2.) 安装 Ghostscript.NET NuGet Install-Package Ghostscript.NET -Version 1.2.1
3.) 安装 Tesseract NuGet Install-Package Tesseract -Version 3.3.0
这是我的 PDF 光栅化例程,使用 Ghostscript.NET
public static List<MemoryStream> GetPdfImages(FileInfo pdfFile, DirectoryInfo workingDir, string fileNamingToken, TextWriter _logger)
{
int desired_x_dpi = 150;
int desired_y_dpi = 150;
string inputPdfPath = pdfFile.FullName;
var streams = new List<MemoryStream>();
using (var rasterizer = new GhostscriptRasterizer())
{
GhostscriptVersionInfo gsVersionInfo = GhostscriptVersionInfo.GetLastInstalledVersion(GhostscriptLicense.GPL | GhostscriptLicense.AFPL, GhostscriptLicense.GPL);
try
{
rasterizer.Open(inputPdfPath, gsVersionInfo, true);
}
catch (Ghostscript.NET.GhostscriptAPICallException exc)
{
_logger.WriteLine("There is an issue with this version of Ghostscript or how Ghostscript was installed. As of Winter 2020, GS 9.26 will work the best with Ghostscript.NET");
}
for (var pageNumber = 1; pageNumber <= rasterizer.PageCount; pageNumber++)
{
var memoryStrm = new MemoryStream();
var img = rasterizer.GetPage(desired_x_dpi, desired_y_dpi, pageNumber);
//save to a memory stream to be returned
img.Save(memoryStrm, System.Drawing.Imaging.ImageFormat.Tiff);
//or save to the file system to see how well it's working
img.Save($"{workingDir.FullName}\\{fileNamingToken}_{pageNumber}.TIF");
_logger.WriteLine($"Image Dimensions: {img.Width} x {img.Height}");
streams.Add(memoryStrm);
}
}
return streams;
}
创建内存流列表后,我选择循环遍历它们并使用 Tesseract 对其中的一个矩形进行 OCR。如果你有很多文件要处理,你不应该一遍又一遍地调用引擎..你应该把它放在其他地方
var _engine = new TesseractEngine("./tessdata", "eng", EngineMode.Default, "letters");
var topHalfPageRect = Rect.FromCoords(1, 1, 1275, 825);//at 150 DPI, get top of 8.5x11 page
for(int i =0;i< _streams.Count;i++)
{
var imgStm = _streams[i];//my list of memorystreams created by Ghostcript 9.26
imgStm.Position = 0;//set memorystream playhead back to start
using (var imageWithText = Pix.LoadTiffFromMemory(imgStm.ToArray()))
{
using (var page = _engine.Process(imageWithText, topHalfPageRect , PageSegMode.SparseText))
{
var text = page.GetText();
var processedText = text.Replace("\n", "").Trim();
Console.WriteLine(processedText);
if (MyRegexPatterns.Pattern1.IsMatch(processedText))
{
Console.WriteLine("*** FOUND IT!! ***");
}
}
}
imgStm.Dispose();//but not matter what, disppose of the stream now
}