프로젝트

일반

사용자정보

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

markus / ConvertService / ConverterService / DZConverterLib / Copy (5) of DZConverter.cs @ fc4e50f2

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

1 7ca218b3 KangIngu
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Text;
5
using System.Collections.ObjectModel;
6
using System.Data.EntityClient;
7
using System.Data.SqlClient;
8
using DeepViewDataModel.DataModel;
9
using DeepViewDataModel.Common;
10
using System.Collections.Concurrent;
11
using System.IO;
12
using DZConverterLib.DAL;
13
using DZConverterLib.Auth;
14
using pdftron;
15
using System.Data.Objects.DataClasses;
16
using pdftron.PDF;
17
using System.Drawing;
18
using System.Drawing.Imaging;
19
using pdftron.SDF;
20
using ImageFields;
21
using DeepView.Toolkit.GuidGenerator;
22
using System.Threading;
23
using System.Net.Cache;
24
using System.Net;
25
using LimitTaskScheduler;
26
using System.Threading.Tasks;
27
using System.Runtime.Caching;
28
using System.Security.Permissions;
29
30
namespace DZConverterLib
31
{
32
    public class DZConverter: IDisposable
33
    {
34
        //public const string ProjectRoot = @"D:\DeepViewConverter\";
35
        //public const string DownloadDir_PDF = ProjectRoot + @"\PDFPath";
36
        public string DownloadDir_PDF;
37
        private PDFDoc doc = null;
38
        private EntityCollection<DocPage> pageSet = null;
39
        public int pageCount = 0;
40
        public ConverterPDF ConverterItem;
41
        public event EventHandler<MakeConverterErrorArgs> ConverterMakeError;
42
        public event EventHandler<EndConverterEventArgs> EndConverter;
43
      
44
        private static ImageCodecInfo DefaultImageCodecInfo = GetEncoderInfo("image/png");
45
        private static EncoderParameters DefaultEncoderParameters = new EncoderParameters(2)
46
        {
47
            Param = new EncoderParameter[]{
48
                new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L),
49
                new EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 8L)
50
            }
51
        };
52
        public DZConverter()
53
        {
54
            pdftron.PDFNet.Initialize("daelim.co.kr(Doftech Corp):CPU:2::W:AMC(20120315):EF6E886F25A414FFB5F8C1F2999CF2DA33DC6C5164315BAF7011B87AF0FA");
55
            
56
            pageSet = new EntityCollection<DocPage>();
57
        }
58
59
        private void SendError(int Level,string ErrorCode, string _Exception, bool ThreadStop)
60
        {
61
            if (ConverterMakeError != null)
62
                ConverterMakeError(this, new MakeConverterErrorArgs 
63
                                            {
64
                                                ThreadStop = ThreadStop, 
65
                                                ConverterID = ConverterItem.ID,
66
                                                _Exception = _Exception,
67
                                                ErrorCode = ErrorCode,
68
                                                Level = Level
69
                                            });
70
        }
71
72
        [FileIOPermission(SecurityAction.LinkDemand)]
73
        public void GetSingleFile(object obj)
74
        {
75
            try
76
            {
77
                ConverterItem = obj as ConverterPDF;
78
79
                using (DeepViewEntities _deepview = new DeepViewEntities(ConnectStringBuilder.DeepViewConnectionString().ToString()))
80
                {
81
                    var _property = _deepview.Properties.Where(pro => pro.Property == ConverterItem.ProjectNo);
82
83
                    if (_property.Count() > 0)
84
                    {
85
                        DownloadDir_PDF = _property.Where(t => t.Type == PropertiesType.PropertiesType.Const_TileSorceStorage).First().Value;
86
87
                        if (!Directory.Exists(DownloadDir_PDF)) // 폴더 없을 시 생성
88
                        {
89
                            Directory.CreateDirectory(DownloadDir_PDF);
90
                        }
91
                    }
92
                }
93
94
                DownloadFile();
95
            }
96
            catch (Exception e)
97
            {
98
                SendError(0, "Converter Error ", e.ToString(), true);
99
            }
100
        }
