프로젝트

일반

사용자정보

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

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

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

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

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

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

    
53
            tbSearch.KeyDown += tbSearch_KeyDown;
54

    
55
            worker.DoWork += Worker_DoWork;
56
            worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
57

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

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

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

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

    
85
                this.searchIndicator.IsIndeterminate = false;
86
                this.DataContext = this;
87
                //tbSearch.Text = "";
88
                tbSearch.Focus();
89

    
90
                txtSearchMsg.Text = "search has completed.";
91
            }));
92
        }
93
        //private System.Collections.ObjectModel.ObservableCollection<SearchText> searchTexts = null;
94
        private void Worker_DoWork(object sender, DoWorkEventArgs e)
95
        {
96
            string searchString = string.Empty;
97
            bool pageoption = false;
98

    
99
            Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate
100
            {
101
                SearchSet.Clear();
102
                searchString = tbSearch.Text;
103
                pageoption = chkCurrentPageOnly.IsChecked.Value;
104
            }));
105

    
106
            //Bytescout.PDFExtractor.SearchablePDFMaker maker = new Bytescout.PDFExtractor.SearchablePDFMaker(RegistrationName, RegistrationKey);
107
            //maker.LoadDocumentFromFile(Common.ViewerDataModel.Instance.searchPDF.FullName);
108
            //maker.MakePDFSearchable(Common.ViewerDataModel.Instance.searchPDF.FullName + ".pdf");
109
            
110
            //maker.Dispose();
111
            extractor.LoadDocumentFromFile(Common.ViewerDataModel.Instance.searchPDF.FullName + ".pdf");
112

    
113
            if (pageoption)
114
            {
115
                var currentPage = Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.pageNavigator.CurrentPage.PageNumber - 1;
116

    
117
                //Bytescout.PDFExtractor.OCRAnalysisResults analysisResults = ocrAnalyzer.AnalyzeByOCRConfidence(currentPage);
118
                //ocrAnalyzer.ApplyResults(analysisResults, extractor);
119
                
120
                if (extractor.Find(currentPage, searchString, false))
121
                    do
122
                    {
123
                        Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate
124
                        {
125
                            SearchSet.Add(new SearchText { PageNo = currentPage + 1, searchResult = extractor.FoundText });
126
                        }));
127
                    }
128
                    while (extractor.FindNext());
129
            }
130
            else
131
            {
132
                int pageCount = extractor.GetPageCount();
133

    
134
                for (int i = 0; i < pageCount; i++)
135
                {
136
                    txtSearchMsg.Dispatcher.Invoke(()=> txtSearchMsg.Text = $"Search Pages {i + 1}/{pageCount}");
137

    
138
                    //Bytescout.PDFExtractor.OCRAnalysisResults analysisResults = ocrAnalyzer.AnalyzeByOCRConfidence(i);
139
                    //ocrAnalyzer.ApplyResults(analysisResults, extractor);
140
                    if (extractor.Find(i, searchString, false))
141
                        do
142
                        {
143
                            Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate
144
                            {
145
                                SearchSet.Add(new SearchText { PageNo = i + 1, searchResult = extractor.FoundText });
146
                            }));
147

    
148
                            if(IsCancelWork)
149
                            {
150
                                break;
151
                            }
152
                        }
153
                        while (extractor.FindNext());
154

    
155
                    if (IsCancelWork)
156
                    {
157
                        break;
158
                    }
159
                }
160
            }
161
        }
162

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

    
182
                //ocrAnalyzer.OCRLanguage = "eng";
183
                //ocrAnalyzer.OCRLanguageDataFolder = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "tessdata");
184

    
185
            }
186
            catch (Exception ex)
187
            {
188
                //Logger.sendResLog("LibInit", ex.Message, 0);
189
            }
190

    
191
        }
192

    
193
        private void SearchPanel_Loaded(object sender, RoutedEventArgs e)
