프로젝트

일반

사용자정보

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

markus / KCOM / Controls / PrintControl.xaml.cs @ e6c46927

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

1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Windows;
5
using System.Windows.Controls;
6
using System.Windows.Media;
7
using Telerik.Windows.Controls;
8
using System.Collections.ObjectModel;
9
using System.Drawing.Printing;
10
using System.Windows.Media.Imaging;
11
using KCOMDataModel.DataModel;
12
using Microsoft.Win32;
13
using System.IO;
14
using System.Timers;
15
//using IKCOM.Common;
16
using KCOM.Event;
17
using iTextSharp;
18
using iTextSharp.text;
19
//using Leadtools.Windows.Controls;
20
using IKCOM;
21
using iTextSharp.text.pdf;
22
using System.Net;
23
using Image = System.Windows.Controls.Image;
24
using System.ComponentModel;
25

    
26
namespace KCOM.Control
27
{
28
    public class DefinedPages
29
    {
30
        public DOCINFO DocumentInfo { get; set; }
31

    
32
        public int PagesCount { get; set; }
33
        public string vpSlip { get; set; }
34
        public string vpTitle { get; set; }
35
        public string fileUrl { get; set; }
36
        public ImageBrush Back_Image { get; set; }
37

    
38
        public double CurrentValue { get; set; }
39

    
40
        string _DefinedPagesStrings;
41
        /// <summary>
42
        /// 사용자 정의 페이지를 입력시 오류를 방지하기 위해 적용
43
        /// </summary>
44
        public string DefinedPagesStrings
45
        {
46
            get { return _DefinedPagesStrings; }
47
            set
48
            {
49
                if (string.IsNullOrWhiteSpace(value)) return;
50

    
51
                var _definedPages = value.Replace('-', ',').Split(',');
52
                List<char> _NotEx = new List<char>();
53

    
54
                foreach (var item in _definedPages)
55
                {
56
                    bool _isNum = true;
57

    
58
                    foreach (var chr in item)
59
                    {
60
                        if (!char.IsNumber(chr))
61
                        {
62
                            _NotEx.Add(chr);
63
                            _isNum = false;
64
                        }
65
                    }
66

    
67
                    if (_isNum)
68
                    {
69
                        if (Convert.ToInt32(item) > PagesCount)
70
                            throw new Exception(string.Format("Max Page Number is '{0}'!!.", PagesCount));
71
                    }
72
                }
73

    
74
                if (_NotEx.Count() > 0)
75
                {
76
                    string _notString = "";
77
                    _NotEx.ForEach(s => _notString += s.ToString());
78
                    throw new Exception(string.Format("'{0}' Can not be added.", _notString));
79
                }
80

    
81

    
82
                try
83
                {
84

    
85
                    string _notString2 = "";
86
                    _NotEx.ForEach(s => _notString2 += s.ToString());
87
                    _DefinedPagesStrings = value;
88
                }
89
                catch (Exception)
90
                {
91
                    throw new Exception(string.Format("Can not be added."));
92
                }
93

    
94
            }
95
        }
96
    }
97

    
98
    /// <summary>
99
    /// Interaction logic for Print.xaml
100
    /// </summary>
101
    public partial class PrintControl : UserControl
102
    {
103
        #region Data
104

    
105
        string ProjectNo = null; //프로젝트 넘버
106
        string _DefaultTileUri = null; //기본 타일 경로
107
        int _StartPageNo; //시작페이지 
108
        DOCINFO _DocInfo; //문서 정보
109
        //DocInfo _DocInfo; //문서 정보
110
        bool currentPagePrint = false; //현재 페이지 수
111
        int PageCount { get; set; } //총 페이지수 
112
        DefinedPages _definePages = null; //인쇄 설정 범위 지정
113
        public bool IsPrint { get; set; }
114

    
115
        PrintDocument printDocument = new PrintDocument(); //프린터도큐먼트 생성
116

    
117
        //LayerControl LayerControl = null; // 레이어 컨트롤
118
        ObservableCollection<IKCOM.MarkupInfoItem> _markupInfo = new ObservableCollection<IKCOM.MarkupInfoItem>(); //마크업 정보
119
        List<MarkupPageItem> _PageMarkupList = new List<MarkupPageItem>();
120
        List<SetColorMarkupItem> _LoadMakupList = new List<SetColorMarkupItem>();
121
        List<int> _lstPrintPageNo = new List<int>();
122

    
123
        System.Windows.Threading.DispatcherTimer tm = new System.Windows.Threading.DispatcherTimer();
124
        bool _initializeComponentFinished; //이벤트
125
        bool _IsDagSlider = false; //드래그 상태인가
126
        bool IsExportOrPrint = false;
127
        bool IsStop = false;
128

    
129
        List<DisplayColorInfo> colorList = new List<DisplayColorInfo>();
130
        DefinedPages DocumentInfo { get; set; } //문서정보 정의        
131
        //PdfSharp.Pdf.PdfDocument document { get; set; } // pdfsharp 인데 아직 왜 넣었는지 모름 
132
        delegate void PrintEventHandler(); //프린트 핸들러
133
        SaveFileDialog SaveDig = new SaveFileDialog(); //파일 세이브 다이얼로그
134
        //SaveFileDialog SaveFile { get; set; } //저장할 때 사용
135

    
136
        //RasterImageViewer _viewer; //이미지 뷰어
137
        //System.Windows.Controls.Image backimg; //백그라운드 이미지
138
        System.Drawing.Image Printimg; //프린트 이미지
139
        System.Drawing.Image p_img; //프린트 이미지
140
        iTextSharp.text.Image Export_img;
141
        Dictionary<int, System.Drawing.Image> Printimg_List; //프린트 이미지
142
        Dictionary<int, string> PrintimgPath_List; //프린트 이미지 파일 경로
143
        string TempImageDir = null;
144

    
145
        //RasterCodecs codecs;
146
        int currentPage;
147
        public string PrintName;
148
        public string Type;
149

    
150
        public System.Timers.Timer timm = new System.Timers.Timer();
151

    
152

    
153
        #endregion
154

    
155
        #region Static Property Defines
156

    
157
        public static readonly DependencyProperty BusyContentProperty =
158
            DependencyProperty.RegisterAttached("BusyContent", typeof(string), typeof(PrintControl),
159
            new PropertyMetadata(new PropertyChangedCallback(BusyContentPropertyChanged)));
160
        #endregion
161

    
162
        #region Property
163
        public string BusyContent
164
        {
165
            get { return (string)GetValue(BusyContentProperty); }
166
            set { SetValue(BusyContentProperty, value); }
167
        }
168
        #endregion
169

    
170
        #region PropertyChangeMethod
171
        private static void BusyContentPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
172
        {
173
        }
174

    
175
        public static readonly DependencyProperty CurrentPageNoProperty =
176
                   DependencyProperty.Register("CurrentPageNo", typeof(int), typeof(PrintControl),
177
                   new PropertyMetadata(new PropertyChangedCallback(CurrentPageNoPropertyChanged)));
178
        #endregion
179

    
180
        #region Property
181
        public int CurrentPageNo
182
        {
183
            get { return (int)GetValue(CurrentPageNoProperty); }
184
            set { SetValue(CurrentPageNoProperty, value); }
185
        }
186
        #endregion
187

    
188
        #region PropertyChangeMethod
189
        private static void CurrentPageNoPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
190
        {
191
            var printPage = (PrintControl)d;
192
            var newValue = (int)e.NewValue;
193

    
194
            printPage.sliderPages.Value = newValue;
195
            printPage.SetLoadMakupList(newValue);
196

    
197
        }
198
        #endregion
199

    
200
        #region 생성자
201

    
202
        public PrintControl(string TileSourceUri, string ProjectNo, DOCINFO DocInfo, List<IKCOM.MarkupInfoItem> markupInfo, int CurrentPageNo, string slip, string title, string fileurl, bool isPrint)
203
        {
204
            InitializeComponent();
205

    
206
            this.Unloaded += (snd, evt) =>
207
            {
208
                try
209
                {
210
                    if (Directory.Exists(TempImageDir))
211
                        Directory.Delete(TempImageDir, true);
212
                }
213
                catch (Exception)
214
                {
215
                }
216
            };
217

    
218
            this.IsEnabled = true;
219

    
220
            //Layer Control을 통째로 가져와야 하는건가
221
            this._DocInfo = DocInfo;
222
            this._DefaultTileUri = TileSourceUri;
223
            this.ProjectNo = ProjectNo;
224
            this._StartPageNo = CurrentPageNo;
225

    
226
            markupInfo.ForEach(info => this._markupInfo.Add(info));
227

    
228
            foreach (var info in _markupInfo)
229
            {
230
                if (info.Consolidate == 1)
231
                {
232
                    info.UserName = "Consolidation";
233
                }
234
                info.MarkupList.ForEach(makup =>
235
                {
236
                    var _pageMarkup = _PageMarkupList.Where(item => item.PageNumber == makup.PageNumber);
237
                    var _SetMarkupItem = new SetColorMarkupItem { markupID = makup.ID, DisplayColor = info.DisplayColor };
238

    
239
                    if (_pageMarkup.Count() > 0)
240
                        _pageMarkup.First().DisplayColorItems.Add(_SetMarkupItem);
241
                    else
242
                        _PageMarkupList.Add(new MarkupPageItem
243
                        {
244
                            PageNumber = makup.PageNumber,
245
                            DisplayColorItems = new List<SetColorMarkupItem> { _SetMarkupItem }
246
                        });
247
                });
248

    
249
                colorList.Add(new DisplayColorInfo
250
                {
251
                    UserID = info.UserID,
252
                    DisplayColor = info.DisplayColor,
253
                    Department = info.Depatment,
254
                    UserName = info.UserName,
255
                });
256
            }
257

    
258
            gridViewMarkup.ItemsSource = this._markupInfo;
259
            SetLoadMakupList(this._StartPageNo);
260
            if (_LoadMakupList.Count() == 0)
261
                chkOnlyMarkup.IsChecked = false;
262

    
263
            this.CurrentPageNo = _StartPageNo;
264

    
265
            _definePages = new DefinedPages { DefinedPagesStrings = "", DocumentInfo = this._DocInfo
266
                            , PagesCount = Convert.ToInt32(this._DocInfo.PAGE_COUNT), vpSlip = slip, vpTitle = title, fileUrl = fileurl };
267

    
268
            DocumentInfo = _definePages;
269
            this.DataContext = _definePages;
270

    
271
            CheckCommentPages();
272

    
273
            //초기화면 Comment Check된 상태로 보여주기
274
            foreach (var item in _markupInfo)
275
            {
276
                gridViewMarkup.SelectedItems.Add(item);
277
            }
278

    
279
            PageChangeAsync(Common.ViewerDataModel.Instance.NewPagImageCancelToken(), _StartPageNo,false).ConfigureAwait(true);
280

    
281
            sliderPages.Maximum = Convert.ToDouble(this._DocInfo.PAGE_COUNT);
282
            this.stPageNo.Maximum = Convert.ToDouble(this._DocInfo.PAGE_COUNT);
283
            this.edPageNo.Maximum = Convert.ToDouble(this._DocInfo.PAGE_COUNT);
284
            this.IsPrint = isPrint;
285

    
286
            if (!IsPrint)
287
            {
288
                GetPrint(false);
289
                btnWholeExport.Visibility = Visibility.Visible;
290
                btnWholePrint.Visibility = Visibility.Collapsed;
291
                Selected_Print.Header = "Export Type";
292
            }
293
            else
294
            {
295
                //PrintList 가져오기
296
                GetPrint(true);
297
                btnWholePrint.Visibility = Visibility.Visible;
298
                btnWholeExport.Visibility = Visibility.Collapsed;
299
            }
300

    
301
            _initializeComponentFinished = true;
302

    
303
            //timm.Interval = 10;
304
            //timm.Elapsed += new System.Timers.ElapsedEventHandler(_Timer_Elapsed);
305
            //timm.Enabled = true;
306
        }
307

    
308
        #endregion
309

    
310
        #region Control Event
311
        private async void sliderPages_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
312
        {
313
            if (_initializeComponentFinished)
314
            {
315
                if (!_IsDagSlider)
316
                {
317
                    this.CurrentPageNo = (int)this.sliderPages.Value;
318

    
319
                    if (!IsExportOrPrint)
320
                    {
321
                        await PageChangeAsync(Common.ViewerDataModel.Instance.NewPagImageCancelToken(), this.CurrentPageNo, false);
322
                    }
323
                    //await App.PageStorage.GetPageUriAsync(this.CurrentPageNo);
324
                
325
                    if (_ButtonName == "Current")
326
                    {
327
                        stPageNo.Value = CurrentPageNo;
328
                        edPageNo.Value = CurrentPageNo;
329
                    }
330

    
331
                    //CheckCommentPages();
332
                }
333
            }
334
        }
335

    
336
        private async void sliderPages_DragCompleted(object sender, RadDragCompletedEventArgs e)
337
        {
338
            _IsDagSlider = false;
339
            this.CurrentPageNo = (int)this.sliderPages.Value;
340
            if (_initializeComponentFinished)
341
            {
342
               
343
            }
344
        }
345

    
346
        private void sliderPages_DragStarted(object sender, RadDragStartedEventArgs e)
347
        {
348
            _IsDagSlider = true;
349
        }
350

    
351
        private void chkOnlyMarkup_Checked(object sender, RoutedEventArgs e)
352
        {
353
            if (_initializeComponentFinished)      //GridRangePages
354
            {
355
                CheckCommentPages();
356
            }
357
        }
358

    
359
        private void chkOnlyRedColor_Checked(object sender, RoutedEventArgs e)
360
        {
361
            if (_initializeComponentFinished)      //GridRangePages
362
            {
363
                CheckCommentPages();
364
            }
365
        }
366
        
367

    
368
        string _ButtonName;
369
        private void PageSelect_Checked(object sender, RoutedEventArgs e)
370
        {
371
            if (!_initializeComponentFinished) return;
372

    
373
            _ButtonName = (sender as RadRadioButton).Tag.ToString();
374
            CommentPageList.ItemsSource = null;
375

    
376
            switch (_ButtonName)
377
            {
378
                case "Current":
379
                    stPageNo.Value = CurrentPageNo;
380
                    edPageNo.Value = CurrentPageNo;
381

    
382
                    GridCurrentPage.Visibility = Visibility.Visible;
383
                    GridDefinePages.Visibility = Visibility.Collapsed;
384
                    GridRangePages.Visibility = Visibility.Collapsed;
385
                    GridAllPages.Visibility = Visibility.Collapsed;
386

    
387
                    break;
388
                case "RangePrint":
389
                    GridCurrentPage.Visibility = Visibility.Collapsed;
390
                    GridDefinePages.Visibility = Visibility.Visible;
391
                    GridRangePages.Visibility = Visibility.Collapsed;
392
                    GridAllPages.Visibility = Visibility.Collapsed;
393
                    break;
394
                case "UserDefined":
395
                    GridCurrentPage.Visibility = Visibility.Collapsed;
396
                    GridDefinePages.Visibility = Visibility.Collapsed;
397
                    GridRangePages.Visibility = Visibility.Visible;
398
                    GridAllPages.Visibility = Visibility.Collapsed;
399
                    break;
400
                case "AllPrint":
401
                    stPageNo.Value = 1;
402
                    edPageNo.Value = Convert.ToDouble(_DocInfo.PAGE_COUNT);
403
                    GridCurrentPage.Visibility = Visibility.Collapsed;
404
                    GridDefinePages.Visibility = Visibility.Collapsed;
405
                    GridRangePages.Visibility = Visibility.Collapsed;
406
                    GridAllPages.Visibility = Visibility.Visible;
407
                    break;
408
            }
409

    
410
            CheckCommentPages();
411
        }
412

    
413
        private void PageNo_ValueChanged(object sender, RadRangeBaseValueChangedEventArgs e)
414
        {
415
            if (_initializeComponentFinished)      //GridRangePages
416
            {
417
                if (stPageNo.Value > edPageNo.Value)
418
                {
419
                    if (sender.Equals(stPageNo))
420
                        edPageNo.Value = stPageNo.Value;
421
                    else
422
                        stPageNo.Value = edPageNo.Value;
423
                }
424

    
425
                //뷰어잠시제외(강인구)
426
                //this.LayoutRoot.Dispatcher.BeginInvoke(delegate()
427
                //{
428
                CheckCommentPages();
429
                //});
430
            }
431
        }
432

    
433
        private void txtDefinedPages_TextChanged(object sender, TextChangedEventArgs e)
434
        {
435
            CheckCommentPages();
436
        }
437

    
438
        private void btnClearDefinedPages_Click(object sender, RoutedEventArgs e)
439
        {
440
            txtDefinedPages.Text = "";
441
        }
442

    
443
        private void CommentPageList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
444
        {
445
            if (_initializeComponentFinished)
446
                if (CommentPageList.SelectedItem != null)
447
                    this.CurrentPageNo = (CommentPageList.SelectedItem as MarkupPageItem).PageNumber;
448
        }
449

    
450
        private async void gridViewMarkup_SelectionChanged(object sender, SelectionChangeEventArgs e)
451
        {
452
            if (_initializeComponentFinished)
453
            {
454
                await PageChangeAsync(Common.ViewerDataModel.Instance.NewPagImageCancelToken(),this.CurrentPageNo, false);
455
            }
456
        }
457

    
458
        #endregion
459

    
460
        public async System.Threading.Tasks.Task<bool> PageChangeAsync(System.Threading.CancellationToken cts, int PageNo,bool saveFile, bool Flag = false)
461
        {
462
            System.Diagnostics.Debug.WriteLine("PageChangeAsync " + PageNo);
463
            bool result = false;
464
            //Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate
465
            //{
466
            try
467
            {
468
                Load load = new Load();
469

    
470
                _definePages.Back_Image = new ImageBrush();
471
                //var defaultBitmapImage = new BitmapImage(new Uri(_DefaultTileUri + PageNo + ".png"));
472

    
473
                var pages = _definePages.DocumentInfo.DOCPAGE.Where(x => x.PAGE_NUMBER == PageNo);
474

    
475
                if(pages.Count() > 0)
476
                {
477
                    var currentPage = pages.First();
478

    
479
                    //var buffer = await new WebClient().DownloadDataTaskAsync(_DefaultTileUri + PageNo + ".png");
480

    
481
                    //var bitmap = new BitmapImage();
482
                    //using (var stream = new MemoryStream(buffer))
483
                    //{
484
                    //bitmap.BeginInit();
485
                    //bitmap.CacheOption = BitmapCacheOption.OnLoad;
486
                    //bitmap.StreamSource = stream;
487
                    //bitmap.EndInit();
488

    
489
                        
490
                    var uri = await App.PageStorage.GetPageUriAsync(cts, currentPage.PAGE_NUMBER);
491
                    //Image bitmap = new Image();
492
                    //bitmap.Stretch = Stretch.Fill;
493
                    //bitmap.Source = bitmapframe;
494
                    //bitmap.Width = Convert.ToDouble(currentPage.PAGE_WIDTH);
495
                    //bitmap.Height = Convert.ToDouble(currentPage.PAGE_HEIGHT);
496

    
497
                    //if (uri.Scheme == Uri.UriSchemeFile)
498
                    //{
499
                    //    var cloneUri = new Uri(System.IO.Path.Combine(System.IO.Path.GetTempPath(),System.IO.Path.GetRandomFileName()),UriKind.Absolute);
500
                    //    File.Copy(uri.LocalPath, cloneUri.LocalPath);
501

    
502
                    //    uri = cloneUri;
503
                    //}
504

    
505
                    printCanvas.Children.Clear();
506
                    printCanvas.Width = Convert.ToDouble(currentPage.PAGE_WIDTH);
507
                    printCanvas.Height = Convert.ToDouble(currentPage.PAGE_HEIGHT);
508
                    
509
                    printCanvas.Background = new ImageBrush{ ImageSource = new BitmapImage(uri)};
510

    
511
                    //printCanvas.RenderTransformOrigin = new Point(0.5, 0.5);
512
                    //printCanvas.RenderTransform = new RotateTransform(currentPage.PAGE_ANGLE);
513
                    //ImageBrush background = new ImageBrush(bitmap);
514
                    //printCanvas.Background = background;
515
                    //printCanvas.Background = new SolidColorBrush(Colors.Transparent);
516

    
517

    
518
                    foreach (var info in gridViewMarkup.SelectedItems.Cast<IKCOM.MarkupInfoItem>())
519
                    {
520
                        load.User_Id = info.UserID;
521
                        load.document_id = _DocInfo.DOCUMENT_ID;
522
                        load.Page_No = PageNo;
523

    
524
                        if (chkOnlyRedColor.IsChecked == true)
525
                        {
526
                            load.DisplayColor = "#FFFF0000";
527
                        }
528
                        else
529
                        {
530
                            load.DisplayColor = info.DisplayColor;
531
                        }
532

    
533
                        load.Markupinfoid = info.MarkupInfoID;
534
                        var IsLoad = await load.Markup_LoadAsync(printCanvas, 0);
535
                    }
536
                    //await Dispatcher.InvokeAsync(() => {
537
                    //    printCanvas.UpdateLayout();
538
                    //});
539

    
540
                    if (Flag)
541
                        {
542
                        //MemoryStream ms = new MemoryStream();
543
                        //BmpBitmapEncoder bbe = new BmpBitmapEncoder();
544
                        //bbe.Frames.Add(BitmapFrame.Create(new Uri(_DefaultTileUri + PageNo + ".png")));
545
                        //bbe.Save(ms);
546

    
547
                        //System.Drawing.Image.FromFile()
548
                        //Printimg = System.Drawing.Image.FromStream(stream);
549
                        //await System.Threading.Tasks.Task.Run(() =>
550
                        //{
551
                           await Dispatcher.InvokeAsync(() =>
552
                            {
553
                                Export export = new Export();
554

    
555
                                if (saveFile)
556
                                {
557
                                    var filepath = Path.Combine(TempImageDir, $"{PrintimgPath_List.Count() + 1}.png");
558

    
559
                                    if (export.ExportingFile(PrintView, printCanvas.Width, printCanvas.Height, filepath))
560
                                    {
561
                                        PrintimgPath_List.Add(PrintimgPath_List.Count() + 1, filepath);
562
                                    }
563
                                    else
564
                                    {
565
                                        throw new Exception($"Export Image Save File Error :{filepath}");
566
                                    }
567
                                }
568
                                else
569
                                {
570
                                    p_img = export.Exporting(PrintView, printCanvas.Width, printCanvas.Height);
571
                                    Printimg_List.Add(Printimg_List.Count() + 1, p_img);
572
                                }
573

    
574
                            },System.Windows.Threading.DispatcherPriority.SystemIdle);
575
                        //});
576
                    }
577

    
578
                        result = true;
579
                    //}
580
                } 
581
            }
582
            catch (Exception ex)
583
            {
584
                //Logger.sendResLog("PrintControl.PageChanged", ex.Message, 0);
585
            }
586

    
587
            return result;
588
            //}));
589
        }
590

    
591

    
592
        public static MemoryStream ByteBufferFromImage(BitmapImage imageSource)
593
        {
594
            var ms = new MemoryStream();
595
            var pngEncoder = new PngBitmapEncoder();
596
            pngEncoder.Frames.Add(BitmapFrame.Create(imageSource));
597
            pngEncoder.Save(ms);
598

    
599
            return ms;
600
        }
601
        //Print 버튼 클릭 이벤트
602
        #region Method - 명령
603
        async void PrintMethod(object sender, RoutedEventArgs e)
604
        {
605
            try
606
            {
607
                var token = Common.ViewerDataModel.Instance.NewPagImageCancelToken();
608

    
609
                if (this.printIndy.IsBusy == true)
610
                    return;
611

    
612
                (this.Parent as RadWindow).CanClose = false;
613

    
614
                await this.Dispatcher.InvokeAsync(() => { 
615
                        this.printIndy.IsBusy = true;
616
                        this.BusyContent = "Printing. . .";
617
                });
618

    
619

    
620
                _lstPrintPageNo = PrintPageCreate();
621

    
622
                if (_lstPrintPageNo.Count == 0)
623
                {
624
                    RadWindow.Alert(new DialogParameters
625
                    {
626
                        Owner = Application.Current.MainWindow,
627
                        Theme = new VisualStudio2013Theme(),
628
                        Header = "Info",
629
                        Content = "Not specified the page."
630
                    });
631
                    sliderPages.Value = 1;
632
                    this.printIndy.IsBusy = false;
633
                    return;
634
                }
635

    
636
                int cnt = 0;
637

    
638
                IsExportOrPrint = true;
639

    
640
                Printimg_List = new Dictionary<int, System.Drawing.Image>();
641
                PrintimgPath_List = new Dictionary<int, string>();
642
                TempImageDir = Path.Combine(Path.GetTempPath(), "Markus", Common.Commons.ShortGuid());
643

    
644
                if (Directory.Exists(TempImageDir))
645
                {
646
                    Directory.Delete(TempImageDir, true);
647
                }
648

    
649
                Directory.CreateDirectory(TempImageDir);
650

    
651
                foreach (int PageNo in _lstPrintPageNo)
652
                {
653
                    if (IsStop)
654
                        break;
655

    
656
                    cnt++;
657
                    sliderPages.Value = PageNo;
658
                    await PageChangeAsync(token,PageNo, true, true);
659
                    //PageChanged(cnt, true);
660
                }
661
                PrintName = cbPrint.SelectedItem.ToString();
662

    
663
                await this.Dispatcher.InvokeAsync(() => {
664
                    if (cnt == _lstPrintPageNo.Count && !IsStop)
665
                    {
666
                        Printing();
667
                    }
668
                });
669

    
670
                IsExportOrPrint = false;
671
            }
672
            catch (Exception ex)
673
            {
674
                //Logger.sendResLog("PrintMethod", ex.Message, 0);
675
            }
676
            finally
677
            {
678
                if (IsStop)
679
                {
680
                    printIndy.IsBusy = false;
681
                    IsStop = false;
682
                }
683
                (this.Parent as RadWindow).CanClose = true;
684
            }
685

    
686
        }
687

    
688
        //Export 버튼 클릭 이벤트
689
        [System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions]
690
        //[System.Security.Permissions.FileIOPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
691
        async void ExportMethod(object sender, RoutedEventArgs e)
692
        {
693
            try
694
            {
695
                if (this.printIndy.IsBusy == true)
696
                    return;
697

    
698
                var token = Common.ViewerDataModel.Instance.NewPagImageCancelToken();
699

    
700
                (this.Parent as RadWindow).CanClose = false;
701

    
702
                this.printIndy.IsBusy = true;
703
                this.BusyContent = "Exporting. . .";
704

    
705
                Export export = new Export();
706
                _lstPrintPageNo = PrintPageCreate();
707

    
708
                if (_lstPrintPageNo.Count == 0)
709
                {
710
                    sliderPages.Value = 1;
711
                    this.printIndy.IsBusy = false;
712
                    RadWindow.Alert(new DialogParameters
713
                    {
714
                        Owner = Application.Current.MainWindow,
715
                        Theme = new VisualStudio2013Theme(),
716
                        Header = "Info",
717
                        Content = "Not specified the page.",
718
                    });
719
                    return;
720
                }
721

    
722
                //FileDialogFilter filterImage = new FileDialogFilter("Image Files", "*.jpg", "*.png");
723

    
724
                switch (cbPrint.SelectedIndex)
725
                {
726
                    case (0):
727
                        {
728
                            SaveDig.Filter = "PDF file format|*.pdf";
729
                            break;
730
                        }
731
                    case (1):
732
                        {
733
                            SaveDig.Filter = "Image Files (*.jpg, *.Jpeg)|*.jpg;*.Jpeg";
734
                            break;
735
                        }
736
                }
737

    
738
                SaveDig.Title = "Save an PDF File";
739
                if(SaveDig.ShowDialog().Value)
740
                {
741
                    IsExportOrPrint = true;
742

    
743
                    PrintimgPath_List = new Dictionary<int, string>();
744
                    TempImageDir = Path.Combine(Path.GetTempPath(), "Markus", Common.Commons.ShortGuid());
745

    
746
                    if (Directory.Exists(TempImageDir))
747
                    {
748
                        Directory.Delete(TempImageDir, true);
749
                    }
750

    
751
                    Directory.CreateDirectory(TempImageDir);
752

    
753
                    foreach (int PageNo in _lstPrintPageNo)
754
                    {
755
                        if (IsStop)
756
                            break;
757

    
758
                        await Dispatcher.InvokeAsync(() =>
759
                        {
760
                            sliderPages.Value = PageNo;
761
                        });
762

    
763
                        await PageChangeAsync(token, PageNo, true, true);
764

    
765
                        System.Diagnostics.Debug.WriteLine("Export Page : " + PageNo);
766
                    }
767

    
768
                    //using (FileStream fs = new FileStream(@"D:\Temp\Text.pdf", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
769

    
770
                    if (SaveDig.FileName != "")
771
                    {
772
                        switch (cbPrint.SelectedIndex)
773
                        {
774
                            case (0):
775
                                {
776
                                    FileStream fs = new FileStream(SaveDig.FileName, FileMode.Create, FileAccess.Write);
777

    
778
                                    Document doc = new Document();
779
                                    try
780
                                    {
781
                                        iTextSharp.text.Version.GetInstance();
782
                                    }
783
                                    catch (System.NullReferenceException ex)
784
                                    {
785

    
786
                                    }
787

    
788
                                    PdfWriter writer = PdfWriter.GetInstance(doc, fs);
789

    
790
                                    doc.Open();
791
                                    
792
                                    float height = doc.PageSize.Height;
793
                                    float width = doc.PageSize.Width;
794

    
795
                                    foreach (var item in PrintimgPath_List)
796
                                    {
797
                                        if (IsStop)
798
                                            break;
799

    
800
                                        System.Drawing.Image image = System.Drawing.Image.FromFile(item.Value);
801
                                        Export_img = iTextSharp.text.Image.GetInstance(image,System.Drawing.Imaging.ImageFormat.Jpeg);
802

    
803
                                        if (Export_img.Width > Export_img.Height)
804
                                        {
805
                                            doc.SetPageSize(new Rectangle(height, width));
806
                                            Export_img.ScaleToFit(height, width);
807
                                        }
808
                                        else
809
                                        {
810
                                            doc.SetPageSize(new Rectangle(width, height));
811
                                            Export_img.ScaleToFit(width, height);
812
                                        }
813

    
814
                                        Export_img.SetAbsolutePosition(0, 0);
815

    
816
                                        doc.NewPage();
817
                                        doc.Add(Export_img);
818
                                    }
819
                                    doc.Close();
820
                                    writer.Close();
821
                                    break;
822
                                }
823
                            case (1):
824
                                {
825
                                    foreach (var item in PrintimgPath_List)
826
                                    {
827
                                        if (IsStop)
828
                                            break;
829

    
830
                                        File.Copy(item.Value, SaveDig.FileName.Replace(".jpg", "_" + item.Key.ToString()) + ".jpg");
831
                                    }
832
                                    break;
833
                                }
834
                        }
835
                    }
836
                    else
837
                    {
838
                        sliderPages.Value = 1;
839
                        this.printIndy.IsBusy = false;
840
                        return;
841
                    }
842

    
843
                    await this.Dispatcher.InvokeAsync(() =>
844
                    {
845
                        sliderPages.Value = 1;
846
                        printIndy.IsBusy = false;
847
                    });
848

    
849
                    await PageChangeAsync(token,_StartPageNo, false);
850

    
851
                    IsExportOrPrint = false;
852

    
853
                    (Application.Current.MainWindow as MainWindow).dzMainMenu.DialogMessage_Alert("Success", "Alert");
854
                }else
855
                {
856
                    Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate
857
                    {
858
                        sliderPages.Value = 1;
859
                        printIndy.IsBusy = false;
860
                    }));
861

    
862
                    //(Application.Current.MainWindow as MainWindow).dzMainMenu.DialogMessage_Alert("Cancel", "Alert");
863
                }                
864
            }
865
            catch (Exception ex)
866
            {
867
                sliderPages.Value = 1;
868
                printIndy.IsBusy = false;
869

    
870
                //Logger.sendResLog("Export Method", ex.Message, 0);
871
                //(Application.Current.MainWindow as MainWindow).dzMainMenu.DialogMessage_Alert("Alert", "관리자 확인이 필요합니다. 다시 시도해 주세요.\n"+ex.Message);
872
            }
873
            finally
874
            {
875
                GC.Collect();
876
                GC.WaitForPendingFinalizers();
877
                GC.Collect();
878
                IsStop = false;
879
                (this.Parent as RadWindow).CanClose = true;
880
            }
881
        }