101
102
        private void SetState(IConverterPDF.ConverterStatus Status)
103
        {
104
            using (DeepViewEntities _entity = new DeepViewEntities(ConnectStringBuilder.DeepViewConnectionString().ToString()))
105
            {
106
                var _items = _entity.ConverterPDF.Where(converter => converter.ID == this.ConverterItem.ID);
107
                if (_items.Count() > 0)
108
                {
109
                    if (Status == IConverterPDF.ConverterStatus.Create)
110
                        _items.First().StartDateTime = DateTime.Now;
111
112
                    _items.First().Status = (int)Status;
113
                    _entity.SaveChanges();
114
                }
115
            }  
116
        }
117
118
        private void SetCurrentPage(int CurrentPage)
119
        {
120
            using (DeepViewEntities _entity = new DeepViewEntities(ConnectStringBuilder.DeepViewConnectionString().ToString()))
121
            {
122
                var _items = _entity.ConverterPDF.Where(converter => converter.ID == this.ConverterItem.ID);
123
                if (_items.Count() > 0)
124
                {
125
                    _items.First().CurrentPage = CurrentPage;
126
                    _entity.SaveChanges();
127
                }
128
            }
129
        }
130
131
        private static object _lock = new object();
132
133
        [FileIOPermission(SecurityAction.LinkDemand)]
134
        public void DownloadFile()
135
        {
136
            string DocUri = ConverterItem.PdfUrl; //PDF 전체 경로
137
            string FileName = DocUri.Remove(0, DocUri.LastIndexOf("/") + 1);
138
            string ProjectFolderPath = DownloadDir_PDF + "\\" + ConverterItem.ProjectNo + "_Tile"; //프로젝트 폴더
139
            string ItemListPath = ProjectFolderPath + "\\" + (System.Convert.ToInt64(ConverterItem.SharepointItemID) / 100).ToString();
140
            string ItemPath = ItemListPath + "\\" + ConverterItem.SharepointItemID;
141
            string DownloadFilePath = ItemPath + "\\" + FileName;
142
          
143
            #region 폴더 생성
144
            try
145
            {
146
                SetState(IConverterPDF.ConverterStatus.Create);
147
148
                DirectoryInfo _dir = new DirectoryInfo(ItemPath);
149
150
                if (_dir.Exists)
151
                {
152
                    _dir.Empty();
153
                }
154
                else
155
                {
156
                    Directory.CreateDirectory(ItemPath);
157
                }
158
159
            }
160
            catch (Exception ex)
161
            {
162
                //DeleteDirectoryDirs(ItemPath);
163
                SendError(0,"폴더삭제 에러",ex.ToString(), false);
164
            }
165
166
            #endregion
167
168
            #region 다운로드
169
170
            try
171
            {
172
                System.Net.WebClient _fileFactory = new System.Net.WebClient();
173
                _fileFactory.UseDefaultCredentials = true;
174
                _fileFactory.DownloadFile(new Uri(DocUri), DownloadFilePath);
175
                _fileFactory.Dispose();
176
177
                if (File.Exists(DownloadFilePath))
178
                {
179
                    ConvertProcess(DownloadFilePath, ItemPath, FileName);
180
                }
181
                else
182
                {
183
                    SendError(1, "File Not Found", "if (File.Exists(DownloadFilePath))", true);
184
                }
185
186
            #endregion
187
            }
188
            catch (Exception ex)
189
            {
190
                SendError(1,"File Download Error : Url - " + DocUri + " Download Path : " + DownloadFilePath, ex.ToString(), true);
191
            }
192
           
193
194
        }
195
196
        [FileIOPermission(SecurityAction.LinkDemand)]
197
        public void ConvertProcess(string DownloadFilePath, string ItemPath, string FileName)
