프로젝트

일반

사용자정보

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

markus / KCOM / Controls / PrintControl.xaml.cs @ 6a19b48d

이력 | 보기 | 이력해설 | 다운로드 (41.1 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 Microsoft.Office.Core;
23
using System.Net;
24
using Image = System.Windows.Controls.Image;
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

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

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

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

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

    
151

    
152
        #endregion
153

    
154
        #region Static Property Defines
155
        public static readonly DependencyProperty CurrentPageNoProperty =
156
                   DependencyProperty.Register("CurrentPageNo", typeof(int), typeof(PrintControl),
157
                   new PropertyMetadata(new PropertyChangedCallback(CurrentPageNoPropertyChanged)));
158
        #endregion
159

    
160
        #region Property
161
        public int CurrentPageNo
162
        {
163
            get { return (int)GetValue(CurrentPageNoProperty); }
164
            set { SetValue(CurrentPageNoProperty, value); }
165
        }
166
        #endregion
167

    
168
        #region PropertyChangeMethod
169
        private static void CurrentPageNoPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
170
        {
171
            var printPage = (PrintControl)d;
172
            var newValue = (int)e.NewValue;
173

    
174
            printPage.sliderPages.Value = newValue;
175
            printPage.SetLoadMakupList(newValue);
176

    
177
        }
178
        #endregion
179

    
180
        #region 생성자
181

    
182
        public PrintControl(string TileSourceUri, string ProjectNo, DOCINFO DocInfo, List<IKCOM.MarkupInfoItem> markupInfo, int CurrentPageNo, string slip, string title, string fileurl, bool isPrint)
183
        {
184
            InitializeComponent();
185

    
186
            this.IsEnabled = true;
187

    
188
            //Layer Control을 통째로 가져와야 하는건가
189
            this._DocInfo = DocInfo;
190
            this._DefaultTileUri = TileSourceUri;
191
            this.ProjectNo = ProjectNo;
192
            this._StartPageNo = CurrentPageNo;
193

    
194
            markupInfo.ForEach(info => this._markupInfo.Add(info));
195

    
196
            foreach (var info in _markupInfo)
197
            {
198
                if (info.Consolidate == 1)
199
                {
200
                    info.UserName = "Consolidation";
201
                }
202
                info.MarkupList.ForEach(makup =>
203
                {
204
                    var _pageMarkup = _PageMarkupList.Where(item => item.PageNumber == makup.PageNumber);
205
                    var _SetMarkupItem = new SetColorMarkupItem { markupID = makup.ID, DisplayColor = info.DisplayColor };
206

    
207
                    if (_pageMarkup.Count() > 0)
208
                        _pageMarkup.First().DisplayColorItems.Add(_SetMarkupItem);
209
                    else
210
                        _PageMarkupList.Add(new MarkupPageItem
211
                        {
212
                            PageNumber = makup.PageNumber,
213
                            DisplayColorItems = new List<SetColorMarkupItem> { _SetMarkupItem }
214
                        });
215
                });
216

    
217
                colorList.Add(new DisplayColorInfo
218
                {
219
                    UserID = info.UserID,
220
                    DisplayColor = info.DisplayColor,
221
                    Department = info.Depatment,
222
                    UserName = info.UserName,
223
                });
224
            }
225

    
226
            gridViewMarkup.ItemsSource = this._markupInfo;
227
            SetLoadMakupList(this._StartPageNo);
228
            if (_LoadMakupList.Count() == 0)
229
                chkOnlyMarkup.IsChecked = false;
230

    
231
            this.CurrentPageNo = _StartPageNo;
232

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

    
236
            DocumentInfo = _definePages;
237
            this.DataContext = _definePages;
238

    
239
            CheckCommentPages();
240

    
241
            //초기화면 Comment Check된 상태로 보여주기
242
            foreach (var item in _markupInfo)
243
            {
244
                gridViewMarkup.SelectedItems.Add(item);
245
            }
246

    
247
            PageChangeAsync(Common.ViewerDataModel.Instance.NewCancellationToken(), _StartPageNo,false).ConfigureAwait(true);
248

    
249
            sliderPages.Maximum = Convert.ToDouble(this._DocInfo.PAGE_COUNT);
250
            this.stPageNo.Maximum = Convert.ToDouble(this._DocInfo.PAGE_COUNT);
251
            this.edPageNo.Maximum = Convert.ToDouble(this._DocInfo.PAGE_COUNT);
252
            this.IsPrint = isPrint;
253

    
254
            if (!IsPrint)
255
            {
256
                GetPrint(false);
257
                btnWholeExport.Visibility = Visibility.Visible;
258
                btnWholePrint.Visibility = Visibility.Collapsed;
259
                Selected_Print.Header = "Export Type";
260
            }
261
            else
262
            {
263
                //PrintList 가져오기
264
                GetPrint(true);
265
                btnWholePrint.Visibility = Visibility.Visible;
266
                btnWholeExport.Visibility = Visibility.Collapsed;
267
            }
268

    
269
            _initializeComponentFinished = true;
270

    
271
            //timm.Interval = 10;
272
            //timm.Elapsed += new System.Timers.ElapsedEventHandler(_Timer_Elapsed);
273
            //timm.Enabled = true;
274
        }
275

    
276
        #endregion
277

    
278
        #region Control Event
279
        private async void sliderPages_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
280
        {
281
            if (_initializeComponentFinished)
282
            {
283
                if (!_IsDagSlider)
284
                {
285
                    this.CurrentPageNo = (int)this.sliderPages.Value;
286

    
287
                    if (!IsExportOrPrint)
288
                    {
289
                        await PageChangeAsync(Common.ViewerDataModel.Instance.NewCancellationToken(), this.CurrentPageNo, false);
290
                    }
291
                    //await App.PageStorage.GetPageUriAsync(this.CurrentPageNo);
292
                
293
                    if (_ButtonName == "Current")
294
                    {
295
                        stPageNo.Value = CurrentPageNo;
296
                        edPageNo.Value = CurrentPageNo;
297
                    }
298

    
299
                    //CheckCommentPages();
300
                }
301
            }
302
        }
303

    
304
        private async void sliderPages_DragCompleted(object sender, RadDragCompletedEventArgs e)
305
        {
306
            _IsDagSlider = false;
307
            this.CurrentPageNo = (int)this.sliderPages.Value;
308
            if (_initializeComponentFinished)
309
            {
310
               
311
            }
312
        }
313

    
314
        private void sliderPages_DragStarted(object sender, RadDragStartedEventArgs e)
315
        {
316
            _IsDagSlider = true;
317
        }
318

    
319
        private void chkOnlyMarkup_Checked(object sender, RoutedEventArgs e)
320
        {
321
            if (_initializeComponentFinished)      //GridRangePages
322
            {
323
                CheckCommentPages();
324
            }
325
        }
326
        string _ButtonName;
327
        private void PageSelect_Checked(object sender, RoutedEventArgs e)
328
        {
329
            if (!_initializeComponentFinished) return;
330

    
331
            _ButtonName = (sender as RadRadioButton).Tag.ToString();
332
            CommentPageList.ItemsSource = null;
333

    
334
            switch (_ButtonName)
335
            {
336
                case "Current":
337
                    stPageNo.Value = CurrentPageNo;
338
                    edPageNo.Value = CurrentPageNo;
339

    
340
                    GridCurrentPage.Visibility = Visibility.Visible;
341
                    GridDefinePages.Visibility = Visibility.Collapsed;
342
                    GridRangePages.Visibility = Visibility.Collapsed;
343
                    GridAllPages.Visibility = Visibility.Collapsed;
344

    
345
                    break;
346
                case "RangePrint":
347
                    GridCurrentPage.Visibility = Visibility.Collapsed;
348
                    GridDefinePages.Visibility = Visibility.Visible;
349
                    GridRangePages.Visibility = Visibility.Collapsed;
350
                    GridAllPages.Visibility = Visibility.Collapsed;
351
                    break;
352
                case "UserDefined":
353
                    GridCurrentPage.Visibility = Visibility.Collapsed;
354
                    GridDefinePages.Visibility = Visibility.Collapsed;
355
                    GridRangePages.Visibility = Visibility.Visible;
356
                    GridAllPages.Visibility = Visibility.Collapsed;
357
                    break;
358
                case "AllPrint":
359
                    stPageNo.Value = 1;
360
                    edPageNo.Value = Convert.ToDouble(_DocInfo.PAGE_COUNT);
361
                    GridCurrentPage.Visibility = Visibility.Collapsed;
362
                    GridDefinePages.Visibility = Visibility.Collapsed;
363
                    GridRangePages.Visibility = Visibility.Collapsed;
364
                    GridAllPages.Visibility = Visibility.Visible;
365
                    break;
366
            }
367

    
368
            CheckCommentPages();
369
        }
370

    
371
        private void PageNo_ValueChanged(object sender, RadRangeBaseValueChangedEventArgs e)
372
        {
373
            if (_initializeComponentFinished)      //GridRangePages
374
            {
375
                if (stPageNo.Value > edPageNo.Value)
376
                {
377
                    if (sender.Equals(stPageNo))
378
                        edPageNo.Value = stPageNo.Value;
379
                    else
380
                        stPageNo.Value = edPageNo.Value;
381
                }
382

    
383
                //뷰어잠시제외(강인구)
384
                //this.LayoutRoot.Dispatcher.BeginInvoke(delegate()
385
                //{
386
                CheckCommentPages();
387
                //});
388
            }
389
        }
390

    
391
        private void txtDefinedPages_TextChanged(object sender, TextChangedEventArgs e)
392
        {
393
            CheckCommentPages();
394
        }
395

    
396
        private void btnClearDefinedPages_Click(object sender, RoutedEventArgs e)
397
        {
398
            txtDefinedPages.Text = "";
399
        }
400

    
401
        private void CommentPageList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
402
        {
403
            if (_initializeComponentFinished)
404
                if (CommentPageList.SelectedItem != null)
405
                    this.CurrentPageNo = (CommentPageList.SelectedItem as MarkupPageItem).PageNumber;
406
        }
407

    
408
        private async void gridViewMarkup_SelectionChanged(object sender, SelectionChangeEventArgs e)
409
        {
410
            if (_initializeComponentFinished)
411
            {
412
                await PageChangeAsync(Common.ViewerDataModel.Instance.NewCancellationToken(),this.CurrentPageNo, false);
413
            }
414
        }
415

    
416
        #endregion
417

    
418
        public async System.Threading.Tasks.Task<bool> PageChangeAsync(System.Threading.CancellationToken cts, int PageNo,bool saveFile, bool Flag = false)
419
        {
420
            System.Diagnostics.Debug.WriteLine("PageChangeAsync " + PageNo);
421
            bool result = false;
422
            //Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate
423
            //{
424
            try
425
            {
426
                Load load = new Load();
427

    
428
                _definePages.Back_Image = new ImageBrush();
429
                //var defaultBitmapImage = new BitmapImage(new Uri(_DefaultTileUri + PageNo + ".png"));
430

    
431
                var pages = _definePages.DocumentInfo.DOCPAGE.Where(x => x.PAGE_NUMBER == PageNo);
432

    
433
                if(pages.Count() > 0)
434
                {
435
                    var currentPage = pages.First();
436

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

    
439
                    //var bitmap = new BitmapImage();
440
                    //using (var stream = new MemoryStream(buffer))
441
                    //{
442
                    //bitmap.BeginInit();
443
                    //bitmap.CacheOption = BitmapCacheOption.OnLoad;
444
                    //bitmap.StreamSource = stream;
445
                    //bitmap.EndInit();
446

    
447
                        
448
                    var uri = await App.PageStorage.GetPageUriAsync(cts, currentPage.PAGE_NUMBER);
449
                    //Image bitmap = new Image();
450
                    //bitmap.Stretch = Stretch.Fill;
451
                    //bitmap.Source = bitmapframe;
452
                    //bitmap.Width = Convert.ToDouble(currentPage.PAGE_WIDTH);
453
                    //bitmap.Height = Convert.ToDouble(currentPage.PAGE_HEIGHT);
454

    
455
                    //if (uri.Scheme == Uri.UriSchemeFile)
456
                    //{
457
                    //    var cloneUri = new Uri(System.IO.Path.Combine(System.IO.Path.GetTempPath(),System.IO.Path.GetRandomFileName()),UriKind.Absolute);
458
                    //    File.Copy(uri.LocalPath, cloneUri.LocalPath);
459

    
460
                    //    uri = cloneUri;
461
                    //}
462

    
463
                    printCanvas.Children.Clear();
464
                    printCanvas.Width = Convert.ToDouble(currentPage.PAGE_WIDTH);
465
                    printCanvas.Height = Convert.ToDouble(currentPage.PAGE_HEIGHT);
466
                 
467
                    printCanvas.Background = new ImageBrush{ ImageSource = new BitmapImage(uri)};
468

    
469
                    //printCanvas.RenderTransformOrigin = new Point(0.5, 0.5);
470
                    //printCanvas.RenderTransform = new RotateTransform(currentPage.PAGE_ANGLE);
471
                    //ImageBrush background = new ImageBrush(bitmap);
472
                    //printCanvas.Background = background;
473
                    //printCanvas.Background = new SolidColorBrush(Colors.Transparent);
474

    
475

    
476
                    foreach (var info in gridViewMarkup.SelectedItems.Cast<IKCOM.MarkupInfoItem>())
477
                    {
478
                        load.User_Id = info.UserID;
479
                        load.document_id = _DocInfo.DOCUMENT_ID;
480
                        load.Page_No = PageNo;
481
                        load.DisplayColor = info.DisplayColor;
482
                        load.Markupinfoid = info.MarkupInfoID;
483
                        var IsLoad = await load.Markup_LoadAsync(printCanvas, 0);
484
                    }
485
                    //await Dispatcher.InvokeAsync(() => {
486
                    //    printCanvas.UpdateLayout();
487
                    //});
488

    
489
                    if (Flag)
490
                        {
491
                        //MemoryStream ms = new MemoryStream();
492
                        //BmpBitmapEncoder bbe = new BmpBitmapEncoder();
493
                        //bbe.Frames.Add(BitmapFrame.Create(new Uri(_DefaultTileUri + PageNo + ".png")));
494
                        //bbe.Save(ms);
495

    
496
                        //System.Drawing.Image.FromFile()
497
                        //Printimg = System.Drawing.Image.FromStream(stream);
498
                        //await System.Threading.Tasks.Task.Run(() =>
499
                        //{
500
                           await Dispatcher.InvokeAsync(() =>
501
                            {
502
                                Export export = new Export();
503

    
504
                                if (saveFile)
505
                                {
506
                                    var filepath = Path.Combine(TempImageDir, $"{PrintimgPath_List.Count() + 1}.png");
507

    
508
                                    if (export.ExportingFile(PrintView, printCanvas.Width, printCanvas.Height, filepath))
509
                                    {
510
                                        PrintimgPath_List.Add(PrintimgPath_List.Count() + 1, filepath);
511
                                    }
512
                                    else
513
                                    {
514
                                        throw new Exception($"Export Image Save File Error :{filepath}");
515
                                    }
516
                                }
517
                                else
518
                                {
519
                                    p_img = export.Exporting(PrintView, printCanvas.Width, printCanvas.Height);
520
                                    Printimg_List.Add(Printimg_List.Count() + 1, p_img);
521
                                }
522

    
523
                            },System.Windows.Threading.DispatcherPriority.SystemIdle);
524
                        //});
525
                    }
526

    
527
                        result = true;
528
                    //}
529
                } 
530
            }
531
            catch (Exception ex)
532
            {
533
                //Logger.sendResLog("PrintControl.PageChanged", ex.Message, 0);
534
            }
535

    
536
            return result;
537
            //}));
538
        }
539

    
540

    
541
        public static MemoryStream ByteBufferFromImage(BitmapImage imageSource)
542
        {
543
            var ms = new MemoryStream();
544
            var pngEncoder = new PngBitmapEncoder();
545
            pngEncoder.Frames.Add(BitmapFrame.Create(imageSource));
546
            pngEncoder.Save(ms);
547

    
548
            return ms;
549
        }
550
        //Print 버튼 클릭 이벤트
551
        #region Method - 명령
552
        async void PrintMethod(object sender, RoutedEventArgs e)
553
        {
554
            try
555
            {
556
                var token = Common.ViewerDataModel.Instance.NewCancellationToken();
557

    
558
                if (this.printIndy.IsBusy == true)
559
                    return;
560

    
561
                (this.Parent as RadWindow).CanClose = false;
562

    
563
                await this.Dispatcher.InvokeAsync(() => { 
564
                        this.printIndy.IsBusy = true;
565
                        printIndy.BusyContent = "Printing. . .";
566
                });
567

    
568

    
569
                _lstPrintPageNo = PrintPageCreate();
570

    
571
                if (_lstPrintPageNo.Count == 0)
572
                {
573
                    RadWindow.Alert(new DialogParameters
574
                    {
575
                        Owner = Application.Current.MainWindow,
576
                        Theme = new VisualStudio2013Theme(),
577
                        Header = "Info",
578
                        Content = "Not specified the page."
579
                    });
580
                    sliderPages.Value = 1;
581
                    this.printIndy.IsBusy = false;
582
                    return;
583
                }
584

    
585
                int cnt = 0;
586

    
587
                IsExportOrPrint = true;
588

    
589
                Printimg_List = new Dictionary<int, System.Drawing.Image>();
590
                PrintimgPath_List = new Dictionary<int, string>();
591
                TempImageDir = Path.Combine(Path.GetTempPath(), "Markus", Common.Commons.shortGuid());
592

    
593
                if (Directory.Exists(TempImageDir))
594
                {
595
                    Directory.Delete(TempImageDir, true);
596
                }
597

    
598
                Directory.CreateDirectory(TempImageDir);
599

    
600
                foreach (int PageNo in _lstPrintPageNo)
601
                {
602
                    cnt++;
603
                    sliderPages.Value = PageNo;
604
                    await PageChangeAsync(token,PageNo, true, true);
605
                    //PageChanged(cnt, true);
606
                }
607
                PrintName = cbPrint.SelectedItem.ToString();
608

    
609
                await this.Dispatcher.InvokeAsync(() => {
610
                    if (cnt == _lstPrintPageNo.Count)
611
                    {
612
                        Printing();
613
                    }
614
                });
615

    
616
                IsExportOrPrint = false;
617
            }
618
            catch (Exception ex)
619
            {
620
                //Logger.sendResLog("PrintMethod", ex.Message, 0);
621
            }
622
            finally
623
            {
624
                (this.Parent as RadWindow).CanClose = true;
625
            }
626

    
627
        }
628

    
629
        //Export 버튼 클릭 이벤트
630
        [System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions]
631
        //[System.Security.Permissions.FileIOPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
632
        async void ExportMethod(object sender, RoutedEventArgs e)
633
        {
634
            try
635
            {
636
                if (this.printIndy.IsBusy == true)
637
                    return;
638

    
639
                var token = Common.ViewerDataModel.Instance.NewCancellationToken();
640

    
641
                (this.Parent as RadWindow).CanClose = false;
642

    
643
                this.printIndy.IsBusy = true;
644
                printIndy.BusyContent = "Exporting. . .";
645

    
646
                Export export = new Export();
647
                _lstPrintPageNo = PrintPageCreate();
648

    
649
                if (_lstPrintPageNo.Count == 0)
650
                {
651
                    sliderPages.Value = 1;
652
                    this.printIndy.IsBusy = false;
653
                    RadWindow.Alert(new DialogParameters
654
                    {
655
                        Owner = Application.Current.MainWindow,
656
                        Theme = new VisualStudio2013Theme(),
657
                        Header = "Info",
658
                        Content = "Not specified the page.",
659
                    });
660
                    return;
661
                }
662

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

    
665
                switch (cbPrint.SelectedIndex)
666
                {
667
                    case (0):
668
                        {
669
                            SaveDig.Filter = "PDF file format|*.pdf";
670
                            break;
671
                        }
672
                    case (1):
673
                        {
674
                            SaveDig.Filter = "Image Files (*.jpg, *.Jpeg)|*.jpg;*.Jpeg";
675
                            break;
676
                        }
677
                }
678

    
679
                SaveDig.Title = "Save an PDF File";
680
                if(SaveDig.ShowDialog().Value)
681
                {
682
                    IsExportOrPrint = true;
683

    
684
                    PrintimgPath_List = new Dictionary<int, string>();
685
                    TempImageDir = Path.Combine(Path.GetTempPath(), "Markus", Common.Commons.shortGuid());
686

    
687
                    if (Directory.Exists(TempImageDir))
688
                    {
689
                        Directory.Delete(TempImageDir, true);
690
                    }
691

    
692
                    Directory.CreateDirectory(TempImageDir);
693

    
694
                    foreach (int PageNo in _lstPrintPageNo)
695
                    {
696
                        await Dispatcher.InvokeAsync(() =>
697
                        {
698
                            sliderPages.Value = PageNo;
699
                        });
700

    
701
                        await PageChangeAsync(token, PageNo, true, true);
702

    
703
                        System.Diagnostics.Debug.WriteLine("Export Page : " + PageNo);
704
                    }
705

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

    
708
                    if (SaveDig.FileName != "")
709
                    {
710
                        switch (cbPrint.SelectedIndex)
711
                        {
712
                            case (0):
713
                                {
714
                                    FileStream fs = new FileStream(SaveDig.FileName, FileMode.Create, FileAccess.Write);
715

    
716
                                    Document doc = new Document();
717
                                    try
718
                                    {
719
                                        iTextSharp.text.Version.GetInstance();
720
                                    }
721
                                    catch (System.NullReferenceException ex)
722
                                    {
723

    
724
                                    }
725

    
726
                                    PdfWriter writer = PdfWriter.GetInstance(doc, fs);
727

    
728
                                    doc.Open();
729
                                    
730
                                    float height = doc.PageSize.Height;
731
                                    float width = doc.PageSize.Width;
732

    
733
                                    foreach (var item in PrintimgPath_List)
734
                                    {
735
                                        System.Drawing.Image image = System.Drawing.Image.FromFile(item.Value);
736
                                        Export_img = iTextSharp.text.Image.GetInstance(image,System.Drawing.Imaging.ImageFormat.Jpeg);
737

    
738
                                        if (Export_img.Width > Export_img.Height)
739
                                        {
740
                                            doc.SetPageSize(new Rectangle(height, width));
741
                                            Export_img.ScaleToFit(height, width);
742
                                        }
743
                                        else
744
                                        {
745
                                            doc.SetPageSize(new Rectangle(width, height));
746
                                            Export_img.ScaleToFit(width, height);
747
                                        }
748

    
749
                                        Export_img.SetAbsolutePosition(0, 0);
750

    
751
                                        doc.NewPage();
752
                                        doc.Add(Export_img);
753
                                    }
754
                                    doc.Close();
755
                                    writer.Close();
756
                                    break;
757
                                }
758
                            case (1):
759
                                {
760
                                    foreach (var item in PrintimgPath_List)
761
                                    {
762
                                        File.Copy(item.Value, SaveDig.FileName.Replace(".jpg", "_" + item.Key.ToString()) + ".jpg");
763
                                    }
764
                                    break;
765
                                }
766
                        }
767
                    }
768
                    else
769
                    {
770
                        sliderPages.Value = 1;
771
                        this.printIndy.IsBusy = false;
772
                        return;
773
                    }
774

    
775
                    await this.Dispatcher.InvokeAsync(() =>
776
                    {
777
                        sliderPages.Value = 1;
778
                        printIndy.IsBusy = false;
779
                    });
780

    
781
                    await PageChangeAsync(token,_StartPageNo, false);
782

    
783
                    IsExportOrPrint = false;
784

    
785
                    (Application.Current.MainWindow as MainWindow).dzMainMenu.DialogMessage_Alert("Success", "Alert");
786
                }else
787
                {
788
                    Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate
789
                    {
790
                        sliderPages.Value = 1;
791
                        printIndy.IsBusy = false;
792
                    }));
793

    
794
                    //(Application.Current.MainWindow as MainWindow).dzMainMenu.DialogMessage_Alert("Cancel", "Alert");
795
                }                
796
            }
