프로젝트

일반

사용자정보

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

markus / KCOM / Controls / PrintControl.xaml.cs @ 5a223b60

이력 | 보기 | 이력해설 | 다운로드 (41.8 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

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

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

    
37
        public double CurrentValue { get; set; }
38

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

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

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

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

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

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

    
80

    
81
                try
82
                {
83

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

    
93
            }
94
        }
95
    }
96

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

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

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

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

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

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

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

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

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

    
150

    
151
        #endregion
152

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

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

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

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

    
176
        }
177
        #endregion
178

    
179
        #region 생성자
180

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

    
185
            this.Unloaded += (snd, evt) =>
186
            {
187
                try
188
                {
189
                    if (Directory.Exists(TempImageDir))
190
                        Directory.Delete(TempImageDir, true);
191
                }
192
                catch (Exception)
193
                {
194
                }
195
            };
196

    
197
            this.IsEnabled = true;
198

    
199
            //Layer Control을 통째로 가져와야 하는건가
200
            this._DocInfo = DocInfo;
201
            this._DefaultTileUri = TileSourceUri;
202
            this.ProjectNo = ProjectNo;
203
            this._StartPageNo = CurrentPageNo;
204

    
205
            markupInfo.ForEach(info => this._markupInfo.Add(info));
206

    
207
            foreach (var info in _markupInfo)
208
            {
209
                if (info.Consolidate == 1)
210
                {
211
                    info.UserName = "Consolidation";
212
                }
213
                info.MarkupList.ForEach(makup =>
214
                {
215
                    var _pageMarkup = _PageMarkupList.Where(item => item.PageNumber == makup.PageNumber);
216
                    var _SetMarkupItem = new SetColorMarkupItem { markupID = makup.ID, DisplayColor = info.DisplayColor };
217

    
218
                    if (_pageMarkup.Count() > 0)
219
                        _pageMarkup.First().DisplayColorItems.Add(_SetMarkupItem);
220
                    else
221
                        _PageMarkupList.Add(new MarkupPageItem
222
                        {
223
                            PageNumber = makup.PageNumber,
224
                            DisplayColorItems = new List<SetColorMarkupItem> { _SetMarkupItem }
225
                        });
226
                });
227

    
228
                colorList.Add(new DisplayColorInfo
229
                {
230
                    UserID = info.UserID,
231
                    DisplayColor = info.DisplayColor,
232
                    Department = info.Depatment,
233
                    UserName = info.UserName,
234
                });
235
            }
236

    
237
            gridViewMarkup.ItemsSource = this._markupInfo;
238
            SetLoadMakupList(this._StartPageNo);
239
            if (_LoadMakupList.Count() == 0)
240
                chkOnlyMarkup.IsChecked = false;
241

    
242
            this.CurrentPageNo = _StartPageNo;
243

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

    
247
            DocumentInfo = _definePages;
248
            this.DataContext = _definePages;
249

    
250
            CheckCommentPages();
251

    
252
            //초기화면 Comment Check된 상태로 보여주기
253
            foreach (var item in _markupInfo)
254
            {
255
                gridViewMarkup.SelectedItems.Add(item);
256
            }
257

    
258
            PageChangeAsync(Common.ViewerDataModel.Instance.NewPagImageCancelToken(), _StartPageNo,false).ConfigureAwait(true);
259

    
260
            sliderPages.Maximum = Convert.ToDouble(this._DocInfo.PAGE_COUNT);
261
            this.stPageNo.Maximum = Convert.ToDouble(this._DocInfo.PAGE_COUNT);
262
            this.edPageNo.Maximum = Convert.ToDouble(this._DocInfo.PAGE_COUNT);
263
            this.IsPrint = isPrint;
264

    
265
            if (!IsPrint)
266
            {
267
                GetPrint(false);
268
                btnWholeExport.Visibility = Visibility.Visible;
269
                btnWholePrint.Visibility = Visibility.Collapsed;
270
                Selected_Print.Header = "Export Type";
271
            }
272
            else
273
            {
274
                //PrintList 가져오기
275
                GetPrint(true);
276
                btnWholePrint.Visibility = Visibility.Visible;
277
                btnWholeExport.Visibility = Visibility.Collapsed;
278
            }
279

    
280
            _initializeComponentFinished = true;
281

    
282
            //timm.Interval = 10;
283
            //timm.Elapsed += new System.Timers.ElapsedEventHandler(_Timer_Elapsed);
284
            //timm.Enabled = true;
285
        }