198
        {
199
            #region 기본 설정
200
            doc = new PDFDoc(DownloadFilePath);
201
            #endregion
202
203
            ResultSet Result_Check = new ResultSet();
204
            #region PDF 체크
205
            try
206
            {
207
                Result_Check = Check_PDF();
208
            }
209
            catch (Exception ex)
210
            {
211
                System.Diagnostics.Debug.WriteLine(ex.ToString());
212
                Result_Check.Message = ex.ToString();
213
                Result_Check.result = false;
214
            }
215
            
216
            if (!Result_Check.result)
217
            {
218
                SendError(1, "PDF 체크 실패 : 보안설정으로 인한 PDF 체크 실패", Result_Check.Message,false);
219
            } 
220
            #endregion
221
222
            #region PDF에서 이미지로 변환
223
224
            try
225
            {
226
                int _pageCount = ConvertImage(ItemPath);
227
                if (_pageCount == pageSet.Count())
228
                {
229
                    SetCurrentPage(_pageCount);
230
231
                    var _infotoDBResult = SetPageInfoToDB(); // 데이터베이스 입력
232
                    
233
                    if (_infotoDBResult != null)
234
                        SendError(0, "SetPageInfoToDB()", _infotoDBResult, true);
235
                }
236
                else
237
                {
238
                    SendError(0, "converter Check", "Page Count :" + _pageCount + "   PageSet : " + pageSet.Count(), true);
239
                    return;
240
                } 
241
            }
242
            catch (Exception ex)
243
            {
244
                SendError(0, "converter Check ","if (!ConvertImage(ItemPath, FileName)) " + ex.ToString(), true);
245
            }
246
247
            #endregion
248
249
            if (EndConverter != null)
250
                EndConverter(this, new EndConverterEventArgs { ConverterPDF = ConverterItem});
251
        }
252
253
        public ResultSet Check_PDF()
254
        {
255
            ResultSet _result = new ResultSet();
256
            bool _Security = false;
257
            bool _isEncrypte = true;
258
            try
259
            {
260
261
                _Security = doc.InitSecurityHandler();
262
                _isEncrypte = doc.IsEncrypted();
263
264
                //접근권한 체크
265
                if (!_Security)
266
                {
267
                    _result.result = false;
268
                    _result.Message = "Document authentication Error";
269
                }
270
                else
271
                    if (_isEncrypte)
272
                    {
273
                        _result.result = false;
274
                        _result.Message = "Document is Encrypted";
275
                    }
276
                    else
277
                        _result.result = true;
278
279
            }
280
            catch (Exception ex)
281
            {
282
                System.Diagnostics.Debug.WriteLine(ex.ToString());
283
                _result.Message = ex.ToString();
284
                _result.result = false;
285
            }
286
287
            return _result;
288
        }
289
290
291
        #region private Method
292
       
293
        private static ImageCodecInfo GetEncoderInfo(String mimeType)
294
        {
295
            int j;
296
            ImageCodecInfo[] encoders;
297
            encoders = ImageCodecInfo.GetImageEncoders();
298
            for (j = 0; j < encoders.Length; ++j)
299
            {
300
                if (encoders[j].MimeType == mimeType)
301
                    return encoders[j];
302
            }
303
            return null;
304
        }
305
306
        private int ConvertImage(string FilePath)