882

    
883
        #endregion
884

    
885
        #region Method - 처리
886
        void CheckCommentPages()
887
        {
888
            List<MarkupPageItem> _pages = new List<MarkupPageItem>();
889
            DoubleCollection _Ticks = new DoubleCollection();
890

    
891

    
892
            if (GridCurrentPage.Visibility == System.Windows.Visibility.Visible)
893
            {
894

    
895
                _pages = (from commPage in this._PageMarkupList
896
                          where commPage.PageNumber == CurrentPageNo
897
                          orderby commPage.PageNumber
898
                          select commPage).ToList();
899
            }
900
            else if (GridRangePages.Visibility == System.Windows.Visibility.Visible)
901
            {
902
                stPageNo.Value = stPageNo.Value == null ? 1 : stPageNo.Value;
903
                edPageNo.Value = edPageNo.Value == null ? 1 : edPageNo.Value;
904

    
905
                int _stPage = (int)stPageNo.Value;
906
                int _edPage = (int)edPageNo.Value;
907

    
908
                _pages = (from commPage in this._PageMarkupList
909
                          where commPage.PageNumber >= _stPage && commPage.PageNumber <= _edPage
910
                          orderby commPage.PageNumber
911
                          select commPage).ToList();
912
            }
913
            else if (GridDefinePages.Visibility == System.Windows.Visibility.Visible)
914
            {
915
                stPageNo.Value = stPageNo.Value == null ? 1 : stPageNo.Value;
916
                edPageNo.Value = edPageNo.Value == null ? 1 : edPageNo.Value;
917

    
918
                int _stPage = (int)stPageNo.Value;
919
                int _edPage = (int)edPageNo.Value;
920

    
921
                //Using DeepView.Common.RangeParser
922
                var lst = RangeParser.Parse(txtDefinedPages.Text, _stPage, _definePages.PagesCount);
923
                _pages = (from commPage in this._PageMarkupList
924
                          from compareData in lst
925
                          where commPage.PageNumber == compareData
926
                          orderby commPage.PageNumber
927
                          select commPage).ToList();
928
            }
929
            else
930
            {
931
                _pages = (from commPage in this._PageMarkupList
932
                          orderby commPage.PageNumber
933
                          select commPage).ToList();
934
            }
935

    
936
            CommentPageList.ItemsSource = _pages.ToList();
937
        }
