프로젝트

일반

사용자정보

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

markus / KCOM / Controls / PrintControl.xaml.cs @ 762737cd

이력 | 보기 | 이력해설 | 다운로드 (44.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
using System.ComponentModel;
25

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

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

    
38
        public double CurrentValue { get; set; }
39

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

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

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

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

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

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

    
81

    
82
                try
83
                {
84

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

    
94
            }
95
        }
96
    }
97

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

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

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

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

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

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

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

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

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

    
152

    
153
        #endregion
154

    
155
        #region Static Property Defines
156

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

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

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

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

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

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

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

    
197
        }
198
        #endregion
199

    
200
        #region 생성자
201

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

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

    
218
            this.IsEnabled = true;
219

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

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

    
228
            foreach (var info in _markupInfo)
229
            {
230
                if (info.Consolidate == 1)
231
                {
232
                    info.UserName = "Consolidation";
233
                }
234

    
235

    
236
                if((info.MarkupList != null))
237
                { 
238
                    info.MarkupList.ForEach(makup =>
239
                    {
240
                        var _pageMarkup = _PageMarkupList.Where(item => item.PageNumber == makup.PageNumber);
241
                        var _SetMarkupItem = new SetColorMarkupItem { markupID = makup.ID, DisplayColor = info.DisplayColor };
242

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

    
253
                    colorList.Add(new DisplayColorInfo
254
                    {
255
                        UserID = info.UserID,
256
                        DisplayColor = info.DisplayColor,
257
                        Department = info.Depatment,
258
                        UserName = info.UserName,
259
                    });
260
                }
261
            }
262

    
263
            gridViewMarkup.ItemsSource = this._markupInfo;
264
            SetLoadMakupList(this._StartPageNo);
265
            if (_LoadMakupList.Count() == 0)
266
                chkOnlyMarkup.IsChecked = false;
267

    
268
            this.CurrentPageNo = _StartPageNo;
269

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

    
273
            DocumentInfo = _definePages;
274
            this.DataContext = _definePages;
275

    
276
            CheckCommentPages();
277

    
278
            //초기화면 Comment Check된 상태로 보여주기
279
            foreach (var item in _markupInfo)
280
            {
281
                gridViewMarkup.SelectedItems.Add(item);
282
            }
283

    
284
            PageChangeAsync(Common.ViewerDataModel.Instance.NewPagImageCancelToken(), _StartPageNo,false).ConfigureAwait(true);
285

    
286
            sliderPages.Maximum = Convert.ToDouble(this._DocInfo.PAGE_COUNT);
287
            this.stPageNo.Maximum = Convert.ToDouble(this._DocInfo.PAGE_COUNT);
288
            this.edPageNo.Maximum = Convert.ToDouble(this._DocInfo.PAGE_COUNT);
289
            this.IsPrint = isPrint;
290

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

    
306
            _initializeComponentFinished = true;
307

    
308
            //timm.Interval = 10;
309
            //timm.Elapsed += new System.Timers.ElapsedEventHandler(_Timer_Elapsed);
310
            //timm.Enabled = true;
311
        }
312

    
313
        #endregion
314

    
315
        #region Control Event
316
        private async void sliderPages_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
317
        {
318
            if (_initializeComponentFinished)
319
            {
320
                if (!_IsDagSlider)
321
                {
322
                    this.CurrentPageNo = (int)this.sliderPages.Value;
323

    
324
                    if (!IsExportOrPrint)
325
                    {
326
                        await PageChangeAsync(Common.ViewerDataModel.Instance.NewPagImageCancelToken(), this.CurrentPageNo, false);
327
                    }
328
                    //await App.PageStorage.GetPageUriAsync(this.CurrentPageNo);
329
                
330
                    if (_ButtonName == "Current")
331
                    {
332
                        stPageNo.Value = CurrentPageNo;
333
                        edPageNo.Value = CurrentPageNo;
334
                    }
335

    
336
                    //CheckCommentPages();
337
                }
338
            }
339
        }
340

    
341
        private async void sliderPages_DragCompleted(object sender, RadDragCompletedEventArgs e)
342
        {
343
            _IsDagSlider = false;
344
            this.CurrentPageNo = (int)this.sliderPages.Value;
345
            if (_initializeComponentFinished)
346
            {
347
               
348
            }
349
        }
350

    
351
        private void sliderPages_DragStarted(object sender, RadDragStartedEventArgs e)
352
        {
353
            _IsDagSlider = true;
354
        }
355

    
356
        private void chkOnlyMarkup_Checked(object sender, RoutedEventArgs e)
357
        {
358
            if (_initializeComponentFinished)      //GridRangePages
359
            {
360
                CheckCommentPages();
361
            }
362
        }
363

    
364
        private void chkOnlyRedColor_Checked(object sender, RoutedEventArgs e)
365
        {
366
            if (_initializeComponentFinished)      //GridRangePages
367
            {
368
                CheckCommentPages();
369
            }
370
        }
371
        
372

    
373
        string _ButtonName;
374
        private void PageSelect_Checked(object sender, RoutedEventArgs e)
375
        {
376
            if (!_initializeComponentFinished) return;
377

    
378
            _ButtonName = (sender as RadRadioButton).Tag.ToString();
379
            CommentPageList.ItemsSource = null;
380

    
381
            switch (_ButtonName)
382
            {
383
                case "Current":
384
                    stPageNo.Value = CurrentPageNo;
385
                    edPageNo.Value = CurrentPageNo;
386

    
387
                    GridCurrentPage.Visibility = Visibility.Visible;
388
                    GridDefinePages.Visibility = Visibility.Collapsed;
389
                    GridRangePages.Visibility = Visibility.Collapsed;
390
                    GridAllPages.Visibility = Visibility.Collapsed;
391

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

    
415
            CheckCommentPages();
416
        }
417

    
418
        private void PageNo_ValueChanged(object sender, RadRangeBaseValueChangedEventArgs e)
419
        {
420
            if (_initializeComponentFinished)      //GridRangePages
421
            {
422
                if (stPageNo.Value > edPageNo.Value)
423
                {
424
                    if (sender.Equals(stPageNo))
425
                        edPageNo.Value = stPageNo.Value;
426
                    else
427
                        stPageNo.Value = edPageNo.Value;
428
                }
429

    
430
                //뷰어잠시제외(강인구)
431
                //this.LayoutRoot.Dispatcher.BeginInvoke(delegate()
432
                //{
433
                CheckCommentPages();
434
                //});
435
            }
436
        }
437

    
438
        private void txtDefinedPages_TextChanged(object sender, TextChangedEventArgs e)
439
        {
440
            CheckCommentPages();
441
        }
442

    
443
        private void btnClearDefinedPages_Click(object sender, RoutedEventArgs e)
444
        {
445
            txtDefinedPages.Text = "";
446
        }
447

    
448
        private void CommentPageList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
449
        {
450
            if (_initializeComponentFinished)
451
                if (CommentPageList.SelectedItem != null)
452
                    this.CurrentPageNo = (CommentPageList.SelectedItem as MarkupPageItem).PageNumber;
453
        }
454

    
455
        private async void gridViewMarkup_SelectionChanged(object sender, SelectionChangeEventArgs e)
456
        {
457
            if (_initializeComponentFinished)
458
            {
459
                await PageChangeAsync(Common.ViewerDataModel.Instance.NewPagImageCancelToken(),this.CurrentPageNo, false);
460
            }
461
        }
462

    
463
        #endregion
464

    
465
        public async System.Threading.Tasks.Task<bool> PageChangeAsync(System.Threading.CancellationToken cts, int PageNo,bool saveFile, bool Flag = false)
466
        {
467
            System.Diagnostics.Debug.WriteLine("PageChangeAsync " + PageNo);
468
            bool result = false;
469
            //Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate
470
            //{
471
            try
472
            {
473
                _definePages.Back_Image = new ImageBrush();
474
                //var defaultBitmapImage = new BitmapImage(new Uri(_DefaultTileUri + PageNo + ".png"));
475

    
476
                var pages = _definePages.DocumentInfo.DOCPAGE.Where(x => x.PAGE_NUMBER == PageNo);
477

    
478
                if(pages.Count() > 0)
479
                {
480
                    var currentPage = pages.First();
481

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

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

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

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

    
505
                    //    uri = cloneUri;
506
                    //}
507

    
508
                    printCanvas.Children.Clear();
509
                    printCanvas.Width = Convert.ToDouble(currentPage.PAGE_WIDTH);
510
                    printCanvas.Height = Convert.ToDouble(currentPage.PAGE_HEIGHT);
511
                    printCanvas.Background = new ImageBrush{ ImageSource = new BitmapImage(uri)};
512
                    //printCanvas.SnapsToDevicePixels = false;
513
                    //printCanvas.UseLayoutRounding = false;
514
                    //printCanvas.CacheMode = new BitmapCache(50);
515
                    RenderOptions.SetBitmapScalingMode(printCanvas, BitmapScalingMode.HighQuality);
516
                    //printCanvas.RenderTransformOrigin = new Point(0.5, 0.5);
517
                    //printCanvas.RenderTransform = new RotateTransform(currentPage.PAGE_ANGLE);
518
                    //ImageBrush background = new ImageBrush(bitmap);
519
                    //printCanvas.Background = background;
520
                    //printCanvas.Background = new SolidColorBrush(Colors.Transparent);
521

    
522
                    Canvas canvas = new Canvas();
523
                    //canvas.CacheMode = new BitmapCache(50);
524
                    //canvas.SnapsToDevicePixels = false;
525
                    RenderOptions.SetBitmapScalingMode(canvas, BitmapScalingMode.HighQuality);
526
                    //foreach (var info in gridViewMarkup.SelectedItems.Cast<IKCOM.MarkupInfoItem>())
527
                    //{
528
                    //    load.User_Id = info.UserID;
529
                    //    load.document_id = _DocInfo.DOCUMENT_ID;
530
                    //    load.Page_No = PageNo;
531

    
532
                    //    if (chkOnlyRedColor.IsChecked == true)
533
                    //    {
534
                    //        load.DisplayColor = "#FFFF0000";
535
                    //    }
536
                    //    else
537
                    //    {
538
                    //        load.DisplayColor = info.DisplayColor;
539
                    //    }
540

    
541
                    //    load.Markupinfoid = info.MarkupInfoID;
542
                    //    var IsLoad = await load.Markup_LoadAsync(canvas, 0);
543
                    //}
544

    
545
                    var tasks = gridViewMarkup.SelectedItems.Cast<IKCOM.MarkupInfoItem>()
546
                                        .Select(async info =>
547
                                        {
548
                                            Load load = new Load();
549
                                            load.User_Id = info.UserID;
550
                                            load.document_id = _DocInfo.DOCUMENT_ID;
551
                                            load.Page_No = PageNo;
552
                                            load.DisplayColor = chkOnlyRedColor.IsChecked == true ? "#FFFF0000" : info.DisplayColor;
553
                                            load.Markupinfoid = info.MarkupInfoID;
554
                                            return await load.Markup_LoadAsync(canvas, 0);
555
                                        });
556

    
557
                    var results = await System.Threading.Tasks.Task.WhenAll(tasks);
558

    
559
                    //printCanvas.Children.Add(canvas);
560

    
561
                    printCanvas.Children.Add(canvas);
562

    
563
                    //await Dispatcher.InvokeAsync(() => {
564
                    //    printCanvas.UpdateLayout();
565
                    //});
566

    
567
                    if (Flag)
568
                        {
569
                        //MemoryStream ms = new MemoryStream();
570
                        //BmpBitmapEncoder bbe = new BmpBitmapEncoder();
571
                        //bbe.Frames.Add(BitmapFrame.Create(new Uri(_DefaultTileUri + PageNo + ".png")));
572
                        //bbe.Save(ms);
573

    
574
                        //System.Drawing.Image.FromFile()
575
                        //Printimg = System.Drawing.Image.FromStream(stream);
576
                        //await System.Threading.Tasks.Task.Run(() =>
577
                        //{
578
                           await Dispatcher.InvokeAsync(() =>
579
                            {
580
                                Export export = new Export();
581

    
582
                                if (saveFile)
583
                                {
584
                                    var filepath = Path.Combine(TempImageDir, $"{PrintimgPath_List.Count() + 1}.png");
585

    
586
                                    if (export.ExportingFile(printCanvas, printCanvas.Width, printCanvas.Height, filepath))
587
                                    {
588
                                        PrintimgPath_List.Add(PrintimgPath_List.Count() + 1, filepath);
589
                                    }
590
                                    else
591
                                    {
592
                                        throw new Exception($"Export Image Save File Error :{filepath}");
593
                                    }
594
                                }
595
                                else
596
                                {
597
                                    p_img = export.Exporting(PrintView, printCanvas.Width, printCanvas.Height);
598
                                    Printimg_List.Add(Printimg_List.Count() + 1, p_img);
599
                                }
600

    
601
                            },System.Windows.Threading.DispatcherPriority.SystemIdle);
602
                        //});
603
                    }
604

    
605
                        result = true;
606
                    //}
607
                } 
608
            }
609
            catch (Exception ex)
610
            {
611
                //Logger.sendResLog("PrintControl.PageChanged", ex.Message, 0);
612
            }
613

    
614
            return result;
615
            //}));
616
        }
617

    
618

    
619
        public static MemoryStream ByteBufferFromImage(BitmapImage imageSource)
620
        {
621
            var ms = new MemoryStream();
622
            var pngEncoder = new PngBitmapEncoder();
623
            pngEncoder.Frames.Add(BitmapFrame.Create(imageSource));
624
            pngEncoder.Save(ms);
625

    
626
            return ms;
627
        }
628
        //Print 버튼 클릭 이벤트
629
        #region Method - 명령
630
        async void PrintMethod(object sender, RoutedEventArgs e)
631
        {
632
            try
633
            {
634
                var token = Common.ViewerDataModel.Instance.NewPagImageCancelToken();
635

    
636
                if (this.printIndy.IsBusy == true)
637
                    return;
638

    
639
                (this.Parent as RadWindow).CanClose = false;
640

    
641
                await this.Dispatcher.InvokeAsync(() => { 
642
                        this.printIndy.IsBusy = true;
643
                        this.BusyContent = "Printing. . .";
644
                });
645

    
646

    
647
                _lstPrintPageNo = PrintPageCreate();
648

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

    
663
                int cnt = 0;
664

    
665
                IsExportOrPrint = true;
666

    
667
                Printimg_List = new Dictionary<int, System.Drawing.Image>();
668
                PrintimgPath_List = new Dictionary<int, string>();
669
                TempImageDir = Path.Combine(Path.GetTempPath(), "Markus", Common.Commons.ShortGuid());
670

    
671
                if (Directory.Exists(TempImageDir))
672
                {
673
                    Directory.Delete(TempImageDir, true);
674
                }
675

    
676
                Directory.CreateDirectory(TempImageDir);
677

    
678
                foreach (int PageNo in _lstPrintPageNo)
679
                {
680
                    if (IsStop)
681
                        break;
682

    
683
                    cnt++;
684
                    sliderPages.Value = PageNo;
685
                    await PageChangeAsync(token,PageNo, true, true);
686
                    //PageChanged(cnt, true);
687
                }
688
                PrintName = cbPrint.SelectedItem.ToString();
689

    
690
                await this.Dispatcher.InvokeAsync(() => {
691
                    if (cnt == _lstPrintPageNo.Count && !IsStop)
692
                    {
693
                        Printing();
694
                    }
695
                });
696

    
697
                IsExportOrPrint = false;
698
            }
699
            catch (Exception ex)
700
            {
701
                //Logger.sendResLog("PrintMethod", ex.Message, 0);
702
            }
703
            finally
704
            {
705
                if (IsStop)
706
                {
707
                    printIndy.IsBusy = false;
708
                    IsStop = false;
709
                }
710
                (this.Parent as RadWindow).CanClose = true;
711
            }
712

    
713
        }
714

    
715
        //Export 버튼 클릭 이벤트
716
        [System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions]
717
        //[System.Security.Permissions.FileIOPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
718
        async void ExportMethod(object sender, RoutedEventArgs e)
719
        {
720
            try
721
            {
722
                if (this.printIndy.IsBusy == true)
723
                    return;
724

    
725
                var token = Common.ViewerDataModel.Instance.NewPagImageCancelToken();
726

    
727
                (this.Parent as RadWindow).CanClose = false;
728

    
729
                this.printIndy.IsBusy = true;
730
                this.BusyContent = "Exporting. . .";
731

    
732
                Export export = new Export();
733
                _lstPrintPageNo = PrintPageCreate();
734

    
735
                if (_lstPrintPageNo.Count == 0)
736
                {
737
                    sliderPages.Value = 1;
738
                    this.printIndy.IsBusy = false;
739
                    RadWindow.Alert(new DialogParameters
740
                    {
741
                        Owner = Application.Current.MainWindow,
742
                        Theme = new VisualStudio2013Theme(),
743
                        Header = "Info",
744
                        Content = "Not specified the page.",
745
                    });
746
                    return;
747
                }
748

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

    
751
                switch (cbPrint.SelectedIndex)
752
                {
753
                    case (0):
754
                        {
755
                            SaveDig.Filter = "PDF file format|*.pdf";
756
                            break;
757
                        }
758
                    case (1):
759
                        {
760
                            SaveDig.Filter = "Image Files (*.jpg, *.Jpeg)|*.jpg;*.Jpeg";
761
                            break;
762
                        }
763
                }
764

    
765
                SaveDig.Title = "Save an PDF File";
766
                if(SaveDig.ShowDialog().Value)
767
                {
768
                    IsExportOrPrint = true;
769

    
770
                    PrintimgPath_List = new Dictionary<int, string>();
771
                    TempImageDir = Path.Combine(Path.GetTempPath(), "Markus", Common.Commons.ShortGuid());
772

    
773
                    if (Directory.Exists(TempImageDir))
774
                    {
775
                        Directory.Delete(TempImageDir, true);
776
                    }
777

    
778
                    Directory.CreateDirectory(TempImageDir);
779

    
780
                    foreach (int PageNo in _lstPrintPageNo)
781
                    {
782
                        if (IsStop)
783
                            break;
784

    
785
                        await Dispatcher.InvokeAsync(() =>
786
                        {
787
                            sliderPages.Value = PageNo;
788
                        });
789

    
790
                        await PageChangeAsync(token, PageNo, true, true);
791

    
792
                        System.Diagnostics.Debug.WriteLine("Export Page : " + PageNo);
793
                    }
794

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

    
797
                    if (SaveDig.FileName != "")
798
                    {
799
                        switch (cbPrint.SelectedIndex)
800
                        {
801
                            case (0):
802
                                {
803
                                    FileStream fs = new FileStream(SaveDig.FileName, FileMode.Create, FileAccess.Write);
804

    
805
                                    Document doc = new Document();
806
                                    try
807
                                    {
808
                                        iTextSharp.text.Version.GetInstance();
809
                                    }
810
                                    catch (System.NullReferenceException ex)
811
                                    {
812

    
813
                                    }
814

    
815
                                    PdfWriter writer = PdfWriter.GetInstance(doc, fs);
816

    
817
                                    doc.Open();
818
                                    
819
                                    float height = doc.PageSize.Height;
820
                                    float width = doc.PageSize.Width;
821

    
822
                                    foreach (var item in PrintimgPath_List)
823
                                    {
824
                                        if (IsStop)
825
                                            break;
826

    
827
                                        System.Drawing.Image image = System.Drawing.Image.FromFile(item.Value);
828
                                        Export_img = iTextSharp.text.Image.GetInstance(image,System.Drawing.Imaging.ImageFormat.Jpeg);
829

    
830
                                        if (Export_img.Width > Export_img.Height)
831
                                        {
832
                                            doc.SetPageSize(new Rectangle(height, width));
833
                                            Export_img.ScaleToFit(height, width);
834
                                        }
835
                                        else
836
                                        {
837
                                            doc.SetPageSize(new Rectangle(width, height));
838
                                            Export_img.ScaleToFit(width, height);
839
                                        }
840

    
841
                                        Export_img.SetAbsolutePosition(0, 0);
842

    
843
                                        doc.NewPage();
844
                                        doc.Add(Export_img);
845
                                    }
846
                                    doc.Close();
847
                                    writer.Close();
848
                                    break;
849
                                }
850
                            case (1):
851
                                {
852
                                    foreach (var item in PrintimgPath_List)
853
                                    {
854
                                        if (IsStop)
855
                                            break;
856

    
857
                                        File.Copy(item.Value, SaveDig.FileName.Replace(".jpg", "_" + item.Key.ToString()) + ".jpg");
858
                                    }
859
                                    break;
860
                                }
861
                        }
862
                    }
863
                    else
864
                    {
865
                        sliderPages.Value = 1;
866
                        this.printIndy.IsBusy = false;
867
                        return;
868
                    }
869

    
870
                    await this.Dispatcher.InvokeAsync(() =>
871
                    {
872
                        sliderPages.Value = 1;
873
                        printIndy.IsBusy = false;
874
                    });
875

    
876
                    await PageChangeAsync(token,_StartPageNo, false);
877

    
878
                    IsExportOrPrint = false;
879

    
880
                    (Application.Current.MainWindow as MainWindow).dzMainMenu.DialogMessage_Alert("Success", "Alert");
881
                }else
882
                {
883
                    Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate
884
                    {
885
                        sliderPages.Value = 1;
886
                        printIndy.IsBusy = false;
887
                    }));
888

    
889
                    //(Application.Current.MainWindow as MainWindow).dzMainMenu.DialogMessage_Alert("Cancel", "Alert");
890
                }                
891
            }
892
            catch (Exception ex)
893
            {
894
                sliderPages.Value = 1;
895
                printIndy.IsBusy = false;
896

    
897
                //Logger.sendResLog("Export Method", ex.Message, 0);
898
                //(Application.Current.MainWindow as MainWindow).dzMainMenu.DialogMessage_Alert("Alert", "관리자 확인이 필요합니다. 다시 시도해 주세요.\n"+ex.Message);
899
            }
900
            finally
901
            {
902
                GC.Collect();
903
                GC.WaitForPendingFinalizers();
904
                GC.Collect();
905
                IsStop = false;
906
                (this.Parent as RadWindow).CanClose = true;
907
            }
908
        }
