프로젝트

일반

사용자정보

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

markus / KCOM / Controls / SearchPanel.xaml.cs @ b1c2c6fe

이력 | 보기 | 이력해설 | 다운로드 (18.8 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
            extractor.LoadDocumentFromFile(Common.ViewerDataModel.Instance.searchPDF.FullName + ".pdf");
121

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

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

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

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

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

    
164
                    if (IsCancelWork)
165
                    {
166
                        break;
167
                    }
168
                }
169
            }
170
        }
171

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

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

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

    
200
        }
201

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

    
207

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

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

    
220
            this.DataContext = this;
221

    
222
        }
223

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

    
230

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

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

    
247

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

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

    
259
            tbSearch.Focus();
260
        }
261

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

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

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

    
275
        //    // Set page area for analysis (optional)
276
        //    ocrAnalyzer.SetExtractionArea(rectangle);
277

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

    
281
        //    // Now extract the text using detected OCR parameters
282

    
283
        //    string outputDocument = @".\result.txt";
284

    
285
        //    // Create TextExtractor instance
286

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

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

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

    
298
        //    // Set extraction area (optional)
299
        //    extractor.SetExtractionArea(rectangle);
300

    
301
        //    // Save extracted text to file
302
        //    extractor.SaveTextToFile(outputDocument);
303

    
304
        //}
305

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

    
310
        }
311

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

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

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

    
329
                if (!worker.IsBusy)
330
                {
331
                    SearchSet.Clear();
332

    
333
                    this.searchIndicator.IsIndeterminate = true;
334
                    btnSearch.Content = _strCancel;
335

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

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

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

    
395
        }
396

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

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

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

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

    
438
                        EventHandler<EventArgs> handler = null;
439

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

    
446
                        ViewerDataModel.Instance.PageLoaded += handler;
447
                        pageNavigator.GotoPage(item.PageNo);
448

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

    
457
        }
458

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

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

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

    
474
                var searchFocus = Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.SearchFocusBorder;
475
                searchFocus.Visibility = Visibility;
476

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

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

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

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