프로젝트

일반

사용자정보

통계
| 브랜치(Branch): | 개정판:

markus / KCOM / Controls / SearchPanel.xaml.cs @ 9380813b

이력 | 보기 | 이력해설 | 다운로드 (18.6 KB)

1
using Bytescout.PDFExtractor;
2
using KCOM.Common;
3
using MarkupToPDF.Common;
4
using System;
5
using System.Collections.Generic;
6
using System.ComponentModel;
7
using System.Diagnostics;
8
using System.Linq;
9
using System.Text;
10
using System.Threading;
11
using System.Threading.Tasks;
12
using System.Windows;
13
using System.Windows.Controls;
14
using System.Windows.Data;
15
using System.Windows.Documents;
16
using System.Windows.Input;
17
using System.Windows.Media;
18
using System.Windows.Media.Imaging;
19
using System.Windows.Navigation;
20
using System.Windows.Shapes;
21
using Telerik.Windows.Controls;
22
using Telerik.Windows.Controls.Rating;
23

    
24
namespace KCOM.Controls
25
{
26
    public class SearchText
27
    {
28
        public Bytescout.PDFExtractor.ISearchResult searchResult { get; set; }
29
        public int PageNo { get; set; }
30
    }
31
    /// <summary>
32
    /// Interaction logic for SearchPanel.xaml
33
    /// </summary>
34
    public partial class SearchPanel : UserControl
35
    {
36
        //List<HoneyheadTEXT> txtSet = new List<HoneyheadTEXT>();
37
        public System.Collections.ObjectModel.ObservableCollection<SearchText> SearchSet { get; set; }
38
        string RegistrationKey = "193B-FD48-42F4-68E6-2D35-4C94-D07";
39
        string RegistrationName = "license@doftech.co.kr";
40
        Bytescout.PDFExtractor.TextExtractor extractor;
41
        //Bytescout.PDFExtractor.OCRAnalyzer ocrAnalyzer;
42
        private BackgroundWorker worker = new BackgroundWorker();
43
        private bool IsCancelWork = false;
44

    
45
        public SearchPanel()
46
        {
47
            App.splashString(ISplashMessage.SEARCHPANEL);
48
            InitializeComponent();
49
            LibInit();
50
            //this.Loaded += SearchPanel_Loaded;
51
            btnSearch.Click += BtnSearch_Click;
52
            btnSearchPDFDownload.Click += BtnSearchPDFDownload_Click;
53
            SearchSet = new System.Collections.ObjectModel.ObservableCollection<SearchText>();
54

    
55
            tbSearch.KeyDown += tbSearch_KeyDown;
56

    
57
            worker.DoWork += Worker_DoWork;
58
            worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
59

    
60
            this.DataContext = this;
61
            /*
62
            if (Common.ViewerDataModel.Instance.searchPDF ==null)
63
            {
64

    
65
            }
66
            else
67
            {
68
                border_Overlap.Visibility = Visibility.Collapsed;
69
                tbSearch.Focus();
70
                
71
            }
72
            */
73

    
74
            if (ViewerDataModel.Instance.IsDownloadOriginal)
75
            {
76
                SetSerachPDFFile(ViewerDataModel.Instance.OriginalTempFile);
77
            }
78
        }
79

    
80
        private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
81
        {
82
            Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate
83
            {
84
                btnSearch.Content = "Search";
85
                IsCancelWork = false;
86

    
87
                this.searchIndicator.IsIndeterminate = false;
88

    
89
                //Debuging용 데이터 
90
                //SearchSet.Add(new SearchText() { PageNo = 1, searchResult = null });
91
                //SearchSet.Add(new SearchText() { PageNo = 2, searchResult = null });
92
                //SearchSet.Add(new SearchText() { PageNo = 3, searchResult = null });
93
                //SearchSet.Add(new SearchText() { PageNo = 4, searchResult = null });
94

    
95
                this.DataContext = this;
96
                //tbSearch.Text = "";
97
                tbSearch.Focus();
98

    
99
                txtSearchMsg.Text = "search has completed.";
100
            }));
101
        }
