프로젝트

일반

사용자정보

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

markus / KCOM / Controls / SearchPanel.xaml.cs @ 285635d3

이력 | 보기 | 이력해설 | 다운로드 (15 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
            extractor.LoadDocumentFromFile(Common.ViewerDataModel.Instance.searchPDF.FullName);
107
            //ocrAnalyzer.LoadDocumentFromFile(Common.ViewerDataModel.Instance.searchPDF.FullName);
108

    
109
            if (pageoption)
110
            {
111
                var currentPage = Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.pageNavigator.CurrentPage.PageNumber - 1;
112

    
113
                //Bytescout.PDFExtractor.OCRAnalysisResults analysisResults = ocrAnalyzer.AnalyzeByOCRConfidence(currentPage);
114
                //ocrAnalyzer.ApplyResults(analysisResults, extractor);
115

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

    
130
                for (int i = 0; i < pageCount; i++)
131
                {
132
                    txtSearchMsg.Dispatcher.Invoke(()=> txtSearchMsg.Text = $"Search Pages {i + 1}/{pageCount}");
133

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

    
144
                            if(IsCancelWork)
145
                            {
146
                                break;
147
                            }
148
                        }
149
                        while (extractor.FindNext());
150

    
151
                    if (IsCancelWork)
152
                    {
153
                        break;
154
                    }
155
                }
156
            }
157
        }
158

    
159
        private void tbSearch_KeyDown(object sender, KeyEventArgs e)
160
        {
161
            if (e.Key == Key.Enter)
162
            {
163
                SearchMethod();
164
            }
165
        }
166
        private void LibInit()
167
        {
168
            try
169
            {
170
                extractor = new Bytescout.PDFExtractor.TextExtractor(RegistrationName, RegistrationKey);
171
                ocrAnalyzer = new Bytescout.PDFExtractor.OCRAnalyzer(RegistrationName, RegistrationKey);
172
                extractor.OCRMode = Bytescout.PDFExtractor.OCRMode.Auto;
173
                extractor.OCRLanguage = "eng";
174
                extractor.OCRLanguageDataFolder = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "tessdata");
175

    
176
                extractor.OCRResolution = 300;
177

    
178
                ocrAnalyzer.OCRLanguage = "eng";
179
                ocrAnalyzer.OCRLanguageDataFolder = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "tessdata");
180

    
181
            }
182
            catch (Exception ex)
183
            {
184
                Logger.sendResLog("LibInit", ex.Message, 0);
185
            }
186

    
187
        }
188

    
189
        private void SearchPanel_Loaded(object sender, RoutedEventArgs e)
190
        {
191
            ////
192
            /// 이벤트 안 들어옴
193

    
194

    
195
            //측정
196
            //Stopwatch sw = new Stopwatch();
197
            //sw.Start();
198
            InitializeComponent();
199
            //System.Diagnostics.Debug.WriteLine("SearchPanel() : " + sw.ElapsedMilliseconds.ToString() + "ms");
200

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

    
207
            this.DataContext = this;
208

    
209
        }
210

    
211
        private void BtnSearchPDFDownload_Click(object sender, RoutedEventArgs e)
212
        {
213
            try
214
            {
215
                Common.ViewerDataModel.Instance.IsDownloadCancel = true;
216

    
217

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

    
225
                    client.DownloadFileAsync(new Uri(downloadurl), instnaceFile);
226
                }
227
            }
228
            catch (Exception ex)
229
            {
230
                Logger.sendResLog("DownloadOriginalFileAsync", ex.Message, 0);
231
            }
232
        }
233

    
234

    
235
        private void Client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
236
        {
237
            SetSerachPDFFile(e.UserState.ToString());
238
        }
239

    
240
        public void SetSerachPDFFile(string FileFullPath)
241
        {
242
            border_Overlap.Visibility = Visibility.Collapsed;
243
            Common.ViewerDataModel.Instance.searchPDF = new System.IO.FileInfo(FileFullPath);
244
            tbSearch.Focus();
245
        }
246

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

    
251
        }
252

    
253
        private void BtnSearch_Click(object sender, RoutedEventArgs e)
254
        {
255
            SearchMethod();
256
        }
257

    
258
        private void SearchMethod()
259
        {
260
            string _strCancel = "Cancel";  // 나중에 정리 
261

    
262
            try
263
            {
264
                if (btnSearch.Content.ToString() == _strCancel)
265
                {
266
                    IsCancelWork = true;
267
                }
268

    
269
                if (!worker.IsBusy)
270
                {
271
                    SearchSet.Clear();
272

    
273
                    this.searchIndicator.IsIndeterminate = true;
274
                    btnSearch.Content = _strCancel;
275

    
276
                    worker.RunWorkerAsync();
277
                }
278
            }
279
            catch (Exception ex)
280
            {
281
                Logger.sendResLog("SearchMethod", ex.Message, 0);
282
            }
283

    
284
        }