286

    
287
        #endregion
288

    
289
        #region Control Event
290
        private async void sliderPages_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
291
        {
292
            if (_initializeComponentFinished)
293
            {
294
                if (!_IsDagSlider)
295
                {
296
                    this.CurrentPageNo = (int)this.sliderPages.Value;
297

    
298
                    if (!IsExportOrPrint)
299
                    {
300
                        await PageChangeAsync(Common.ViewerDataModel.Instance.NewPagImageCancelToken(), this.CurrentPageNo, false);
301
                    }
302
                    //await App.PageStorage.GetPageUriAsync(this.CurrentPageNo);
303
                
304
                    if (_ButtonName == "Current")
305
                    {
306
                        stPageNo.Value = CurrentPageNo;
307
                        edPageNo.Value = CurrentPageNo;
308
                    }
309

    
310
                    //CheckCommentPages();
311
                }
312
            }
313
        }
314

    
315
        private async void sliderPages_DragCompleted(object sender, RadDragCompletedEventArgs e)
316
        {
317
            _IsDagSlider = false;
318
            this.CurrentPageNo = (int)this.sliderPages.Value;
319
            if (_initializeComponentFinished)
320
            {
321
               
322
            }
323
        }
324

    
325
        private void sliderPages_DragStarted(object sender, RadDragStartedEventArgs e)
326
        {
327
            _IsDagSlider = true;
328
        }
329

    
330
        private void chkOnlyMarkup_Checked(object sender, RoutedEventArgs e)
331
        {
332
            if (_initializeComponentFinished)      //GridRangePages
333
            {
334
                CheckCommentPages();
335
            }
336
        }
337

    
338
        private void chkOnlyRedColor_Checked(object sender, RoutedEventArgs e)
339
        {
340
            if (_initializeComponentFinished)      //GridRangePages
341
            {
342
                CheckCommentPages();
343
            }
344
        }
345
        
346

    
347
        string _ButtonName;
348
        private void PageSelect_Checked(object sender, RoutedEventArgs e)
349
        {
350
            if (!_initializeComponentFinished) return;
351

    
352
            _ButtonName = (sender as RadRadioButton).Tag.ToString();
353
            CommentPageList.ItemsSource = null;
354

    
355
            switch (_ButtonName)
356
            {
357
                case "Current":
358
                    stPageNo.Value = CurrentPageNo;
359
                    edPageNo.Value = CurrentPageNo;
360

    
361
                    GridCurrentPage.Visibility = Visibility.Visible;
362
                    GridDefinePages.Visibility = Visibility.Collapsed;
363
                    GridRangePages.Visibility = Visibility.Collapsed;
364
                    GridAllPages.Visibility = Visibility.Collapsed;
365

    
366
                    break;
367
                case "RangePrint":
368
                    GridCurrentPage.Visibility = Visibility.Collapsed;
369
                    GridDefinePages.Visibility = Visibility.Visible;
370
                    GridRangePages.Visibility = Visibility.Collapsed;
371
                    GridAllPages.Visibility = Visibility.Collapsed;
372
                    break;
373
                case "UserDefined":
374
                    GridCurrentPage.Visibility = Visibility.Collapsed;
375
                    GridDefinePages.Visibility = Visibility.Collapsed;
376
                    GridRangePages.Visibility = Visibility.Visible;
377
                    GridAllPages.Visibility = Visibility.Collapsed;
378
                    break;
379
                case "AllPrint":
380
                    stPageNo.Value = 1;
381
                    edPageNo.Value = Convert.ToDouble(_DocInfo.PAGE_COUNT);
382
                    GridCurrentPage.Visibility = Visibility.Collapsed;
383
                    GridDefinePages.Visibility = Visibility.Collapsed;
384
                    GridRangePages.Visibility = Visibility.Collapsed;
385
                    GridAllPages.Visibility = Visibility.Visible;
386
                    break;
387
            }
388

    
389
            CheckCommentPages();
390
        }
391

    
392
        private void PageNo_ValueChanged(object sender, RadRangeBaseValueChangedEventArgs e)
393
        {
394
            if (_initializeComponentFinished)      //GridRangePages
395
            {
396
                if (stPageNo.Value > edPageNo.Value)
397
                {
398
                    if (sender.Equals(stPageNo))
399
                        edPageNo.Value = stPageNo.Value;
400
                    else
401
                        stPageNo.Value = edPageNo.Value;
402
                }
403

    
404
                //뷰어잠시제외(강인구)
405
                //this.LayoutRoot.Dispatcher.BeginInvoke(delegate()
406
                //{
407
                CheckCommentPages();
408
                //});
409
            }
410
        }