797
            catch (Exception ex)
798
            {
799
                sliderPages.Value = 1;
800
                printIndy.IsBusy = false;
801

    
802
                //Logger.sendResLog("Export Method", ex.Message, 0);
803
                //(Application.Current.MainWindow as MainWindow).dzMainMenu.DialogMessage_Alert("Alert", "관리자 확인이 필요합니다. 다시 시도해 주세요.\n"+ex.Message);
804
            }
805
            finally
806
            {
807
                if(Directory.Exists(TempImageDir))
808
                    Directory.Delete(TempImageDir, true);
809

    
810
                GC.Collect();
811
                GC.WaitForPendingFinalizers();
812
                GC.Collect();
813

    
814
                (this.Parent as RadWindow).CanClose = true;
815
            }
816
        }
817

    
818
        #endregion
819

    
820
        #region Method - 처리
821
        void CheckCommentPages()
822
        {
823
            List<MarkupPageItem> _pages = new List<MarkupPageItem>();
824
            DoubleCollection _Ticks = new DoubleCollection();
825

    
826

    
827
            if (GridCurrentPage.Visibility == System.Windows.Visibility.Visible)
828
            {
829

    
830
                _pages = (from commPage in this._PageMarkupList
831
                          where commPage.PageNumber == CurrentPageNo
832
                          orderby commPage.PageNumber
833
                          select commPage).ToList();
834
            }
835
            else if (GridRangePages.Visibility == System.Windows.Visibility.Visible)
836
            {
837
                stPageNo.Value = stPageNo.Value == null ? 1 : stPageNo.Value;
838
                edPageNo.Value = edPageNo.Value == null ? 1 : edPageNo.Value;
839

    
840
                int _stPage = (int)stPageNo.Value;
841
                int _edPage = (int)edPageNo.Value;
842

    
843
                _pages = (from commPage in this._PageMarkupList
844
                          where commPage.PageNumber >= _stPage && commPage.PageNumber <= _edPage
845
                          orderby commPage.PageNumber
846
                          select commPage).ToList();
847
            }
848
            else if (GridDefinePages.Visibility == System.Windows.Visibility.Visible)
849
            {
850
                stPageNo.Value = stPageNo.Value == null ? 1 : stPageNo.Value;
851
                edPageNo.Value = edPageNo.Value == null ? 1 : edPageNo.Value;
852

    
853
                int _stPage = (int)stPageNo.Value;
854
                int _edPage = (int)edPageNo.Value;
855

    
856
                //Using DeepView.Common.RangeParser
857
                var lst = RangeParser.Parse(txtDefinedPages.Text, _stPage, _definePages.PagesCount);
858
                _pages = (from commPage in this._PageMarkupList
859
                          from compareData in lst
860
                          where commPage.PageNumber == compareData
861
                          orderby commPage.PageNumber
862
                          select commPage).ToList();
863
            }
864
            else
865
            {
866
                _pages = (from commPage in this._PageMarkupList
867
                          orderby commPage.PageNumber
868
                          select commPage).ToList();
869
            }
870
            CommentPageList.ItemsSource = _pages.ToList();
871
        }