307
        {
308
            int _result = 0;
309
            
310
            try
311
            {
312
                Bitmap newBmp_;
313
                pageCount = doc.GetPageCount();
314
315
                using (DeepViewEntities _entity = new DeepViewEntities(ConnectStringBuilder.DeepViewConnectionString().ToString()))
316
                {
317
                    var _items = _entity.ConverterPDF.Where(converter => converter.ID == this.ConverterItem.ID);
318
                    if (_items.Count() > 0)
319
                    {
320
                        _items.First().TotalPages = pageCount;
321
                        _entity.SaveChanges();
322
                    }
323
                }
324
325
                #region 이미지 만들기
326
327
                for (int k = 1; k < pageCount + 1; k++)
328
                {
329
                    try
330
                    {
331
                        using (pdftron.PDF.PDFDraw draw = new pdftron.PDF.PDFDraw())
332
                        {
333
                            var widthData = (int)doc.GetPage(k).GetPageWidth();
334
                            int heightData = (int)doc.GetPage(k).GetPageHeight();
335
                            pageSet.Add(new DocPage
336
                                        {
337
                                            Id = GuidGenerator.GetUniqueGuid(),
338
                                            PageWidth = (widthData * 3).ToString(),
339
                                            PageHeight = (heightData * 3).ToString(),
340
                                            PageNumber = k,
341
                                            PageAngle = 0,
342
                                        });
343
344
                            var rotation = doc.GetPage(k).GetRotation();
345
                            draw.SetImageSize((int)(widthData * 3), (int)(heightData * 3), true);
346
                            //draw.SetImageSize((int)(widthData), (int)(heightData), true);
347
                            draw.SetAntiAliasing(true);
348
                            draw.SetImageSmoothing(true);
349
                            draw.SetThinLineAdjustment(true, true);
350
                            newBmp_ = draw.GetBitmap(doc.GetPage(k));
351
352
                            using (MemoryStream _savestream = new MemoryStream())
353
                            {
354
                                newBmp_.Save(_savestream, DefaultImageCodecInfo, DefaultEncoderParameters);
355
                                newBmp_ = new Bitmap(_savestream);
356
                                ObjSet objset = new ObjSet();
357
                                Obj jbig2_hint = objset.CreateName("png");
358
359
                                string pagePath = FilePath + "\\" + k;
360
361
                                Directory.CreateDirectory(pagePath);
362
                                string _fileName = pagePath + "\\" + k + ".jpg";
363
                                newBmp_.Save(_fileName);
364
                                newBmp_.Dispose();
365
                                _Task.Add(Task.Factory.StartNew<string>(() => ConvertImgToDeep(_fileName, k)));
366
                            }
367
                            SetCurrentPage(k);
368
                        }
369
                    }
370
                    catch (Exception ex)
371
                    {
372
                        SendError(0, "ConverterImage Error : Page NO -" + k.ToString(), ex.ToString(), true);
373
                        return k;
374
                    }
375
376
                }
377
378
                Task.WaitAll(_Task.ToArray());
379
                _result = _Task.Where(r => r.Result.Count() == 0).Count();
380
                if (_result != pageCount)
381
                {
382
                    var _Ex = from task in _Task
383
                              let a = task.Result.Count() > 0
384
                              select new { ex = string.Join(",", a) };
385
386
                    SendError(0, "Converter Error code(21324) : Page Count Error", string.Join(",", _Ex), true);
387
                    return 0;
388
                }
389
                
390
                _Task.ForEach(f=>f.Dispose());
391
                _Task.Clear();
392
393
                GC.Collect(2);
394
                GC.Collect(2);
395
            }
396
            catch (Exception ex)
397
            {
398
                 
399
                SendError(0, "code 1230saf325 Error :", ex.ToString(), true);
400
            }
401
            finally
402
            {
403
                doc.Close();
404
                doc.Dispose();
405
                pdftron.PDFNet.Terminate();
406
                doc = null;
407
            }
408
409
            #endregion
410
            return _result;
411
        }
412
        List<Task<string>> _Task = new List<Task<string>>();
413
414
        private string ConvertImgToDeep(string convertFileName, int Index)