411

    
412
        private void txtDefinedPages_TextChanged(object sender, TextChangedEventArgs e)
413
        {
414
            CheckCommentPages();
415
        }
416

    
417
        private void btnClearDefinedPages_Click(object sender, RoutedEventArgs e)
418
        {
419
            txtDefinedPages.Text = "";
420
        }
421

    
422
        private void CommentPageList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
423
        {
424
            if (_initializeComponentFinished)
425
                if (CommentPageList.SelectedItem != null)
426
                    this.CurrentPageNo = (CommentPageList.SelectedItem as MarkupPageItem).PageNumber;
427
        }
428

    
429
        private async void gridViewMarkup_SelectionChanged(object sender, SelectionChangeEventArgs e)
430
        {
431
            if (_initializeComponentFinished)
432
            {
433
                await PageChangeAsync(Common.ViewerDataModel.Instance.NewPagImageCancelToken(),this.CurrentPageNo, false);
434
            }
435
        }
436

    
437
        #endregion
438

    
439
        public async System.Threading.Tasks.Task<bool> PageChangeAsync(System.Threading.CancellationToken cts, int PageNo,bool saveFile, bool Flag = false)
440
        {
441
            System.Diagnostics.Debug.WriteLine("PageChangeAsync " + PageNo);
442
            bool result = false;
443
            //Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate
444
            //{
445
            try
446
            {
447
                Load load = new Load();
448

    
449
                _definePages.Back_Image = new ImageBrush();
450
                //var defaultBitmapImage = new BitmapImage(new Uri(_DefaultTileUri + PageNo + ".png"));
451

    
452
                var pages = _definePages.DocumentInfo.DOCPAGE.Where(x => x.PAGE_NUMBER == PageNo);
453

    
454
                if(pages.Count() > 0)
455
                {
456
                    var currentPage = pages.First();
457

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

    
460
                    //var bitmap = new BitmapImage();
461
                    //using (var stream = new MemoryStream(buffer))
462
                    //{
463
                    //bitmap.BeginInit();
464
                    //bitmap.CacheOption = BitmapCacheOption.OnLoad;
465
                    //bitmap.StreamSource = stream;
466
                    //bitmap.EndInit();
467

    
468
                        
469
                    var uri = await App.PageStorage.GetPageUriAsync(cts, currentPage.PAGE_NUMBER);
470
                    //Image bitmap = new Image();
471
                    //bitmap.Stretch = Stretch.Fill;
472
                    //bitmap.Source = bitmapframe;
473
                    //bitmap.Width = Convert.ToDouble(currentPage.PAGE_WIDTH);
474
                    //bitmap.Height = Convert.ToDouble(currentPage.PAGE_HEIGHT);
475

    
476
                    //if (uri.Scheme == Uri.UriSchemeFile)
477
                    //{
478
                    //    var cloneUri = new Uri(System.IO.Path.Combine(System.IO.Path.GetTempPath(),System.IO.Path.GetRandomFileName()),UriKind.Absolute);
479
                    //    File.Copy(uri.LocalPath, cloneUri.LocalPath);
480

    
481
                    //    uri = cloneUri;
482
                    //}
483

    
484
                    printCanvas.Children.Clear();
485
                    printCanvas.Width = Convert.ToDouble(currentPage.PAGE_WIDTH);
486
                    printCanvas.Height = Convert.ToDouble(currentPage.PAGE_HEIGHT);
487
                    
488
                    printCanvas.Background = new ImageBrush{ ImageSource = new BitmapImage(uri)};
489

    
490
                    //printCanvas.RenderTransformOrigin = new Point(0.5, 0.5);
491
                    //printCanvas.RenderTransform = new RotateTransform(currentPage.PAGE_ANGLE);
492
                    //ImageBrush background = new ImageBrush(bitmap);
493
                    //printCanvas.Background = background;
494
                    //printCanvas.Background = new SolidColorBrush(Colors.Transparent);
495

    
496

    
497
                    foreach (var info in gridViewMarkup.SelectedItems.Cast<IKCOM.MarkupInfoItem>())
498
                    {
499
                        load.User_Id = info.UserID;
500
                        load.document_id = _DocInfo.DOCUMENT_ID;
501
                        load.Page_No = PageNo;
502

    
503
                        if (chkOnlyRedColor.IsChecked == true)
504
                        {
505
                            load.DisplayColor = "#FFFF0000";
506
                        }
507
                        else
508
                        {
509
                            load.DisplayColor = info.DisplayColor;
510
                        }
511

    
512
                        load.Markupinfoid = info.MarkupInfoID;
513
                        var IsLoad = await load.Markup_LoadAsync(printCanvas, 0);
514
                    }
515
                    //await Dispatcher.InvokeAsync(() => {
516
                    //    printCanvas.UpdateLayout();
517
                    //});
518

    
519
                    if (Flag)
520
                        {
521
                        //MemoryStream ms = new MemoryStream();
522
                        //BmpBitmapEncoder bbe = new BmpBitmapEncoder();
523
                        //bbe.Frames.Add(BitmapFrame.Create(new Uri(_DefaultTileUri + PageNo + ".png")));
524
                        //bbe.Save(ms);
525

    
526
                        //System.Drawing.Image.FromFile()
527
                        //Printimg = System.Drawing.Image.FromStream(stream);
528
                        //await System.Threading.Tasks.Task.Run(() =>
529
                        //{
530
                           await Dispatcher.InvokeAsync(() =>
531
                            {
532
                                Export export = new Export();
533

    
534
                                if (saveFile)
535
                                {
536
                                    var filepath = Path.Combine(TempImageDir, $"{PrintimgPath_List.Count() + 1}.png");
537

    
538
                                    if (export.ExportingFile(PrintView, printCanvas.Width, printCanvas.Height, filepath))
539
                                    {
540
                                        PrintimgPath_List.Add(PrintimgPath_List.Count() + 1, filepath);
541
                                    }
542
                                    else
543
                                    {
544
                                        throw new Exception($"Export Image Save File Error :{filepath}");
545
                                    }
546
                                }
547
                                else
548
                                {
549
                                    p_img = export.Exporting(PrintView, printCanvas.Width, printCanvas.Height);
550
                                    Printimg_List.Add(Printimg_List.Count() + 1, p_img);
551
                                }
552

    
553
                            },System.Windows.Threading.DispatcherPriority.SystemIdle);
554
                        //});
555
                    }
556

    
557
                        result = true;
558
                    //}
559
                } 
560
            }
561
            catch (Exception ex)
562
            {
563
                //Logger.sendResLog("PrintControl.PageChanged", ex.Message, 0);
564
            }
565

    
566
            return result;
567
            //}));
568
        }