872

    
873
        void SetLoadMakupList(int PageNo)
874
        {
875
            _LoadMakupList.Clear();
876
            var _markupList = _PageMarkupList.Where(page => page.PageNumber == PageNo);
877

    
878
            if (_markupList.Count() > 0)
879
                _LoadMakupList = _markupList.First().DisplayColorItems.ToList();
880
        }
881

    
882
        #region 프린트 리스트 가져오기
883
        public void GetPrint(bool flag)
884
        {
885
            if (flag)
886
            {
887
                foreach (string printer in PrinterSettings.InstalledPrinters)
888
                {
889
                    this.cbPrint.Items.Add(printer);
890
                }
891
                printDocument = new PrintDocument();
892
                this.cbPrint.SelectedItem = printDocument.PrinterSettings.PrinterName;
893
            }
894
            else
895
            {
896
                this.cbPrint.Items.Add("PDF");
897
                this.cbPrint.Items.Add("IMAGE");
898

    
899
                this.cbPrint.SelectedItem = "PDF";
900
            }
901
        }
902
        #endregion
903

    
904
        #region 프린트 실행
905
        public async void Printing()
906
        {
907
            var token = Common.ViewerDataModel.Instance.NewCancellationToken();
908

    
909
            await PageChangeAsync(token,1, false);
910

    
911
            if (PrinterSettings.InstalledPrinters != null && PrinterSettings.InstalledPrinters.Count > 0)
912
            {
913
                printDocument = new PrintDocument();
914
                printDocument.OriginAtMargins = true;
915
                printDocument.BeginPrint += new System.Drawing.Printing.PrintEventHandler(printDocument_BeginPrint);
916
                printDocument.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(printDocument_PrintPage);
917
                printDocument.EndPrint += new System.Drawing.Printing.PrintEventHandler(printDocument_EndPrint);
918
            }
919
            else
920
                printDocument = null;
921

    
922
            #region 인쇄 미리보기 테스트
923
            using (System.Windows.Forms.PrintPreviewDialog dlg = new System.Windows.Forms.PrintPreviewDialog())
924
            {
925
                printDocument.PrinterSettings.MinimumPage = 1;
926
                printDocument.PrinterSettings.MaximumPage = _lstPrintPageNo.Count();
927
                printDocument.PrinterSettings.FromPage = 1;
928
                printDocument.PrinterSettings.ToPage = _lstPrintPageNo.Count();
929
                printDocument.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
930
                printDocument.PrinterSettings.PrinterName = PrintName;
931
                dlg.Document = printDocument;
932
                dlg.WindowState = System.Windows.Forms.FormWindowState.Maximized;
933
                dlg.ShowDialog();
934
            }
935
            #endregion
936

    
937
            #region 인쇄
938
            //printDocument.PrinterSettings.MinimumPage = 1;
939
            //printDocument.PrinterSettings.MaximumPage = _lstPrintPageNo.Count();
940
            //printDocument.PrinterSettings.FromPage = 1;
941
            //printDocument.PrinterSettings.ToPage = _lstPrintPageNo.Count();
942

    
943
            //printDocument.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
944
            //printDocument.PrinterSettings.PrinterName = PrintName;
945

    
946
            //printDocument.Print();
947
            #endregion
948
        }
