프로젝트

일반

사용자정보

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

markus / KCOM / Controls / SearchPanel.xaml.cs @ 299f2c11

이력 | 보기 | 이력해설 | 다운로드 (19 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
            //Bytescout.PDFExtractor.SearchablePDFMaker maker = new Bytescout.PDFExtractor.SearchablePDFMaker(RegistrationName, RegistrationKey);
116
            //maker.LoadDocumentFromFile(Common.ViewerDataModel.Instance.searchPDF.FullName);
117
            //maker.MakePDFSearchable(Common.ViewerDataModel.Instance.searchPDF.FullName + ".pdf");
118

    
119
            //maker.Dispose();
120
            if (extractor == null)
121
            {
122
                throw new InvalidOperationException("extractor is null");
123
            }
124
            extractor.LoadDocumentFromFile(Common.ViewerDataModel.Instance.searchPDF.FullName + ".pdf");
125

    
126
            if (pageoption)
127
            {
128
                var currentPage = Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.pageNavigator.CurrentPage.PageNumber - 1;
129

    
130
                //Bytescout.PDFExtractor.OCRAnalysisResults analysisResults = ocrAnalyzer.AnalyzeByOCRConfidence(currentPage);
131
                //ocrAnalyzer.ApplyResults(analysisResults, extractor);
132
                
133
                if (extractor.Find(currentPage, searchString, false))
134
                    do
135
                    {
136
                        Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate
137
                        {
138
                            SearchSet.Add(new SearchText { PageNo = currentPage + 1, searchResult = extractor.FoundText });
139
                        }));
140
                    }
141
                    while (extractor.FindNext());
142
            }
143
            else
144
            {
145
                int pageCount = extractor.GetPageCount();
146

    
147
                for (int i = 0; i < pageCount; i++)
148
                {
149
                    txtSearchMsg.Dispatcher.Invoke(()=> txtSearchMsg.Text = $"Search Pages {i + 1}/{pageCount}");
150

    
151
                    //Bytescout.PDFExtractor.OCRAnalysisResults analysisResults = ocrAnalyzer.AnalyzeByOCRConfidence(i);
152
                    //ocrAnalyzer.ApplyResults(analysisResults, extractor);
153
                    if (extractor.Find(i, searchString, false))
154
                        do
155
                        {
156
                            Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate
157
                            {
158
                                SearchSet.Add(new SearchText { PageNo = i + 1, searchResult = extractor.FoundText });
159
                            }));
160

    
161
                            if(IsCancelWork)
162
                            {
163
                                break;
164
                            }
165
                        }
166
                        while (extractor.FindNext());
167

    
168
                    if (IsCancelWork)
169
                    {
170
                        break;
171
                    }
172
                }
173
            }
174
        }
175

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

    
195
                //ocrAnalyzer.OCRLanguage = "eng";
196
                //ocrAnalyzer.OCRLanguageDataFolder = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "tessdata");
197

    
198
            }
199
            catch (Exception ex)
200
            {
201
                //Logger.sendResLog("LibInit", ex.Message, 0);
202
            }
203

    
204
        }
205

    
206
        private void SearchPanel_Loaded(object sender, RoutedEventArgs e)
207
        {
208
            ////
209
            /// 이벤트 안 들어옴
210

    
211

    
212
            //측정
213
            //Stopwatch sw = new Stopwatch();
214
            //sw.Start();
215
            InitializeComponent();
216
            //System.Diagnostics.Debug.WriteLine("SearchPanel() : " + sw.ElapsedMilliseconds.ToString() + "ms");
217

    
218
            btnSearch.Click += BtnSearch_Click;
219
            btnSearchPDFDownload.Click += BtnSearchPDFDownload_Click;
220
            SearchSet = new System.Collections.ObjectModel.ObservableCollection<SearchText>();
221
            extractor = new Bytescout.PDFExtractor.TextExtractor(RegistrationName, RegistrationKey);
222
            tbSearch.KeyDown += tbSearch_KeyDown;
223

    
224
            this.DataContext = this;
225

    
226
        }
227

    
228
        private void BtnSearchPDFDownload_Click(object sender, RoutedEventArgs e)
