using ComPDFKit.Import; using ComPDFKit.PDFAnnotation; using ComPDFKit.PDFDocument; using ComPDFKit.PDFPage; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace TextSearchTest { internal class TextSearch { static private string outputPath = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory()))) + "\\Output\\TextSearch"; static void Main(string[] args) { Console.WriteLine("Running text search test sample…\r\n"); if (!Directory.Exists(outputPath)) { Directory.CreateDirectory(outputPath); } SDKLicenseHelper.LicenseVerify(); CPDFDocument document = CPDFDocument.InitWithFilePath("Text.pdf"); SearchText(document); Console.WriteLine("--------------------"); Console.WriteLine("Done"); Console.WriteLine("--------------------"); Console.ReadLine(); } static void SearchForPage(CPDFPage page, string searchKeywords, C_Search_Options option, ref List rects, ref List strings) { rects = new List(); strings = new List(); int findIndex = 0; CPDFTextPage textPage = page.GetTextPage(); CPDFTextSearcher searcher = new CPDFTextSearcher(); if (searcher.FindStart(textPage, searchKeywords, option, 0)) { CRect textRect = new CRect(); string textContent = ""; while (searcher.FindNext(page, textPage, ref textRect, ref textContent, ref findIndex)) { strings.Add(textContent); rects.Add(new Rect(textRect.left, textRect.top, textRect.width(), textRect.height())); } } } static private bool HighlightTheFirstResult(CPDFPage page, Rect rect) { List cRectList = new List(); cRectList.Add(new CRect((float)rect.Left, (float)rect.Top, (float)rect.Right, (float)rect.Bottom)); CPDFHighlightAnnotation annotation = page.CreateAnnot(C_ANNOTATION_TYPE.C_ANNOTATION_HIGHLIGHT) as CPDFHighlightAnnotation; byte[] color = { 0, 255, 0 }; annotation.SetColor(color); annotation.SetTransparency(120); annotation.SetQuardRects(cRectList); annotation.UpdateAp(); return true; } static private bool SearchText(CPDFDocument document) { CPDFPage page = document.PageAtIndex(0); List rects = new List(); List strings = new List(); SearchForPage(page, "PDF", C_Search_Options.Search_Case_Insensitive, ref rects, ref strings); Console.WriteLine("the key PDF have {0} results", rects.Count); Console.WriteLine("Search finished, now highlight the first result. "); HighlightTheFirstResult(page, rects[0]); string path = outputPath + "\\HighlightFirstTest.pdf"; if (!document.WriteToFilePath(path)) { return false; } Console.WriteLine("Browse the changed file in " + path); return true; } } }