949

    
950
        private void printDocument_BeginPrint(object sender, PrintEventArgs e)
951
        {
952
            //Printimg_List = new Dictionary<int, System.Drawing.Image>();
953
            // This demo only loads one page at a time, so no need to re-set the print page number
954
            PrintDocument document = sender as PrintDocument;
955
            currentPage = document.PrinterSettings.FromPage;
956
        }
957

    
958
        private void printDocument_PrintPage(object sender, PrintPageEventArgs e)
959
        {
960
            //e.Graphics.DrawImage(Printimg_List.Where(info => info.Key == currentPage).FirstOrDefault().Value, 0, 0);
961

    
962
            Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate
963
            {
964
                //p_img = Printimg_List.Where(data => data.Key == currentPage).FirstOrDefault().Value;
965
                p_img = System.Drawing.Image.FromFile(PrintimgPath_List.Where(data => data.Key == currentPage).FirstOrDefault().Value);
966

    
967
                if (p_img.Width > p_img.Height)
968
                {
969
                    p_img.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
970
                }
971

    
972
                //iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(p_img, System.Drawing.Imaging.ImageFormat.Jpeg);
973
                System.Drawing.Image pic = p_img;
974
                System.Drawing.Rectangle m = e.MarginBounds;
975

    
976
                //if ((double)pic.Width / (double)pic.Height > (double)m.Width / (double)m.Height) // image is wider
977
                //{
978
                //    m.Height = 1135;//(int)((double)pic.Height / (double)pic.Width * (double)m.Width) - 16;
979
                //}
980
                //else
981
                //{
982
                //    m.Width = 793;//(int)((double)pic.Width / (double)pic.Height * (double)m.Height) - 16;
983
                //}
984
                m.Width = (int)e.PageSettings.PrintableArea.Width;
985
                m.Height = (int)e.PageSettings.PrintableArea.Height;
986
                m.X = (int)e.PageSettings.HardMarginX;
987
                m.Y = (int)e.PageSettings.HardMarginY;
988

    
989
                e.Graphics.DrawImage(pic, m);
990
                //e.Graphics.DrawImage(p_img, e.MarginBounds);
991
                //e.Graphics.DrawImage(p_img, 0, 0);
992
            }));