909

    
910
        #endregion
911

    
912
        #region Method - 처리
913
        void CheckCommentPages()
914
        {
915
            List<MarkupPageItem> _pages = new List<MarkupPageItem>();
916
            DoubleCollection _Ticks = new DoubleCollection();
917

    
918

    
919
            if (GridCurrentPage.Visibility == System.Windows.Visibility.Visible)
920
            {
921

    
922
                _pages = (from commPage in this._PageMarkupList
923
                          where commPage.PageNumber == CurrentPageNo
924
                          orderby commPage.PageNumber
925
                          select commPage).ToList();
926
            }
927
            else if (GridRangePages.Visibility == System.Windows.Visibility.Visible)
928
            {
929
                stPageNo.Value = stPageNo.Value == null ? 1 : stPageNo.Value;
930
                edPageNo.Value = edPageNo.Value == null ? 1 : edPageNo.Value;
931

    
932
                int _stPage = (int)stPageNo.Value;
933
                int _edPage = (int)edPageNo.Value;
934

    
935
                _pages = (from commPage in this._PageMarkupList
936
                          where commPage.PageNumber >= _stPage && commPage.PageNumber <= _edPage
937
                          orderby commPage.PageNumber
938
                          select commPage).ToList();
939
            }
940
            else if (GridDefinePages.Visibility == System.Windows.Visibility.Visible)
941
            {
942
                stPageNo.Value = stPageNo.Value == null ? 1 : stPageNo.Value;
943
                edPageNo.Value = edPageNo.Value == null ? 1 : edPageNo.Value;
944

    
945
                int _stPage = (int)stPageNo.Value;
946
                int _edPage = (int)edPageNo.Value;
947

    
948
                //Using DeepView.Common.RangeParser
949
                var lst = RangeParser.Parse(txtDefinedPages.Text, _stPage, _definePages.PagesCount);
950
                _pages = (from commPage in this._PageMarkupList
951
                          from compareData in lst
952
                          where commPage.PageNumber == compareData
953
                          orderby commPage.PageNumber
954
                          select commPage).ToList();
955
            }
956
            else
957
            {
958
                _pages = (from commPage in this._PageMarkupList
959
                          orderby commPage.PageNumber
960
                          select commPage).ToList();
961
            }
962

    
963
            CommentPageList.ItemsSource = _pages.ToList();
964
        }
