프로젝트

일반

사용자정보

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

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

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

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

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

    
38
        public double CurrentValue { get; set; }
39

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

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

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

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

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

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

    
81

    
82
                try
83
                {
84

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

    
94
            }
95
        }
96
    }
97

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

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

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

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

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

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

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

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

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

    
151

    
152
        #endregion
153

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

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

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

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

    
177
        }
178
        #endregion
179

    
180
        #region 생성자
181

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

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

    
198
            this.IsEnabled = true;
199

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

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

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

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

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

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

    
243
            this.CurrentPageNo = _StartPageNo;
244

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

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

    
251
            CheckCommentPages();
252

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

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

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

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

    
281
            _initializeComponentFinished = true;
282

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

    
288
        #endregion
289

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

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

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

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

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

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

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

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

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

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

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

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

    
390
            CheckCommentPages();
391
        }
392

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

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

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

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

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

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

    
438
        #endregion
439

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

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

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

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

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

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

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

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

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

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

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

    
497

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

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

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

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

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

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

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

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

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

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

    
571

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

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

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

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

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

    
599

    
600
                _lstPrintPageNo = PrintPageCreate();
601

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

    
616
                int cnt = 0;
617

    
618
                IsExportOrPrint = true;
619

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

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

    
629
                Directory.CreateDirectory(TempImageDir);
630

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

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

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

    
658
        }
659

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

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

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

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

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

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

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

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

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

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

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

    
723
                    Directory.CreateDirectory(TempImageDir);
724

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

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

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

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

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

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

    
755
                                    }
756

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

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

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

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

    
780
                                        Export_img.SetAbsolutePosition(0, 0);
781

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

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

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

    
814
                    IsExportOrPrint = false;
815

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

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

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

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

    
846
        #endregion
847

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

    
854

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1032
        }
1033

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

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

    
1044
            }));
1045
        }
1046
        #endregion
1047

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

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

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

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

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