194
        {
195
            ////
196
            /// 이벤트 안 들어옴
197

    
198

    
199
            //측정
200
            //Stopwatch sw = new Stopwatch();
201
            //sw.Start();
202
            InitializeComponent();
203
            //System.Diagnostics.Debug.WriteLine("SearchPanel() : " + sw.ElapsedMilliseconds.ToString() + "ms");
204

    
205
            btnSearch.Click += BtnSearch_Click;
206
            btnSearchPDFDownload.Click += BtnSearchPDFDownload_Click;
207
            SearchSet = new System.Collections.ObjectModel.ObservableCollection<SearchText>();
208
            extractor = new Bytescout.PDFExtractor.TextExtractor(RegistrationName, RegistrationKey);
209
            tbSearch.KeyDown += tbSearch_KeyDown;
210

    
211
            this.DataContext = this;
212

    
213
        }
214

    
215
        private void BtnSearchPDFDownload_Click(object sender, RoutedEventArgs e)
216
        {
217
            try
218
            {
219
                Common.ViewerDataModel.Instance.IsDownloadCancel = true;
220

    
221

    
222
                using (System.Net.WebClient client = new System.Net.WebClient())
223
                {
224
                    string instnaceFile = System.IO.Path.GetTempFileName().Replace(".pdf", ".tmp");
225
                    client.DownloadFileCompleted += Client_DownloadFileCompleted;
226
                    client.DownloadProgressChanged += Client_DownloadProgressChanged;
227
                    string downloadurl = Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.GetOriginalPDFURL();
228

    
229
                    client.DownloadFileAsync(new Uri(downloadurl), instnaceFile);
230
                }
231
            }
232
            catch (Exception ex)
233
            {
234
                //Logger.sendResLog("DownloadOriginalFileAsync", ex.Message, 0);
235
            }
236
        }
237

    
238

    
239
        private void Client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
240
        {
241
            SetSerachPDFFile(e.UserState.ToString());
242
        }
243

    
244
        public void SetSerachPDFFile(string FileFullPath)
245
        {
246
            border_Overlap.Visibility = Visibility.Collapsed;
247
            Common.ViewerDataModel.Instance.searchPDF = new System.IO.FileInfo(FileFullPath);
248
            //OcrAnalyzer();
249

    
250
            tbSearch.Focus();
251
        }
252

    
253
        //private void OcrAnalyzer()
254
        //{
255
        //    System.Drawing.RectangleF rectangle = System.Drawing.RectangleF.Empty;
256

    
257
        //    // Display analysis progress
258
        //    ocrAnalyzer.ProgressChanged += (object sender, string message, double progress, ref bool cancel)=>
259
        //    {
260
        //        System.Diagnostics.Debug.WriteLine(message);
261
        //    };
262

    
263
        //    // Load document to OCRAnalyzer
264
        //    ocrAnalyzer.LoadDocumentFromFile(Common.ViewerDataModel.Instance.searchPDF.FullName);
265

    
266
        //    // Set page area for analysis (optional)
267
        //    ocrAnalyzer.SetExtractionArea(rectangle);
268

    
269
        //    // Perform analysis and get results
270
        //    Bytescout.PDFExtractor.OCRAnalysisResults analysisResults = ocrAnalyzer.AnalyzeByOCRConfidence(0);
271

    
272
        //    // Now extract the text using detected OCR parameters
273

    
274
        //    string outputDocument = @".\result.txt";
275

    
276
        //    // Create TextExtractor instance
277

    
278
        //    // Load document to TextExtractor
279
        //    extractor.LoadDocumentFromFile(Common.ViewerDataModel.Instance.searchPDF.FullName);
280

    
281
        //    // Setup TextExtractor
282
        //    extractor.OCRMode = Bytescout.PDFExtractor.OCRMode.TextFromImagesAndVectorsAndFonts;
283
        //    extractor.OCRLanguageDataFolder = ocrAnalyzer.OCRLanguageDataFolder;
284
        //    extractor.OCRLanguage = ocrAnalyzer.OCRLanguage;
285

    
286
        //        // Apply analysys results to TextExtractor instance
287
        //    ocrAnalyzer.ApplyResults(analysisResults, extractor);
288

    
289
        //    // Set extraction area (optional)
290
        //    extractor.SetExtractionArea(rectangle);
291

    
292
        //    // Save extracted text to file
293
        //    extractor.SaveTextToFile(outputDocument);
294

    
295
        //}
296

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

    
301
        }
302

    
303
        private void BtnSearch_Click(object sender, RoutedEventArgs e)
304
        {
305
            SearchMethod();
306
        }
307

    
308
        private void SearchMethod()