569

    
570

    
571
        public static MemoryStream ByteBufferFromImage(BitmapImage imageSource)
572
        {
573
            var ms = new MemoryStream();
574
            var pngEncoder = new PngBitmapEncoder();
575
            pngEncoder.Frames.Add(BitmapFrame.Create(imageSource));
576
            pngEncoder.Save(ms);
577

    
578
            return ms;
579
        }
580
        //Print 버튼 클릭 이벤트
581
        #region Method - 명령
582
        async void PrintMethod(object sender, RoutedEventArgs e)
583
        {
584
            try
585
            {
586
                var token = Common.ViewerDataModel.Instance.NewPagImageCancelToken();
587

    
588
                if (this.printIndy.IsBusy == true)
589
                    return;
590

    
591
                (this.Parent as RadWindow).CanClose = false;
592

    
593
                await this.Dispatcher.InvokeAsync(() => { 
594
                        this.printIndy.IsBusy = true;
595
                        printIndy.BusyContent = "Printing. . .";
596
                });
597

    
598

    
599
                _lstPrintPageNo = PrintPageCreate();
600

    
601
                if (_lstPrintPageNo.Count == 0)
602
                {
603
                    RadWindow.Alert(new DialogParameters
604
                    {
605
                        Owner = Application.Current.MainWindow,
606
                        Theme = new VisualStudio2013Theme(),
607
                        Header = "Info",
608
                        Content = "Not specified the page."
609
                    });
610
                    sliderPages.Value = 1;
611
                    this.printIndy.IsBusy = false;
612
                    return;
613
                }
614

    
615
                int cnt = 0;
616

    
617
                IsExportOrPrint = true;
618

    
619
                Printimg_List = new Dictionary<int, System.Drawing.Image>();
620
                PrintimgPath_List = new Dictionary<int, string>();
621
                TempImageDir = Path.Combine(Path.GetTempPath(), "Markus", Common.Commons.ShortGuid());
622

    
623
                if (Directory.Exists(TempImageDir))
624
                {
625
                    Directory.Delete(TempImageDir, true);
626
                }
627

    
628
                Directory.CreateDirectory(TempImageDir);
629

    
630
                foreach (int PageNo in _lstPrintPageNo)
631
                {
632
                    cnt++;
633
                    sliderPages.Value = PageNo;
634
                    await PageChangeAsync(token,PageNo, true, true);
635
                    //PageChanged(cnt, true);
636
                }
637
                PrintName = cbPrint.SelectedItem.ToString();
638

    
639
                await this.Dispatcher.InvokeAsync(() => {
640
                    if (cnt == _lstPrintPageNo.Count)
641
                    {
642
                        Printing();
643
                    }
644
                });
645

    
646
                IsExportOrPrint = false;
647
            }
648
            catch (Exception ex)
649
            {
650
                //Logger.sendResLog("PrintMethod", ex.Message, 0);
651
            }
652
            finally
653
            {
654
                (this.Parent as RadWindow).CanClose = true;
655
            }
656

    
657
        }