102
        //private System.Collections.ObjectModel.ObservableCollection<SearchText> searchTexts = null;
103
        private void Worker_DoWork(object sender, DoWorkEventArgs e)
104
        {
105
            string searchString = string.Empty;
106
            bool pageoption = false;
107

    
108
            Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate
109
            {
110
                SearchSet.Clear();
111
                searchString = tbSearch.Text;
112
                pageoption = chkCurrentPageOnly.IsChecked.Value;
113
            }));
114

    
115
            extractor.LoadDocumentFromFile(Common.ViewerDataModel.Instance.searchPDF.FullName);
116
            extractor.RegexSearch = true;
117

    
118
            //ocrAnalyzer.LoadDocumentFromFile(Common.ViewerDataModel.Instance.searchPDF.FullName);
119

    
120
            if (pageoption)
121
            {
122
                var currentPage = Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.pageNavigator.CurrentPage.PageNumber - 1;
123

    
124
                //Bytescout.PDFExtractor.OCRAnalysisResults analysisResults = ocrAnalyzer.AnalyzeByOCRConfidence(currentPage);
125
                //ocrAnalyzer.ApplyResults(analysisResults, extractor);
126

    
127
                if (extractor.Find(currentPage, searchString, false))
128
                    do
129
                    {
130
                        Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate
131
                        {
132
                            SearchSet.Add(new SearchText { PageNo = currentPage + 1, searchResult = extractor.FoundText });
133
                        }));
134
                    }
135
                    while (extractor.FindNext());
136
            }
137
            else
138
            {
139
                int pageCount = extractor.GetPageCount();
140

    
141
                for (int i = 0; i < pageCount; i++)
142
                {
143
                    txtSearchMsg.Dispatcher.Invoke(()=> txtSearchMsg.Text = $"Search Pages {i + 1}/{pageCount}");
144

    
145
                    //Bytescout.PDFExtractor.OCRAnalysisResults analysisResults = ocrAnalyzer.AnalyzeByOCRConfidence(i);
146
                    //ocrAnalyzer.ApplyResults(analysisResults, extractor);
147
                    if (extractor.Find(i, searchString, false))
148
                        do
149
                        {
150
                            Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate
151
                            {
152
                                SearchSet.Add(new SearchText { PageNo = i + 1, searchResult = extractor.FoundText });
153
                            }));
154

    
155
                            if(IsCancelWork)
156
                            {
157
                                break;
158
                            }
159
                        }
160
                        while (extractor.FindNext());
161

    
162
                    if (IsCancelWork)
163
                    {
164
                        break;
165
                    }
166
                }
167
            }
168
        }
169

    
170
        private void tbSearch_KeyDown(object sender, KeyEventArgs e)
171
        {
172
            if (e.Key == Key.Enter)
173
            {
174
                SearchMethod();
175
            }
176
        }
177
        private void LibInit()
178
        {
179
            try
180
            {
181
                extractor = new Bytescout.PDFExtractor.TextExtractor(RegistrationName, RegistrationKey);
182
                //ocrAnalyzer = new Bytescout.PDFExtractor.OCRAnalyzer(RegistrationName, RegistrationKey);
183
                extractor.OCRMode = Bytescout.PDFExtractor.OCRMode.Off;
184
                //extractor.OCRLanguage = "eng";
185
                //extractor.OCRLanguageDataFolder = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "tessdata");
186
                
187
                extractor.OCRResolution = 100;
188

    
189
                //ocrAnalyzer.OCRLanguage = "eng";
190
                //ocrAnalyzer.OCRLanguageDataFolder = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "tessdata");
191

    
192
            }
193
            catch (Exception ex)
194
            {
195
                //Logger.sendResLog("LibInit", ex.Message, 0);
196
            }
197

    
198
        }
199

    
200
        private void SearchPanel_Loaded(object sender, RoutedEventArgs e)