965

    
966
        void SetLoadMakupList(int PageNo)
967
        {
968
            _LoadMakupList.Clear();
969
            var _markupList = _PageMarkupList.Where(page => page.PageNumber == PageNo);
970

    
971
            if (_markupList.Count() > 0)
972
                _LoadMakupList = _markupList.First().DisplayColorItems.ToList();
973
        }
974

    
975
        #region 프린트 리스트 가져오기
976
        public void GetPrint(bool flag)
977
        {
978
            if (flag)
979
            {
980
                foreach (string printer in PrinterSettings.InstalledPrinters)
981
                {
982
                    this.cbPrint.Items.Add(printer);
983
                }
984
                printDocument = new PrintDocument();
985
                this.cbPrint.SelectedItem = printDocument.PrinterSettings.PrinterName;
986
            }
987
            else
988
            {
989
                this.cbPrint.Items.Add("PDF");
990
                this.cbPrint.Items.Add("IMAGE");
991

    
992
                this.cbPrint.SelectedItem = "PDF";
993
            }
994
        }
995
        #endregion
996

    
997
        #region 프린트 실행
998
        public async void Printing()
999
        {
1000
            var token = Common.ViewerDataModel.Instance.NewPagImageCancelToken ();
1001

    
1002
            await PageChangeAsync(token,1, false);
1003

    
1004
            if (PrinterSettings.InstalledPrinters != null && PrinterSettings.InstalledPrinters.Count > 0)
1005
            {
1006
                printDocument = new PrintDocument();
1007
                printDocument.OriginAtMargins = true;
1008
                printDocument.BeginPrint += new System.Drawing.Printing.PrintEventHandler(printDocument_BeginPrint);
1009
                printDocument.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(printDocument_PrintPage);
1010
                printDocument.EndPrint += new System.Drawing.Printing.PrintEventHandler(printDocument_EndPrint);
1011
            }
1012
            else
1013
                printDocument = null;
1014

    
1015
            #region 인쇄 미리보기 테스트
1016
            using (System.Windows.Forms.PrintPreviewDialog dlg = new System.Windows.Forms.PrintPreviewDialog())
1017
            {
1018
                printDocument.PrinterSettings.MinimumPage = 1;
1019
                printDocument.PrinterSettings.MaximumPage = _lstPrintPageNo.Count();
1020
                printDocument.PrinterSettings.FromPage = 1;
1021
                printDocument.PrinterSettings.ToPage = _lstPrintPageNo.Count();
1022
                printDocument.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
1023
                printDocument.PrinterSettings.PrinterName = PrintName;
1024
                dlg.Document = printDocument;
1025
                dlg.WindowState = System.Windows.Forms.FormWindowState.Maximized;
1026
                dlg.ShowDialog();
1027
            }
1028
            #endregion
1029

    
1030
            #region 인쇄
1031
            //printDocument.PrinterSettings.MinimumPage = 1;
1032
            //printDocument.PrinterSettings.MaximumPage = _lstPrintPageNo.Count();
1033
            //printDocument.PrinterSettings.FromPage = 1;
1034
            //printDocument.PrinterSettings.ToPage = _lstPrintPageNo.Count();
1035

    
1036
            //printDocument.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
1037
            //printDocument.PrinterSettings.PrinterName = PrintName;
1038

    
1039
            //printDocument.Print();
1040
            #endregion
1041
        }