658

    
659
        //Export 버튼 클릭 이벤트
660
        [System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions]
661
        //[System.Security.Permissions.FileIOPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
662
        async void ExportMethod(object sender, RoutedEventArgs e)
663
        {
664
            try
665
            {
666
                if (this.printIndy.IsBusy == true)
667
                    return;
668

    
669
                var token = Common.ViewerDataModel.Instance.NewPagImageCancelToken();
670

    
671
                (this.Parent as RadWindow).CanClose = false;
672

    
673
                this.printIndy.IsBusy = true;
674
                printIndy.BusyContent = "Exporting. . .";
675

    
676
                Export export = new Export();
677
                _lstPrintPageNo = PrintPageCreate();
678

    
679
                if (_lstPrintPageNo.Count == 0)
680
                {
681
                    sliderPages.Value = 1;
682
                    this.printIndy.IsBusy = false;
683
                    RadWindow.Alert(new DialogParameters
684
                    {
685
                        Owner = Application.Current.MainWindow,
686
                        Theme = new VisualStudio2013Theme(),
687
                        Header = "Info",
688
                        Content = "Not specified the page.",
689
                    });
690
                    return;
691
                }
692

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

    
695
                switch (cbPrint.SelectedIndex)
696
                {
697
                    case (0):
698
                        {
699
                            SaveDig.Filter = "PDF file format|*.pdf";
700
                            break;
701
                        }
702
                    case (1):
703
                        {
704
                            SaveDig.Filter = "Image Files (*.jpg, *.Jpeg)|*.jpg;*.Jpeg";
705
                            break;
706
                        }
707
                }
708

    
709
                SaveDig.Title = "Save an PDF File";
710
                if(SaveDig.ShowDialog().Value)
711
                {
712
                    IsExportOrPrint = true;
713

    
714
                    PrintimgPath_List = new Dictionary<int, string>();
715
                    TempImageDir = Path.Combine(Path.GetTempPath(), "Markus", Common.Commons.ShortGuid());
716

    
717
                    if (Directory.Exists(TempImageDir))
718
                    {
719
                        Directory.Delete(TempImageDir, true);
720
                    }
721

    
722
                    Directory.CreateDirectory(TempImageDir);
723

    
724
                    foreach (int PageNo in _lstPrintPageNo)
725
                    {
726
                        await Dispatcher.InvokeAsync(() =>
727
                        {
728
                            sliderPages.Value = PageNo;
729
                        });
730

    
731
                        await PageChangeAsync(token, PageNo, true, true);
732

    
733
                        System.Diagnostics.Debug.WriteLine("Export Page : " + PageNo);
734
                    }
735

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

    
738
                    if (SaveDig.FileName != "")
739
                    {
740
                        switch (cbPrint.SelectedIndex)
741
                        {
742
                            case (0):
743
                                {
744
                                    FileStream fs = new FileStream(SaveDig.FileName, FileMode.Create, FileAccess.Write);
745

    
746
                                    Document doc = new Document();
747
                                    try
748
                                    {
749
                                        iTextSharp.text.Version.GetInstance();
750
                                    }
751
                                    catch (System.NullReferenceException ex)
752
                                    {
753

    
754
                                    }
755

    
756
                                    PdfWriter writer = PdfWriter.GetInstance(doc, fs);
757

    
758
                                    doc.Open();
759
                                    
760
                                    float height = doc.PageSize.Height;
761
                                    float width = doc.PageSize.Width;
762

    
763
                                    foreach (var item in PrintimgPath_List)
764
                                    {
765
                                        System.Drawing.Image image = System.Drawing.Image.FromFile(item.Value);
766
                                        Export_img = iTextSharp.text.Image.GetInstance(image,System.Drawing.Imaging.ImageFormat.Jpeg);
767

    
768
                                        if (Export_img.Width > Export_img.Height)
769
                                        {
770
                                            doc.SetPageSize(new Rectangle(height, width));
771
                                            Export_img.ScaleToFit(height, width);
772
                                        }
773
                                        else
774
                                        {
775
                                            doc.SetPageSize(new Rectangle(width, height));
776
                                            Export_img.ScaleToFit(width, height);
777
                                        }
778

    
779
                                        Export_img.SetAbsolutePosition(0, 0);
780

    
781
                                        doc.NewPage();
782
                                        doc.Add(Export_img);
783
                                    }
784
                                    doc.Close();
785
                                    writer.Close();
786
                                    break;
787
                                }
788
                            case (1):
789
                                {
790
                                    foreach (var item in PrintimgPath_List)
791
                                    {
792
                                        File.Copy(item.Value, SaveDig.FileName.Replace(".jpg", "_" + item.Key.ToString()) + ".jpg");
793
                                    }
794
                                    break;
795
                                }
796
                        }
797
                    }
798
                    else
799
                    {
800
                        sliderPages.Value = 1;
801
                        this.printIndy.IsBusy = false;
802
                        return;
803
                    }
804

    
805
                    await this.Dispatcher.InvokeAsync(() =>
806
                    {
807
                        sliderPages.Value = 1;
808
                        printIndy.IsBusy = false;
809
                    });
810

    
811
                    await PageChangeAsync(token,_StartPageNo, false);
812

    
813
                    IsExportOrPrint = false;
814

    
815
                    (Application.Current.MainWindow as MainWindow).dzMainMenu.DialogMessage_Alert("Success", "Alert");
816
                }else
817
                {
818
                    Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate
819
                    {
820
                        sliderPages.Value = 1;
821
                        printIndy.IsBusy = false;
822
                    }));
823

    
824
                    //(Application.Current.MainWindow as MainWindow).dzMainMenu.DialogMessage_Alert("Cancel", "Alert");
825
                }                