938

    
939
        void SetLoadMakupList(int PageNo)
940
        {
941
            _LoadMakupList.Clear();
942
            var _markupList = _PageMarkupList.Where(page => page.PageNumber == PageNo);
943

    
944
            if (_markupList.Count() > 0)
945
                _LoadMakupList = _markupList.First().DisplayColorItems.ToList();
946
        }
947

    
948
        #region 프린트 리스트 가져오기
949
        public void GetPrint(bool flag)
950
        {
951
            if (flag)
952
            {
953
                foreach (string printer in PrinterSettings.InstalledPrinters)
954
                {
955
                    this.cbPrint.Items.Add(printer);
956
                }
957
                printDocument = new PrintDocument();
958
                this.cbPrint.SelectedItem = printDocument.PrinterSettings.PrinterName;
959
            }
960
            else
961
            {
962
                this.cbPrint.Items.Add("PDF");
963
                this.cbPrint.Items.Add("IMAGE");
964

    
965
                this.cbPrint.SelectedItem = "PDF";
966
            }
967
        }
968
        #endregion
969

    
970
        #region 프린트 실행
971
        public async void Printing()
972
        {
973
            var token = Common.ViewerDataModel.Instance.NewPagImageCancelToken ();
974

    
975
            await PageChangeAsync(token,1, false);
976

    
977
            if (PrinterSettings.InstalledPrinters != null && PrinterSettings.InstalledPrinters.Count > 0)
978
            {
979
                printDocument = new PrintDocument();
980
                printDocument.OriginAtMargins = true;
981
                printDocument.BeginPrint += new System.Drawing.Printing.PrintEventHandler(printDocument_BeginPrint);
982
                printDocument.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(printDocument_PrintPage);
983
                printDocument.EndPrint += new System.Drawing.Printing.PrintEventHandler(printDocument_EndPrint);
984
            }
985
            else
986
                printDocument = null;
987

    
988
            #region 인쇄 미리보기 테스트
989
            using (System.Windows.Forms.PrintPreviewDialog dlg = new System.Windows.Forms.PrintPreviewDialog())
990
            {
991
                printDocument.PrinterSettings.MinimumPage = 1;
992
                printDocument.PrinterSettings.MaximumPage = _lstPrintPageNo.Count();
993
                printDocument.PrinterSettings.FromPage = 1;
994
                printDocument.PrinterSettings.ToPage = _lstPrintPageNo.Count();
995
                printDocument.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
996
                printDocument.PrinterSettings.PrinterName = PrintName;
997
                dlg.Document = printDocument;
998
                dlg.WindowState = System.Windows.Forms.FormWindowState.Maximized;
999
                dlg.ShowDialog();
1000
            }
1001
            #endregion
1002

    
1003
            #region 인쇄
1004
            //printDocument.PrinterSettings.MinimumPage = 1;
1005
            //printDocument.PrinterSettings.MaximumPage = _lstPrintPageNo.Count();
1006
            //printDocument.PrinterSettings.FromPage = 1;
1007
            //printDocument.PrinterSettings.ToPage = _lstPrintPageNo.Count();
1008

    
1009
            //printDocument.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
1010
            //printDocument.PrinterSettings.PrinterName = PrintName;
1011

    
1012
            //printDocument.Print();
1013
            #endregion
1014
        }