1042

    
1043
        private void printDocument_BeginPrint(object sender, PrintEventArgs e)
1044
        {
1045
            //Printimg_List = new Dictionary<int, System.Drawing.Image>();
1046
            // This demo only loads one page at a time, so no need to re-set the print page number
1047
            PrintDocument document = sender as PrintDocument;
1048
            currentPage = document.PrinterSettings.FromPage;
1049
        }
1050

    
1051
        private void printDocument_PrintPage(object sender, PrintPageEventArgs e)
1052
        {
1053
            //e.Graphics.DrawImage(Printimg_List.Where(info => info.Key == currentPage).FirstOrDefault().Value, 0, 0);
1054

    
1055
            Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate
1056
            {
1057
                //p_img = Printimg_List.Where(data => data.Key == currentPage).FirstOrDefault().Value;
1058
                p_img = System.Drawing.Image.FromFile(PrintimgPath_List.Where(data => data.Key == currentPage).FirstOrDefault().Value);
1059

    
1060
                if (p_img.Width > p_img.Height)
1061
                {
1062
                    p_img.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
1063
                }
1064

    
1065
                //iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(p_img, System.Drawing.Imaging.ImageFormat.Jpeg);
1066
                System.Drawing.Image pic = p_img;
1067
                System.Drawing.Rectangle m = e.MarginBounds;
1068

    
1069
                //if ((double)pic.Width / (double)pic.Height > (double)m.Width / (double)m.Height) // image is wider
1070
                //{
1071
                //    m.Height = 1135;//(int)((double)pic.Height / (double)pic.Width * (double)m.Width) - 16;
1072
                //}
1073
                //else
1074
                //{
1075
                //    m.Width = 793;//(int)((double)pic.Width / (double)pic.Height * (double)m.Height) - 16;
1076
                //}
1077
                m.Width = (int)e.PageSettings.PrintableArea.Width;
1078
                m.Height = (int)e.PageSettings.PrintableArea.Height;
1079
                m.X = (int)e.PageSettings.HardMarginX;
1080
                m.Y = (int)e.PageSettings.HardMarginY;
1081

    
1082
                e.Graphics.DrawImage(pic, m);
1083
                //e.Graphics.DrawImage(p_img, e.MarginBounds);
1084
                //e.Graphics.DrawImage(p_img, 0, 0);
1085
            }));