826
            }
827
            catch (Exception ex)
828
            {
829
                sliderPages.Value = 1;
830
                printIndy.IsBusy = false;
831

    
832
                //Logger.sendResLog("Export Method", ex.Message, 0);
833
                //(Application.Current.MainWindow as MainWindow).dzMainMenu.DialogMessage_Alert("Alert", "관리자 확인이 필요합니다. 다시 시도해 주세요.\n"+ex.Message);
834
            }
835
            finally
836
            {
837
                GC.Collect();
838
                GC.WaitForPendingFinalizers();
839
                GC.Collect();
840

    
841
                (this.Parent as RadWindow).CanClose = true;
842
            }
843
        }
844

    
845
        #endregion
846

    
847
        #region Method - 처리
848
        void CheckCommentPages()
849
        {
850
            List<MarkupPageItem> _pages = new List<MarkupPageItem>();
851
            DoubleCollection _Ticks = new DoubleCollection();
852

    
853

    
854
            if (GridCurrentPage.Visibility == System.Windows.Visibility.Visible)
855
            {
856

    
857
                _pages = (from commPage in this._PageMarkupList
858
                          where commPage.PageNumber == CurrentPageNo
859
                          orderby commPage.PageNumber
860
                          select commPage).ToList();
861
            }
862
            else if (GridRangePages.Visibility == System.Windows.Visibility.Visible)
863
            {
864
                stPageNo.Value = stPageNo.Value == null ? 1 : stPageNo.Value;
865
                edPageNo.Value = edPageNo.Value == null ? 1 : edPageNo.Value;
866

    
867
                int _stPage = (int)stPageNo.Value;
868
                int _edPage = (int)edPageNo.Value;
869

    
870
                _pages = (from commPage in this._PageMarkupList
871
                          where commPage.PageNumber >= _stPage && commPage.PageNumber <= _edPage
872
                          orderby commPage.PageNumber
873
                          select commPage).ToList();
874
            }
875
            else if (GridDefinePages.Visibility == System.Windows.Visibility.Visible)
876
            {
877
                stPageNo.Value = stPageNo.Value == null ? 1 : stPageNo.Value;
878
                edPageNo.Value = edPageNo.Value == null ? 1 : edPageNo.Value;
879

    
880
                int _stPage = (int)stPageNo.Value;
881
                int _edPage = (int)edPageNo.Value;
882

    
883
                //Using DeepView.Common.RangeParser
884
                var lst = RangeParser.Parse(txtDefinedPages.Text, _stPage, _definePages.PagesCount);
885
                _pages = (from commPage in this._PageMarkupList
886
                          from compareData in lst
887
                          where commPage.PageNumber == compareData
888
                          orderby commPage.PageNumber
889
                          select commPage).ToList();
890
            }
891
            else
892
            {
893
                _pages = (from commPage in this._PageMarkupList
894
                          orderby commPage.PageNumber
895
                          select commPage).ToList();
896
            }
897

    
898
            CommentPageList.ItemsSource = _pages.ToList();
899
        }