229
        {
230
            try
231
            {
232
                Common.ViewerDataModel.Instance.IsDownloadCancel = true;
233

    
234

    
235
                using (System.Net.WebClient client = new System.Net.WebClient())
236
                {
237
                    string instnaceFile = System.IO.Path.GetTempFileName().Replace(".pdf", ".tmp");
238
                    client.DownloadFileCompleted += Client_DownloadFileCompleted;
239
                    client.DownloadProgressChanged += Client_DownloadProgressChanged;
240
                    string downloadurl = Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.GetOriginalPDFURL();
241

    
242
                    client.DownloadFileAsync(new Uri(downloadurl), instnaceFile);
243
                }
244
            }
245
            catch (Exception ex)
246
            {
247
                //Logger.sendResLog("DownloadOriginalFileAsync", ex.Message, 0);
248
            }
249
        }
250

    
251

    
252
        private void Client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
253
        {
254
            SetSerachPDFFile(e.UserState.ToString());
255
        }
256

    
257
        public void SetSerachPDFFile(string FileFullPath)
258
        {
259
            border_Overlap.Visibility = Visibility.Collapsed;
260
            Common.ViewerDataModel.Instance.searchPDF = new System.IO.FileInfo(FileFullPath);
261
            //OcrAnalyzer();
262

    
263
            tbSearch.Focus();
264
        }
265

    
266
        //private void OcrAnalyzer()
267
        //{
268
        //    System.Drawing.RectangleF rectangle = System.Drawing.RectangleF.Empty;
269

    
270
        //    // Display analysis progress
271
        //    ocrAnalyzer.ProgressChanged += (object sender, string message, double progress, ref bool cancel)=>
272
        //    {
273
        //        System.Diagnostics.Debug.WriteLine(message);
274
        //    };
275

    
276
        //    // Load document to OCRAnalyzer
277
        //    ocrAnalyzer.LoadDocumentFromFile(Common.ViewerDataModel.Instance.searchPDF.FullName);
278

    
279
        //    // Set page area for analysis (optional)
280
        //    ocrAnalyzer.SetExtractionArea(rectangle);
281

    
282
        //    // Perform analysis and get results
283
        //    Bytescout.PDFExtractor.OCRAnalysisResults analysisResults = ocrAnalyzer.AnalyzeByOCRConfidence(0);
284

    
285
        //    // Now extract the text using detected OCR parameters
286

    
287
        //    string outputDocument = @".\result.txt";
288

    
289
        //    // Create TextExtractor instance
290

    
291
        //    // Load document to TextExtractor
292
        //    extractor.LoadDocumentFromFile(Common.ViewerDataModel.Instance.searchPDF.FullName);
293

    
294
        //    // Setup TextExtractor
295
        //    extractor.OCRMode = Bytescout.PDFExtractor.OCRMode.TextFromImagesAndVectorsAndFonts;
296
        //    extractor.OCRLanguageDataFolder = ocrAnalyzer.OCRLanguageDataFolder;
297
        //    extractor.OCRLanguage = ocrAnalyzer.OCRLanguage;
298

    
299
        //        // Apply analysys results to TextExtractor instance
300
        //    ocrAnalyzer.ApplyResults(analysisResults, extractor);
301

    
302
        //    // Set extraction area (optional)
303
        //    extractor.SetExtractionArea(rectangle);
304

    
305
        //    // Save extracted text to file
306
        //    extractor.SaveTextToFile(outputDocument);
307

    
308
        //}
309

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

    
314
        }
315

    
316
        private void BtnSearch_Click(object sender, RoutedEventArgs e)
317
        {
318
            SearchMethod();
319
        }
320

    
321
        private void SearchMethod()
322
        {
323
            string _strCancel = "Cancel";  // 나중에 정리 
324

    
325
            try
326
            {
327
                if (btnSearch.Content.ToString() == _strCancel)
328
                {
329
                    IsCancelWork = true;
330
                    worker.CancelAsync();
331
                }
332

    
333
                if (!worker.IsBusy)
334
                {
335
                    SearchSet.Clear();
336

    
337
                    this.searchIndicator.IsIndeterminate = true;
338
                    btnSearch.Content = _strCancel;
339

    
340
                    worker.RunWorkerAsync();
341
                }
342
            }
343
            catch (Exception ex)
344
            {
345
                //Logger.sendResLog("SearchMethod", ex.Message, 0);
346
            }
347

    
348
        }
349
        private void DialogMessage_Alert(string Msg)
350
        {
351
            RadWindow CheckPop = new RadWindow();
352
            Alert check = new Alert(Msg);
353

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

    
399
        }