1086

    
1087
            //다음 페이지
1088
            currentPage++;
1089

    
1090
            ////인쇄를 계속 할지 말지 확인
1091
            if (currentPage <= printDocument.PrinterSettings.ToPage && !IsStop)
1092
                e.HasMorePages = true;
1093
            else
1094
                e.HasMorePages = false;
1095

    
1096
        }
1097

    
1098
        private void printDocument_EndPrint(object sender, PrintEventArgs e)
1099
        {
1100
            Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate
1101
            {
1102
                //if (Directory.Exists(TempImageDir))
1103
                //    Directory.Delete(TempImageDir, true);
1104

    
1105
                sliderPages.Value = 1;
1106
                printIndy.IsBusy = false;
1107
                IsStop = false;
1108
            }));
1109
        }
1110
        #endregion
1111

    
1112
        #region Selected Pages Check
1113
        List<int> PrintPageCreate()
1114
        {
1115
            List<int> Result = new List<int>();
1116

    
1117
            if (GridCurrentPage.Visibility == System.Windows.Visibility.Visible || currentPagePrint)
1118
            {
1119
                Result.Add(CurrentPageNo);
1120
            }
1121
            else if (GridRangePages.Visibility == System.Windows.Visibility.Visible)
1122
            {
1123
                for (int i = Convert.ToInt32(stPageNo.Value); i <= Convert.ToInt32(edPageNo.Value); i++)
1124
                {
1125
                    Result.Add(i);
1126
                }
1127
            }
1128
            else if (GridDefinePages.Visibility == System.Windows.Visibility.Visible)
1129
            {
1130
                int _stPage = (int)stPageNo.Value;
1131
                int _edPage = (int)edPageNo.Value;
1132

    
1133
                var lst = RangeParser.Parse(txtDefinedPages.Text, _stPage, _definePages.PagesCount);
1134
                Result.AddRange(lst);
1135
            }
1136
            else
1137
            {
1138
                for (int i = 1; i <= _definePages.PagesCount; i++)
1139
                {
1140
                    Result.Add(i);
1141
                }
1142
            }
1143
            if (currentPagePrint)
1144
            {
1145
                return Result;
1146
            }
1147

    
1148
            if (chkOnlyMarkup.IsChecked.Value)
1149
            {
1150
                var _result = from result in Result
1151
                              where _PageMarkupList.Where(page => page.PageNumber == result).Count() > 0
1152
                              select result;
1153
                Result = _result.ToList();
1154
            }
1155
            return Result;
1156
        }
1157
        #endregion
1158

    
1159
        #endregion
1160

    
1161
        private void btPrintCancel_click(object sender, RoutedEventArgs e)
1162
        {
1163
            IsStop = true;
1164
        }
1165
    }
1166
}
클립보드 이미지 추가 (최대 크기: 500 MB)