900

    
901
        void SetLoadMakupList(int PageNo)
902
        {
903
            _LoadMakupList.Clear();
904
            var _markupList = _PageMarkupList.Where(page => page.PageNumber == PageNo);
905

    
906
            if (_markupList.Count() > 0)
907
                _LoadMakupList = _markupList.First().DisplayColorItems.ToList();
908
        }
909

    
910
        #region 프린트 리스트 가져오기
911
        public void GetPrint(bool flag)
912
        {
913
            if (flag)
914
            {
915
                foreach (string printer in PrinterSettings.InstalledPrinters)
916
                {
917
                    this.cbPrint.Items.Add(printer);
918
                }
919
                printDocument = new PrintDocument();
920
                this.cbPrint.SelectedItem = printDocument.PrinterSettings.PrinterName;
921
            }
922
            else
923
            {
924
                this.cbPrint.Items.Add("PDF");
925
                this.cbPrint.Items.Add("IMAGE");
926

    
927
                this.cbPrint.SelectedItem = "PDF";
928
            }
929
        }
930
        #endregion
931

    
932
        #region 프린트 실행
933
        public async void Printing()
934
        {
935
            var token = Common.ViewerDataModel.Instance.NewPagImageCancelToken ();
936

    
937
            await PageChangeAsync(token,1, false);
938

    
939
            if (PrinterSettings.InstalledPrinters != null && PrinterSettings.InstalledPrinters.Count > 0)
940
            {
941
                printDocument = new PrintDocument();
942
                printDocument.OriginAtMargins = true;
943
                printDocument.BeginPrint += new System.Drawing.Printing.PrintEventHandler(printDocument_BeginPrint);
944
                printDocument.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(printDocument_PrintPage);
945
                printDocument.EndPrint += new System.Drawing.Printing.PrintEventHandler(printDocument_EndPrint);
946
            }
947
            else
948
                printDocument = null;
949

    
950
            #region 인쇄 미리보기 테스트
951
            using (System.Windows.Forms.PrintPreviewDialog dlg = new System.Windows.Forms.PrintPreviewDialog())
952
            {
953
                printDocument.PrinterSettings.MinimumPage = 1;
954
                printDocument.PrinterSettings.MaximumPage = _lstPrintPageNo.Count();
955
                printDocument.PrinterSettings.FromPage = 1;
956
                printDocument.PrinterSettings.ToPage = _lstPrintPageNo.Count();
957
                printDocument.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
958
                printDocument.PrinterSettings.PrinterName = PrintName;
959
                dlg.Document = printDocument;
960
                dlg.WindowState = System.Windows.Forms.FormWindowState.Maximized;
961
                dlg.ShowDialog();
962
            }
963
            #endregion
964

    
965
            #region 인쇄
966
            //printDocument.PrinterSettings.MinimumPage = 1;
967
            //printDocument.PrinterSettings.MaximumPage = _lstPrintPageNo.Count();
968
            //printDocument.PrinterSettings.FromPage = 1;
969
            //printDocument.PrinterSettings.ToPage = _lstPrintPageNo.Count();
970

    
971
            //printDocument.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
972
            //printDocument.PrinterSettings.PrinterName = PrintName;
973

    
974
            //printDocument.Print();
975
            #endregion
976
        }
977

    
978
        private void printDocument_BeginPrint(object sender, PrintEventArgs e)
979
        {
980
            //Printimg_List = new Dictionary<int, System.Drawing.Image>();
981
            // This demo only loads one page at a time, so no need to re-set the print page number
982
            PrintDocument document = sender as PrintDocument;
983
            currentPage = document.PrinterSettings.FromPage;
984
        }