285
        private void DialogMessage_Alert(string Msg)
286
        {
287
            RadWindow CheckPop = new RadWindow();
288
            Alert check = new Alert(Msg);
289

    
290
            CheckPop = new RadWindow
291
            {
292
                Owner = Application.Current.MainWindow,
293
                MinWidth = 400,
294
                MinHeight = 100,
295
                //Closed = (obj, args) => this.MarkupNamePromptClose(MarkupData, args),
296
                Header = "Alert",
297
                Content = check,
298
                ResizeMode = System.Windows.ResizeMode.NoResize,
299
                WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen,
300
                IsTopmost = true,
301
            };
302
            StyleManager.SetTheme(CheckPop, new Office2013Theme());
303
            CheckPop.ShowDialog();
304
        }
305
        private void chkSelectionChangeEvent(object sender, RoutedEventArgs e)
306
        {
307
            try
308
            {
309
                if (Common.ViewerDataModel.Instance.searchPDF != null)
310
                {
311
                    if (sender is RadioButton)
312
                    {
313
                        switch ((sender as RadioButton).Tag.ToString())
314
                        {
315
                            case "0":
316
                                extractor.WordMatchingMode = Bytescout.PDFExtractor.WordMatchingMode.None;
317
                                break;
318
                            case "1":
319
                                extractor.WordMatchingMode = Bytescout.PDFExtractor.WordMatchingMode.ExactMatch;
320
                                break;
321
                            case "2":
322
                                extractor.WordMatchingMode = Bytescout.PDFExtractor.WordMatchingMode.SmartMatch;
323
                                break;
324
                            default:
325
                                break;
326
                        }
327
                    }
328
                }
329
            }
330
            catch (Exception ex)
331
            {
332
                Logger.sendResLog("chkSelectionChangeEvent", ex.Message, 0);
333
            }
334

    
335
        }
336

    
337
        private void lstSearchWord_SelectionChanged(object sender, SelectionChangedEventArgs e)
338
        {
339
            try
340
            {
341
                if (e.AddedItems.Count > 0)
342
                {
343
                    SearchText item = (e.AddedItems[0] as SearchText);
344

    
345
                    if (Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.pageNavigator.CurrentPage.PageNumber == item.PageNo)
346
                    {
347
                        GotoPosition(item);
348
                    }
349
                    else
350
                    {
351
                        var pageNavigator = Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.pageNavigator;
352

    
353
                        EventHandler<EventArgs> handler = null;
354

    
355
                        handler = (snd, evt) =>
356
                        {
357
                            GotoPosition(item);
358
                            ViewerDataModel.Instance.PageLoaded -= handler;
359
                        };
360

    
361
                        ViewerDataModel.Instance.PageLoaded += handler;
362
                        pageNavigator.GotoPage(item.PageNo);
363

    
364
                    }
365
                }
366
            }
367
            catch (Exception ex)
368
            {
369
                Logger.sendResLog("lstSearchWord_SelectionChanged", ex.Message, 0);
370
            }
371

    
372
        }
373

    
374
        private void GotoPosition(SearchText item)
375
        {
376
            Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.Dispatcher.Invoke(() => {
377

    
378
                for (int i = 0; i < (Common.ViewerDataModel.Instance.Angle / 90); i++)
379
                {
380
                    Common.ViewerDataModel.Instance.SystemMain.dzTopMenu.drawingPannelRotate(true);
381
                }
382

    
383
                var width = Convert.ToDouble(Common.ViewerDataModel.Instance.Document_Info[item.PageNo - 1].PAGE_WIDTH);
384
                var height = Convert.ToDouble(Common.ViewerDataModel.Instance.Document_Info[item.PageNo - 1].PAGE_HEIGHT);
385
                var widthScale = width / Convert.ToDouble(extractor.GetPageRect_Width(item.PageNo - 1));
386
                var heightScale = height / Convert.ToDouble(extractor.GetPageRect_Height(item.PageNo - 1));
387

    
388
                var searchFocus = Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.SearchFocusBorder;
389
                searchFocus.Visibility = Visibility;
390

    
391
                Canvas.SetLeft(searchFocus, item.searchResult.Left * widthScale);
392
                Canvas.SetTop(searchFocus, item.searchResult.Top * heightScale);
393
                searchFocus.Width = item.searchResult.Width * widthScale;
394
                searchFocus.Height = item.searchResult.Height * widthScale;
395

    
396
                Common.ViewerDataModel.Instance.SystemMain.dzMainMenu.zoomAndPanControl.ZoomTo(new Rect
397
                {
398
                    X =item.searchResult.Left * widthScale,
399
                    Y = item.searchResult.Top * heightScale,
400
                    Width = ( item.searchResult.Width * widthScale *7),
401
                    Height = (item.searchResult.Height * heightScale *7)
402
                });
403
            });
404
        }
405
    }
406
}
클립보드 이미지 추가 (최대 크기: 500 MB)