993

    
994
            //다음 페이지
995
            currentPage++;
996

    
997
            ////인쇄를 계속 할지 말지 확인
998
            if (currentPage <= printDocument.PrinterSettings.ToPage)
999
                e.HasMorePages = true;
1000
            else
1001
                e.HasMorePages = false;
1002

    
1003
        }
1004

    
1005
        private void printDocument_EndPrint(object sender, PrintEventArgs e)
1006
        {
1007
            Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate
1008
            {
1009
                //if (Directory.Exists(TempImageDir))
1010
                //    Directory.Delete(TempImageDir, true);
1011

    
1012
                sliderPages.Value = 1;
1013
                printIndy.IsBusy = false;
1014

    
1015
            }));
1016
        }
1017
        #endregion
1018

    
1019
        #region Selected Pages Check
1020
        List<int> PrintPageCreate()
1021
        {
1022
            List<int> Result = new List<int>();
1023

    
1024
            if (GridCurrentPage.Visibility == System.Windows.Visibility.Visible || currentPagePrint)
1025
            {
1026
                Result.Add(CurrentPageNo);
1027
            }
1028
            else if (GridRangePages.Visibility == System.Windows.Visibility.Visible)
1029
            {
1030
                for (int i = Convert.ToInt32(stPageNo.Value); i <= Convert.ToInt32(edPageNo.Value); i++)
1031
                {
1032
                    Result.Add(i);
1033
                }
1034
            }
1035
            else if (GridDefinePages.Visibility == System.Windows.Visibility.Visible)
1036
            {
1037
                int _stPage = (int)stPageNo.Value;
1038
                int _edPage = (int)edPageNo.Value;
1039

    
1040
                var lst = RangeParser.Parse(txtDefinedPages.Text, _stPage, _definePages.PagesCount);
1041
                Result.AddRange(lst);
1042
            }
1043
            else
1044
            {
1045
                for (int i = 1; i <= _definePages.PagesCount; i++)
1046
                {
1047
                    Result.Add(i);
1048
                }
1049
            }
1050
            if (currentPagePrint)
1051
            {
1052
                return Result;
1053
            }
1054

    
1055
            if (chkOnlyMarkup.IsChecked.Value)
1056
            {
1057
                var _result = from result in Result
1058
                              where _PageMarkupList.Where(page => page.PageNumber == result).Count() > 0
1059
                              select result;
1060
                Result = _result.ToList();
1061
            }
1062
            return Result;
1063
        }
1064
        #endregion
1065

    
1066
        #endregion
1067
    }
1068
}
클립보드 이미지 추가 (최대 크기: 500 MB)