415
        {
416
            string _result = string.Empty;
417
            FileInfo convertFile = new FileInfo(convertFileName);
418
419
            ImageFields.ImageFields creator = new ImageFields.ImageFields
420
            {
421
                TileSize = 256,
422
                TileFormat = ImageFields.ImageFormat.AutoSelect,
423
                CopyMetadata = false,
424
                ConversionCopyMetadata = false,
425
                LowLevelPass = true
426
            };
427
428
            try
429
            {
430
                if (convertFile.Exists)
431
                {
432
                    creator.Create(convertFile.FullName, convertFile.FullName.ToString().Replace(".jpg", ".xml"));
433
                    convertFile.Delete();
434
                    
435
                }
436
                else
437
                {
438
                    _result = "Code 123412545 Page No :" + Index.ToString() + "     ex : File Not";
439
                }
440
            }
441
            catch (Exception ex)
442
            {
443
                System.Diagnostics.Debug.WriteLine(ex.ToString());
444
445
                if (ex.GetType() == typeof(System.ArgumentException))
446
                    _result = "DPI Exception. Page No :" + Index.ToString();
447
                else
448
                    _result = "Code 102312394 Page No :" + Index.ToString() + "     ex" + ex.Message;
449
            }
450
            System.Diagnostics.Debug.WriteLine("ImageFields End : " + _result);
451
            return _result;
452
        }
453
454
        private string SetPageInfoToDB()