309
        {
310
            string _strCancel = "Cancel";  // 나중에 정리 
311

    
312
            try
313
            {
314
                if (btnSearch.Content.ToString() == _strCancel)
315
                {
316
                    IsCancelWork = true;
317
                    worker.CancelAsync();
318
                }
319

    
320
                if (!worker.IsBusy)
321
                {
322
                    SearchSet.Clear();
323

    
324
                    this.searchIndicator.IsIndeterminate = true;
325
                    btnSearch.Content = _strCancel;
326

    
327
                    worker.RunWorkerAsync();
328
                }
329
            }
330
            catch (Exception ex)
331
            {
332
                //Logger.sendResLog("SearchMethod", ex.Message, 0);
333
            }
334

    
335
        }
336
        private void DialogMessage_Alert(string Msg)
337
        {
338
            RadWindow CheckPop = new RadWindow();
339
            Alert check = new Alert(Msg);
340

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

    
386
        }
387

    
388
        private void lstSearchWord_SelectionChanged(object sender, SelectionChangedEventArgs e)
389
        {
390
            try
391
            {
392
                if (e.AddedItems.Count > 0)
393
                {
394
                    SearchText item = (e.AddedItems[0] as SearchText);
395

    
396
                    if (Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.pageNavigator.CurrentPage.PageNumber == item.PageNo)
397
                    {
398
                        GotoPosition(item);
399
                    }
400
                    else
401
                    {
402
                        var pageNavigator = Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.pageNavigator;
403

    
404
                        EventHandler<EventArgs> handler = null;
405

    
406
                        handler = (snd, evt) =>
407
                        {
408
                            GotoPosition(item);
409
                            ViewerDataModel.Instance.PageLoaded -= handler;
410
                        };
411

    
412
                        ViewerDataModel.Instance.PageLoaded += handler;
413
                        pageNavigator.GotoPage(item.PageNo);
414

    
415
                    }
416
                }
417
            }
418
            catch (Exception ex)
419
            {
420
                //Logger.sendResLog("lstSearchWord_SelectionChanged", ex.Message, 0);
421
            }
422

    
423
        }
424

    
425
        private void GotoPosition(SearchText item)
426
        {
427
            Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.Dispatcher.Invoke(() => {
428

    
429
                for (int i = 0; i < (Common.ViewerDataModel.Instance.MarkupAngle / 90); i++)
430
                {
431
                    Common.ViewerDataModel.Instance.SystemMain.dzTopMenu.drawingPannelRotate(true);
432
                }
433

    
434
                var width = Convert.ToDouble(Common.ViewerDataModel.Instance.Document_Info[item.PageNo - 1].PAGE_WIDTH);
435
                var height = Convert.ToDouble(Common.ViewerDataModel.Instance.Document_Info[item.PageNo - 1].PAGE_HEIGHT);
436
                
437
                var widthScale = width / Convert.ToDouble(extractor.GetPageRect_Width(item.PageNo - 1));
438
                var heightScale = height / Convert.ToDouble(extractor.GetPageRect_Height(item.PageNo - 1));
439

    
440
                var searchFocus = Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.SearchFocusBorder;
441
                searchFocus.Visibility = Visibility;
442

    
443
                Canvas.SetLeft(searchFocus, item.searchResult.Left * widthScale);
444
                Canvas.SetTop(searchFocus, item.searchResult.Top * heightScale);
445
                searchFocus.Width = item.searchResult.Width * widthScale;
446
                searchFocus.Height = item.searchResult.Height * widthScale;
447

    
448
                Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.zoomAndPanControl.ZoomTo(new Rect
449
                {
450
                    X =item.searchResult.Left * widthScale,
451
                    Y = item.searchResult.Top * heightScale,
452
                    Width = ( item.searchResult.Width * widthScale *7),
453
                    Height = (item.searchResult.Height * heightScale *7)
454
                });
455

    
456
                //extractor.SavePageTextToFile(item.PageNo - 1, @"C:\Users\kts\AppData\Local\Temp\MARKUS\savepageText\text.txt");
457
                //extractor.SavePreprocessedPagePreview(item.PageNo - 1, $"C:\\Users\\kts\\AppData\\Local\\Temp\\MARKUS\\savepageText\\{(item.PageNo - 1).ToString()}.png");
458
            });
459
        }
460
    }
461
}
클립보드 이미지 추가 (최대 크기: 500 MB)