201
        {
202
            ////
203
            /// 이벤트 안 들어옴
204

    
205

    
206
            //측정
207
            //Stopwatch sw = new Stopwatch();
208
            //sw.Start();
209
            InitializeComponent();
210
            //System.Diagnostics.Debug.WriteLine("SearchPanel() : " + sw.ElapsedMilliseconds.ToString() + "ms");
211

    
212
            btnSearch.Click += BtnSearch_Click;
213
            btnSearchPDFDownload.Click += BtnSearchPDFDownload_Click;
214
            SearchSet = new System.Collections.ObjectModel.ObservableCollection<SearchText>();
215
            extractor = new Bytescout.PDFExtractor.TextExtractor(RegistrationName, RegistrationKey);
216
            tbSearch.KeyDown += tbSearch_KeyDown;
217

    
218
            this.DataContext = this;
219

    
220
        }
221

    
222
        private void BtnSearchPDFDownload_Click(object sender, RoutedEventArgs e)
223
        {
224
            try
225
            {
226
                Common.ViewerDataModel.Instance.IsDownloadCancel = true;
227

    
228

    
229
                using (System.Net.WebClient client = new System.Net.WebClient())
230
                {
231
                    string instnaceFile = System.IO.Path.GetTempFileName().Replace(".pdf", ".tmp");
232
                    client.DownloadFileCompleted += Client_DownloadFileCompleted;
233
                    client.DownloadProgressChanged += Client_DownloadProgressChanged;
234
                    string downloadurl = Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.GetOriginalPDFURL();
235

    
236
                    client.DownloadFileAsync(new Uri(downloadurl), instnaceFile);
237
                }
238
            }
239
            catch (Exception ex)
240
            {
241
                //Logger.sendResLog("DownloadOriginalFileAsync", ex.Message, 0);
242
            }
243
        }
244

    
245

    
246
        private void Client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
247
        {
248
            SetSerachPDFFile(e.UserState.ToString());
249
        }
250

    
251
        public void SetSerachPDFFile(string FileFullPath)
252
        {
253
            border_Overlap.Visibility = Visibility.Collapsed;
254
            Common.ViewerDataModel.Instance.searchPDF = new System.IO.FileInfo(FileFullPath);
255
            //OcrAnalyzer();
256

    
257
            tbSearch.Focus();
258
        }
259

    
260
        //private void OcrAnalyzer()
261
        //{
262
        //    System.Drawing.RectangleF rectangle = System.Drawing.RectangleF.Empty;
263

    
264
        //    // Display analysis progress
265
        //    ocrAnalyzer.ProgressChanged += (object sender, string message, double progress, ref bool cancel)=>
266
        //    {
267
        //        System.Diagnostics.Debug.WriteLine(message);
268
        //    };
269

    
270
        //    // Load document to OCRAnalyzer
271
        //    ocrAnalyzer.LoadDocumentFromFile(Common.ViewerDataModel.Instance.searchPDF.FullName);
272

    
273
        //    // Set page area for analysis (optional)
274
        //    ocrAnalyzer.SetExtractionArea(rectangle);
275

    
276
        //    // Perform analysis and get results
277
        //    Bytescout.PDFExtractor.OCRAnalysisResults analysisResults = ocrAnalyzer.AnalyzeByOCRConfidence(0);
278

    
279
        //    // Now extract the text using detected OCR parameters
280

    
281
        //    string outputDocument = @".\result.txt";
282

    
283
        //    // Create TextExtractor instance
284

    
285
        //    // Load document to TextExtractor
286
        //    extractor.LoadDocumentFromFile(Common.ViewerDataModel.Instance.searchPDF.FullName);
287

    
288
        //    // Setup TextExtractor
289
        //    extractor.OCRMode = Bytescout.PDFExtractor.OCRMode.TextFromImagesAndVectorsAndFonts;
290
        //    extractor.OCRLanguageDataFolder = ocrAnalyzer.OCRLanguageDataFolder;