455
        {
456
            try
457
            {
458
            
459
                #region DB에 페이지 정보 입력
460
           
461
462
                using (CI_Entities deepViewEntity = new CI_Entities(ConnectStringBuilder.ProjectCIConnectString(ConverterItem.ProjectNo).ToString()))
463
                {
464
                    var _docinfo = deepViewEntity
465
                                    .DocInfo.Where(info => info.OrginPDFUrl == ConverterItem.PdfUrl);
466
467
                    if (_docinfo.Count() > 0)
468
                    {
469
                        System.Diagnostics.Stopwatch _watch = new System.Diagnostics.Stopwatch();
470
                        _watch.Start();
471
                        var _doc = _docinfo.First();
472
                        _doc.SharepointItemID = ConverterItem.SharepointItemID;
473
                        _doc.PageCount = pageCount;
474
475
                        pageSet.AsParallel().ForAll(p => p.DocInfo_Id = _doc.Id);
476
477
                        var _exceptDocInfo = (from newinfo in pageSet
478
                                              select new { newinfo.PageNumber, newinfo.DocInfo_Id,newinfo.PageWidth,newinfo.PageHeight})
479
                                                  .Except
480
                                                        (from oldinfo in _doc.DocPage
481
                                                         select new { oldinfo.PageNumber, oldinfo.DocInfo_Id, oldinfo.PageWidth, oldinfo.PageHeight });
482
483
                        var _delDocInfo = (from oldinfo in _doc.DocPage
484
                                           select new { oldinfo.PageNumber, oldinfo.DocInfo_Id, oldinfo.PageWidth, oldinfo.PageHeight })
485
                                                  .Except
486
                                                        (from newinfo in pageSet
487
                                                         select new { newinfo.PageNumber, newinfo.DocInfo_Id, newinfo.PageWidth, newinfo.PageHeight })
488
                                                         .ToList(); /// 삭제되는 collection은 하나씩 제거 될때마다 수정되기 때문에
489
                                                                    ///  foreach가 안된다. 그러므로 tolist로 가져와서 작업한다.
490
                        
491
                        //using (DeepView_SystemEntities SystemEntity = new DeepView_SystemEntities(ConnectStringBuilder.DeepViewSystemConnectionString().ToString()))
492
                        //{
493
                        //    SystemEntity.RemoveBackup_DocInfo.AddObject(new RemoveBackup_DocInfo
494
                        //    {
495
                        //        BackupUserID = "ConvertStation",
496
                        //        BackupTime= DateTime.Now,
497
                        //        ID = GuidGenerator.GetUniqueGuid(),
498
                        //        OriginDocInfoID = _doc.Id,
499
                        //        SharepointItemID = _doc.SharepointItemID,
500
                        //        OriginPDFUrl= _doc.OrginPDFUrl,
501
                        //        PageCount= _doc.PageCount,
502
                        //        ProjectNo = ConverterItem.ProjectNo,
503
                        //        Status = true
504
                        //    });
505
506
507
                        //    foreach (var item in _delDocInfo)
508
                        //    {
509
                        //        var _delitem = _doc.DocPage.Where(p => p.PageNumber == item.PageNumber).First();
510
511
                        //        deepViewEntity.DocPage.DeleteObject(_delitem);
512
                        //        //deepViewEntity.DocPage.DeleteObject(item);
513
                        //    }
514
                        //}
515
                        foreach (var item in _delDocInfo)
516
                        {
517
                            var _delitem = _doc.DocPage.Where(p => p.PageNumber == item.PageNumber).First();
518
519
                            deepViewEntity.DocPage.DeleteObject(_delitem);
520
                            //deepViewEntity.DocPage.DeleteObject(item);
521
                        }
522
523
                        deepViewEntity.SaveChanges();
524
525
                        foreach (var exceptitem in _exceptDocInfo)
526
                        {
527
                            var _lstPage = deepViewEntity.DocPage.Where(page => page.PageNumber == exceptitem.PageNumber
528
                                                                                    && page.DocInfo_Id == exceptitem.DocInfo_Id);
529
530
                            if (_lstPage.Count() > 0)
531
                            {
532
                                var _page = _lstPage.First();
533
                                _page.PageHeight = exceptitem.PageHeight;
534
                                _page.PageWidth = exceptitem.PageWidth;
535
                            }
536
                            else
537
                            {
538
                                _doc.DocPage.Add(pageSet.Where(p=>p.PageNumber == exceptitem.PageNumber).First());
539
                            }
540
                        }
541
542
                        deepViewEntity.SaveChanges();
543
544
                        _watch.Stop();
545
                        System.Diagnostics.Debug.WriteLine(_watch.ElapsedMilliseconds);
546
                    }
547
                    else
548
                    {
549
550
                        Guid guid = GuidGenerator.GetUniqueGuid();
551
                        DocInfo instace = new DocInfo
552
                        {
553
                            Id = guid,
554
                            OrginPDFUrl = ConverterItem.PdfUrl,
555
                            SharepointItemID = ConverterItem.SharepointItemID,
556
                            PageCount = pageCount,
557
                            DocPage = pageSet
558
                        };
559
                        deepViewEntity.DocInfo.AddObject(instace);
560
                    }
561
562
                    deepViewEntity.SaveChanges();
563
                }
564
            }
565
            catch (Exception e)
566
            {
567
                return e.ToString();
568
            }
569
               
570
            #endregion
571
572
            return null;
573
        }
574
    #endregion
575
576
        public void Dispose()
577
        {
578
            if (doc != null)
579
            {
580
                doc.Close();
581
                doc.Dispose();
582
                pdftron.PDFNet.Terminate();
583
                doc = null;
584
            }
585
586
            GC.Collect();
587
            GC.SuppressFinalize(this);
588
            GC.Collect(2);
589
            GC.Collect(2);
590
        }
591
     
592
    }
593
594
    public enum FinalStatus
595
    {
596
        /// <summary>
597
        /// Final PDF를 만들기 위한 순서에 추가
598
        /// </summary>
599
        Insert = 0,
600
601
        /// <summary>
602
        /// 앞의 final이 처리중일때 대기
603
        /// </summary>
604
        Wait = 1,
605
606
        /// <summary>
607
        /// 만들고 있는중
608
        /// 이때 데이터베이스에 Current Page는 만들고 있는 페이지
609
        /// </summary>
610
        Create = 2,
611
612
        /// <summary>
613
        /// final pdf 완료시
614
        /// </summary>
615
        Seccess = 99,
616
617
        /// <summary>
618
        /// 에러
619
        /// </summary>
620
        Error = 88
621
    }
622
623
}
클립보드 이미지 추가 (최대 크기: 500 MB)