1015

    
1016
        private void printDocument_BeginPrint(object sender, PrintEventArgs e)
1017
        {
1018
            //Printimg_List = new Dictionary<int, System.Drawing.Image>();
1019
            // This demo only loads one page at a time, so no need to re-set the print page number
1020
            PrintDocument document = sender as PrintDocument;
1021
            currentPage = document.PrinterSettings.FromPage;
1022
        }
1023

    
1024
        private void printDocument_PrintPage(object sender, PrintPageEventArgs e)
1025
        {
1026
            //e.Graphics.DrawImage(Printimg_List.Where(info => info.Key == currentPage).FirstOrDefault().Value, 0, 0);
1027

    
1028
            Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate
1029
            {
1030
                //p_img = Printimg_List.Where(data => data.Key == currentPage).FirstOrDefault().Value;
1031
                p_img = System.Drawing.Image.FromFile(PrintimgPath_List.Where(data => data.Key == currentPage).FirstOrDefault().Value);
1032

    
1033
                if (p_img.Width > p_img.Height)
1034
                {
1035
                    p_img.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
1036
                }
1037

    
1038
                //iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(p_img, System.Drawing.Imaging.ImageFormat.Jpeg);
1039
                System.Drawing.Image pic = p_img;
1040
                System.Drawing.Rectangle m = e.MarginBounds;
1041

    
1042
                //if ((double)pic.Width / (double)pic.Height > (double)m.Width / (double)m.Height) // image is wider
1043
                //{
1044
                //    m.Height = 1135;//(int)((double)pic.Height / (double)pic.Width * (double)m.Width) - 16;
1045
                //}
1046
                //else
1047
                //{
1048
                //    m.Width = 793;//(int)((double)pic.Width / (double)pic.Height * (double)m.Height) - 16;
1049
                //}
1050
                m.Width = (int)e.PageSettings.PrintableArea.Width;
1051
                m.Height = (int)e.PageSettings.PrintableArea.Height;
1052
                m.X = (int)e.PageSettings.HardMarginX;
1053
                m.Y = (int)e.PageSettings.HardMarginY;
1054

    
1055
                e.Graphics.DrawImage(pic, m);
1056
                //e.Graphics.DrawImage(p_img, e.MarginBounds);
1057
                //e.Graphics.DrawImage(p_img, 0, 0);
1058
            }));