291
        //    extractor.OCRLanguage = ocrAnalyzer.OCRLanguage;
292

    
293
        //        // Apply analysys results to TextExtractor instance
294
        //    ocrAnalyzer.ApplyResults(analysisResults, extractor);
295

    
296
        //    // Set extraction area (optional)
297
        //    extractor.SetExtractionArea(rectangle);
298

    
299
        //    // Save extracted text to file
300
        //    extractor.SaveTextToFile(outputDocument);
301

    
302
        //}
303

    
304
        private void Client_DownloadProgressChanged(object sender, System.Net.DownloadProgressChangedEventArgs e)
305
        {
306
            tlDonwloadState.Text = "문서를 다운로드 중입니다 : " + e.ProgressPercentage;
307

    
308
        }
309

    
310
        private void BtnSearch_Click(object sender, RoutedEventArgs e)
311
        {
312
            SearchMethod();
313
        }
314

    
315
        private void SearchMethod()
316
        {
317
            string _strCancel = "Cancel";  // 나중에 정리 
318

    
319
            try
320
            {
321
                if (btnSearch.Content.ToString() == _strCancel)
322
                {
323
                    IsCancelWork = true;
324
                    worker.CancelAsync();
325
                }
326

    
327
                if (!worker.IsBusy)
328
                {
329
                    SearchSet.Clear();
330

    
331
                    this.searchIndicator.IsIndeterminate = true;
332
                    btnSearch.Content = _strCancel;
333

    
334
                    worker.RunWorkerAsync();
335
                }
336
            }
337
            catch (Exception ex)
338
            {
339
                //Logger.sendResLog("SearchMethod", ex.Message, 0);
340
            }
341

    
342
        }
343
        private void DialogMessage_Alert(string Msg)
344
        {
345
            RadWindow CheckPop = new RadWindow();
346
            Alert check = new Alert(Msg);
347

    
348
            CheckPop = new RadWindow
349
            {
350
                Owner = Application.Current.MainWindow,
351
                MinWidth = 400,
352
                MinHeight = 100,
353
                //Closed = (obj, args) => this.MarkupNamePromptClose(MarkupData, args),
354
                Header = "Alert",
355
                Content = check,
356
                ResizeMode = System.Windows.ResizeMode.NoResize,
357
                WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen,
358
                IsTopmost = true,
359
            };
360
            StyleManager.SetTheme(CheckPop, new Office2013Theme());
361
            CheckPop.ShowDialog();
362
        }
363
        private void chkSelectionChangeEvent(object sender, RoutedEventArgs e)
364
        {
365
            try
366
            {
367
                if (Common.ViewerDataModel.Instance.searchPDF != null)
368
                {
369
                    if (sender is RadioButton)
370
                    {
371
                        switch ((sender as RadioButton).Tag.ToString())
372
                        {
373
                            case "0":
374
                                extractor.WordMatchingMode = Bytescout.PDFExtractor.WordMatchingMode.None;
375
                                break;
376
                            case "1":
377
                                extractor.WordMatchingMode = Bytescout.PDFExtractor.WordMatchingMode.ExactMatch;
378
                                break;
379
                            case "2":
380
                                extractor.WordMatchingMode = Bytescout.PDFExtractor.WordMatchingMode.SmartMatch;
381
                                break;
382
                            default:
383
                                break;
384
                        }
385
                    }
386
                }
387
            }
388
            catch (Exception ex)
389
            {
390
                //Logger.sendResLog("chkSelectionChangeEvent", ex.Message, 0);
391
            }
392

    
393
        }
394

    
395
        private void lstSearchWord_PreviewKeyDown(object sender, KeyEventArgs e)