985

    
986
        private void printDocument_PrintPage(object sender, PrintPageEventArgs e)
987
        {
988
            //e.Graphics.DrawImage(Printimg_List.Where(info => info.Key == currentPage).FirstOrDefault().Value, 0, 0);
989

    
990
            Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate
991
            {
992
                //p_img = Printimg_List.Where(data => data.Key == currentPage).FirstOrDefault().Value;
993
                p_img = System.Drawing.Image.FromFile(PrintimgPath_List.Where(data => data.Key == currentPage).FirstOrDefault().Value);
994

    
995
                if (p_img.Width > p_img.Height)
996
                {
997
                    p_img.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
998
                }
999

    
1000
                //iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(p_img, System.Drawing.Imaging.ImageFormat.Jpeg);
1001
                System.Drawing.Image pic = p_img;
1002
                System.Drawing.Rectangle m = e.MarginBounds;
1003

    
1004
                //if ((double)pic.Width / (double)pic.Height > (double)m.Width / (double)m.Height) // image is wider
1005
                //{
1006
                //    m.Height = 1135;//(int)((double)pic.Height / (double)pic.Width * (double)m.Width) - 16;
1007
                //}
1008
                //else
1009
                //{
1010
                //    m.Width = 793;//(int)((double)pic.Width / (double)pic.Height * (double)m.Height) - 16;
1011
                //}
1012
                m.Width = (int)e.PageSettings.PrintableArea.Width;
1013
                m.Height = (int)e.PageSettings.PrintableArea.Height;
1014
                m.X = (int)e.PageSettings.HardMarginX;
1015
                m.Y = (int)e.PageSettings.HardMarginY;
1016

    
1017
                e.Graphics.DrawImage(pic, m);
1018
                //e.Graphics.DrawImage(p_img, e.MarginBounds);
1019
                //e.Graphics.DrawImage(p_img, 0, 0);
1020
            }));
1021

    
1022
            //다음 페이지
1023
            currentPage++;
1024

    
1025
            ////인쇄를 계속 할지 말지 확인
1026
            if (currentPage <= printDocument.PrinterSettings.ToPage)
1027
                e.HasMorePages = true;
1028
            else
1029
                e.HasMorePages = false;
1030

    
1031
        }
1032

    
1033
        private void printDocument_EndPrint(object sender, PrintEventArgs e)
1034
        {
1035
            Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate
1036
            {
1037
                //if (Directory.Exists(TempImageDir))
1038
                //    Directory.Delete(TempImageDir, true);
1039

    
1040
                sliderPages.Value = 1;
1041
                printIndy.IsBusy = false;
1042

    
1043
            }));
1044
        }
1045
        #endregion
1046

    
1047
        #region Selected Pages Check
1048
        List<int> PrintPageCreate()
1049
        {
1050
            List<int> Result = new List<int>();
1051

    
1052
            if (GridCurrentPage.Visibility == System.Windows.Visibility.Visible || currentPagePrint)
1053
            {
1054
                Result.Add(CurrentPageNo);
1055
            }
1056
            else if (GridRangePages.Visibility == System.Windows.Visibility.Visible)
1057
            {
1058
                for (int i = Convert.ToInt32(stPageNo.Value); i <= Convert.ToInt32(edPageNo.Value); i++)
1059
                {
1060
                    Result.Add(i);
1061
                }
1062
            }
1063
            else if (GridDefinePages.Visibility == System.Windows.Visibility.Visible)
1064
            {
1065
                int _stPage = (int)stPageNo.Value;
1066
                int _edPage = (int)edPageNo.Value;
1067

    
1068
                var lst = RangeParser.Parse(txtDefinedPages.Text, _stPage, _definePages.PagesCount);
1069
                Result.AddRange(lst);
1070
            }
1071
            else
1072
            {
1073
                for (int i = 1; i <= _definePages.PagesCount; i++)
1074
                {
1075
                    Result.Add(i);
1076
                }
1077
            }
1078
            if (currentPagePrint)
1079
            {
1080
                return Result;
1081
            }
1082

    
1083
            if (chkOnlyMarkup.IsChecked.Value)
1084
            {
1085
                var _result = from result in Result
1086
                              where _PageMarkupList.Where(page => page.PageNumber == result).Count() > 0
1087
                              select result;
1088
                Result = _result.ToList();
1089
            }
1090
            return Result;
1091
        }
1092
        #endregion
1093

    
1094
        #endregion
1095
    }
1096
}
클립보드 이미지 추가 (최대 크기: 500 MB)