400

    
401
        private void lstSearchWord_PreviewKeyDown(object sender, KeyEventArgs e)
402
        {
403
            int iIndex = this.lstSearchWord.SelectedIndex;
404

    
405
            if (iIndex > -1)
406
            {
407
                if (e.Key == Key.Up)
408
                {
409
                    int iUpIndex = iIndex- 1;
410
                    if(iUpIndex > -1)
411
                    {
412
                        this.lstSearchWord.SelectedIndex = iUpIndex;
413
                    }
414
                }
415
                else if (e.Key == Key.Down)
416
                {
417
                    int iDownIndex = iIndex + 1;
418
                    if(iDownIndex < this.lstSearchWord.Items.Count-1)
419
                    {
420
                        this.lstSearchWord.SelectedIndex = iDownIndex;
421
                    }
422
                }
423
            }
424
        }
425

    
426
        private void lstSearchWord_SelectionChanged(object sender, SelectionChangedEventArgs e)
427
        {
428
            try
429
            {
430
                if (e.AddedItems.Count > 0)
431
                {
432
                    SearchText item = (e.AddedItems[0] as SearchText);
433

    
434
                    if (Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.pageNavigator.CurrentPage.PageNumber == item.PageNo)
435
                    {
436
                        GotoPosition(item);
437
                    }
438
                    else
439
                    {
440
                        var pageNavigator = Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.pageNavigator;
441

    
442
                        EventHandler<EventArgs> handler = null;
443

    
444
                        handler = (snd, evt) =>
445
                        {
446
                            GotoPosition(item);
447
                            ViewerDataModel.Instance.PageLoaded -= handler;
448
                        };
449

    
450
                        ViewerDataModel.Instance.PageLoaded += handler;
451
                        pageNavigator.GotoPage(item.PageNo);
452

    
453
                    }
454
                }
455
            }
456
            catch (Exception ex)
457
            {
458
                //Logger.sendResLog("lstSearchWord_SelectionChanged", ex.Message, 0);
459
            }
460

    
461
        }
462

    
463
        private void GotoPosition(SearchText item)
464
        {
465
            Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.Dispatcher.Invoke(() => {
466

    
467
                for (int i = 0; i < (Common.ViewerDataModel.Instance.MarkupAngle / 90); i++)
468
                {
469
                    Common.ViewerDataModel.Instance.SystemMain.dzTopMenu.drawingPannelRotate(true);
470
                }
471

    
472
                var width = Convert.ToDouble(Common.ViewerDataModel.Instance.Document_Info[item.PageNo - 1].PAGE_WIDTH);
473
                var height = Convert.ToDouble(Common.ViewerDataModel.Instance.Document_Info[item.PageNo - 1].PAGE_HEIGHT);
474
                
475
                var widthScale = width / Convert.ToDouble(extractor.GetPageRect_Width(item.PageNo - 1));
476
                var heightScale = height / Convert.ToDouble(extractor.GetPageRect_Height(item.PageNo - 1));
477

    
478
                var searchFocus = Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.SearchFocusBorder;
479
                searchFocus.Visibility = Visibility;
480

    
481
                if (item.searchResult != null)
482
                {
483
                    Canvas.SetLeft(searchFocus, item.searchResult.Left * widthScale);
484
                    Canvas.SetTop(searchFocus, item.searchResult.Top * heightScale);
485
                    searchFocus.Width = item.searchResult.Width * widthScale;
486
                    searchFocus.Height = item.searchResult.Height * widthScale;
487

    
488
                    Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.zoomAndPanControl.ZoomTo(new Rect
489
                    {
490
                        X = item.searchResult.Left * widthScale,
491
                        Y = item.searchResult.Top * heightScale,
492
                        Width = (item.searchResult.Width * widthScale * 7),
493
                        Height = (item.searchResult.Height * heightScale * 7)
494
                    });
495
                }
496

    
497
                //extractor.SavePageTextToFile(item.PageNo - 1, @"C:\Users\kts\AppData\Local\Temp\MARKUS\savepageText\text.txt");
498
                //extractor.SavePreprocessedPagePreview(item.PageNo - 1, $"C:\\Users\\kts\\AppData\\Local\\Temp\\MARKUS\\savepageText\\{(item.PageNo - 1).ToString()}.png");
499
            });
500
        }
501

    
502
        
503
    }
504
}
클립보드 이미지 추가 (최대 크기: 500 MB)