396
        {
397
            int iIndex = this.lstSearchWord.SelectedIndex;
398

    
399
            if (iIndex > -1)
400
            {
401
                if (e.Key == Key.Up)
402
                {
403
                    int iUpIndex = iIndex- 1;
404
                    if(iUpIndex > -1)
405
                    {
406
                        this.lstSearchWord.SelectedIndex = iUpIndex;
407
                    }
408
                }
409
                else if (e.Key == Key.Down)
410
                {
411
                    int iDownIndex = iIndex + 1;
412
                    if(iDownIndex < this.lstSearchWord.Items.Count-1)
413
                    {
414
                        this.lstSearchWord.SelectedIndex = iDownIndex;
415
                    }
416
                }
417
            }
418
        }
419

    
420
        private void lstSearchWord_SelectionChanged(object sender, SelectionChangedEventArgs e)
421
        {
422
            try
423
            {
424
                if (e.AddedItems.Count > 0)
425
                {
426
                    SearchText item = (e.AddedItems[0] as SearchText);
427

    
428
                    if (Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.pageNavigator.CurrentPage.PageNumber == item.PageNo)
429
                    {
430
                        GotoPosition(item);
431
                    }
432
                    else
433
                    {
434
                        var pageNavigator = Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.pageNavigator;
435

    
436
                        EventHandler<EventArgs> handler = null;
437

    
438
                        handler = (snd, evt) =>
439
                        {
440
                            GotoPosition(item);
441
                            ViewerDataModel.Instance.PageLoaded -= handler;
442
                        };
443

    
444
                        ViewerDataModel.Instance.PageLoaded += handler;
445
                        pageNavigator.GotoPage(item.PageNo);
446

    
447
                    }
448
                }
449
            }
450
            catch (Exception ex)
451
            {
452
                //Logger.sendResLog("lstSearchWord_SelectionChanged", ex.Message, 0);
453
            }
454

    
455
        }
456

    
457
        private void GotoPosition(SearchText item)
458
        {
459
            Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.Dispatcher.Invoke(() => {
460

    
461
                for (int i = 0; i < (Common.ViewerDataModel.Instance.MarkupAngle / 90); i++)
462
                {
463
                    Common.ViewerDataModel.Instance.SystemMain.dzTopMenu.drawingPannelRotate(true);
464
                }
465

    
466
                var width = Convert.ToDouble(Common.ViewerDataModel.Instance.Document_Info[item.PageNo - 1].PAGE_WIDTH);
467
                var height = Convert.ToDouble(Common.ViewerDataModel.Instance.Document_Info[item.PageNo - 1].PAGE_HEIGHT);
468
                
469
                var widthScale = width / Convert.ToDouble(extractor.GetPageRect_Width(item.PageNo - 1));
470
                var heightScale = height / Convert.ToDouble(extractor.GetPageRect_Height(item.PageNo - 1));
471

    
472
                var searchFocus = Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.SearchFocusBorder;
473
                searchFocus.Visibility = Visibility;
474

    
475
                if (item.searchResult != null)
476
                {
477
                    Canvas.SetLeft(searchFocus, item.searchResult.Left * widthScale);
478
                    Canvas.SetTop(searchFocus, item.searchResult.Top * heightScale);
479
                    searchFocus.Width = item.searchResult.Width * widthScale;
480
                    searchFocus.Height = item.searchResult.Height * widthScale;
481

    
482
                    Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.zoomAndPanControl.ZoomTo(new Rect
483
                    {
484
                        X = item.searchResult.Left * widthScale,
485
                        Y = item.searchResult.Top * heightScale,
486
                        Width = (item.searchResult.Width * widthScale * 7),
487
                        Height = (item.searchResult.Height * heightScale * 7)
488
                    });
489
                }
490

    
491
                //extractor.SavePageTextToFile(item.PageNo - 1, @"C:\Users\kts\AppData\Local\Temp\MARKUS\savepageText\text.txt");
492
                //extractor.SavePreprocessedPagePreview(item.PageNo - 1, $"C:\\Users\\kts\\AppData\\Local\\Temp\\MARKUS\\savepageText\\{(item.PageNo - 1).ToString()}.png");
493
            });
494
        }
495

    
496
        
497
    }
498
}
클립보드 이미지 추가 (최대 크기: 500 MB)