PDFium(v135版pdfium.dll)单词搜索结果异常的技术求助
PDFium(v135版pdfium.dll)单词搜索结果异常的技术求助
各位好,我这边遇到个PDFium的棘手问题,想请教下有经验的朋友。我们现在用pdfium.dll(当前版本是135)开发了PDF文本搜索功能,但实际用下来发现,和Adobe产品的搜索结果差异特别大——我们搜出来的结果数量多了好多,其中大部分要么是屏幕外的内容,要么就是完全不存在的匹配项。
更头疼的是,只有那些结构复杂的客户文档才会出现这个问题,可这些文档涉及客户保密,根本没法分享出来。我把我们实现的Search方法核心代码贴在下面,希望大家能帮忙看看代码里有没有潜在问题,或者用你们自己的复杂PDF文档测试下能不能复现这个情况,非常感谢!
核心搜索方法代码
// 基于PDFium v135的文本搜索实现 public IEnumerable<SearchResult> SearchPdfText(IntPtr pdfDoc, string searchKeyword) { if (pdfDoc == IntPtr.Zero || string.IsNullOrWhiteSpace(searchKeyword)) yield break; int pageCount = FPDF_GetPageCount(pdfDoc); for (int pageIdx = 0; pageIdx < pageCount; pageIdx++) { IntPtr pdfPage = FPDF_LoadPage(pdfDoc, pageIdx); if (pdfPage == IntPtr.Zero) { continue; } // 初始化搜索句柄:参数0表示不区分大小写,0表示不匹配整词 IntPtr searchHandle = FPDFText_FindStart(pdfPage, searchKeyword, 0, 0); if (searchHandle == IntPtr.Zero) { FPDF_ClosePage(pdfPage); continue; } // 遍历所有匹配结果 while (FPDFText_FindNext(searchHandle)) { int matchCount = FPDFText_GetMatchCount(searchHandle); for (int matchIdx = 0; matchIdx < matchCount; matchIdx++) { int left = 0, top = 0, right = 0, bottom = 0; FPDFText_GetMatchRect(searchHandle, matchIdx, ref left, ref top, ref right, ref bottom); // 转换PDF的坐标系(PDF以左下角为原点,通常UI以左上角为原点) int pageHeight = FPDF_GetPageHeight(pdfPage); int adjustedTop = pageHeight - top; int adjustedBottom = pageHeight - bottom; yield return new SearchResult { PageNumber = pageIdx + 1, BoundingBox = new Rectangle(left, adjustedTop, right - left, adjustedBottom - adjustedTop) }; } } FPDFText_FindClose(searchHandle); FPDF_ClosePage(pdfPage); } } // 辅助类:存储搜索结果信息 public class SearchResult { public int PageNumber { get; set; } public Rectangle BoundingBox { get; set; } } // 辅助结构体:表示匹配区域的矩形坐标 public struct Rectangle { public int X { get; set; } public int Y { get; set; } public int Width { get; set; } public int Height { get; set; } public Rectangle(int x, int y, int width, int height) { X = x; Y = y; Width = width; Height = height; } }
备注:内容来源于stack exchange,提问作者Marcel Grüger
相关产品推荐
相关产品推荐