1059

    
1060
            //다음 페이지
1061
            currentPage++;
1062

    
1063
            ////인쇄를 계속 할지 말지 확인
1064
            if (currentPage <= printDocument.PrinterSettings.ToPage && !IsStop)
1065
                e.HasMorePages = true;
1066
            else
1067
                e.HasMorePages = false;
1068

    
1069
        }
1070

    
1071
        private void printDocument_EndPrint(object sender, PrintEventArgs e)
1072
        {
1073
            Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate
1074
            {
1075
                //if (Directory.Exists(TempImageDir))
1076
                //    Directory.Delete(TempImageDir, true);
1077

    
1078
                sliderPages.Value = 1;
1079
                printIndy.IsBusy = false;
1080
                IsStop = false;
1081
            }));
1082
        }
1083
        #endregion
1084

    
1085
        #region Selected Pages Check
1086
        List<int> PrintPageCreate()
1087
        {
1088
            List<int> Result = new List<int>();
1089

    
1090
            if (GridCurrentPage.Visibility == System.Windows.Visibility.Visible || currentPagePrint)
1091
            {
1092
                Result.Add(CurrentPageNo);
1093
            }
1094
            else if (GridRangePages.Visibility == System.Windows.Visibility.Visible)
1095
            {
1096
                for (int i = Convert.ToInt32(stPageNo.Value); i <= Convert.ToInt32(edPageNo.Value); i++)
1097
                {
1098
                    Result.Add(i);
1099
                }
1100
            }
1101
            else if (GridDefinePages.Visibility == System.Windows.Visibility.Visible)
1102
            {
1103
                int _stPage = (int)stPageNo.Value;
1104
                int _edPage = (int)edPageNo.Value;
1105

    
1106
                var lst = RangeParser.Parse(txtDefinedPages.Text, _stPage, _definePages.PagesCount);
1107
                Result.AddRange(lst);
1108
            }
1109
            else
1110
            {
1111
                for (int i = 1; i <= _definePages.PagesCount; i++)
1112
                {
1113
                    Result.Add(i);
1114
                }
1115
            }
1116
            if (currentPagePrint)
1117
            {
1118
                return Result;
1119
            }
1120

    
1121
            if (chkOnlyMarkup.IsChecked.Value)
1122
            {
1123
                var _result = from result in Result
1124
                              where _PageMarkupList.Where(page => page.PageNumber == result).Count() > 0
1125
                              select result;
1126
                Result = _result.ToList();
1127
            }
1128
            return Result;
1129
        }
1130
        #endregion
1131

    
1132
        #endregion
1133

    
1134
        private void btPrintCancel_click(object sender, RoutedEventArgs e)
1135
        {
1136
            IsStop = true;
1137
        }
1138
    }
1139
}