프로젝트

일반

사용자정보

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

markus / ConvertService / ServiceBase / Markus.Service.Convert / ConvertService.cs @ 8ebd5302

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

1
using log4net;
2
using Markus.Message;
3
using Markus.Service.Helper;
4
using System;
5
using System.Collections.Generic;
6
using System.IO;
7
using System.Linq;
8
using System.Net.Http;
9
using System.ServiceModel;
10
using System.Text;
11
using Markus.Service.Extensions;
12
using Markus.Service.WcfClient.StationServiceAsync;
13

    
14
using System.Threading.Tasks;
15
using System.Web;
16
using StatusCodeType = Markus.Message.StatusCodeType;
17
using Microsoft.SqlServer.Server;
18
using Markus.Service.DataBase.Entities;
19
using Markus.Service.DataBase.Repositories;
20

    
21
namespace Markus.Service.Convert
22
{
23
    public class ConvertService : IDisposable
24
    {
25
        // 1GigaBytes
26
        protected ILog logger;
27

    
28
        readonly ProcessContext ConvertProcessContext;
29
        Markus.Service.DataBase.DBMSType DbmsType;
30
        private Markus.SaveTask gSaveTask;
31
        private Markus.MarkusPDF gMarkusPDF;
32
        private string gFontsFolder;
33
        private bool gIsApiDownload;
34

    
35
        // 컨버터 완료시 파일갯수를 체크 하여 틀리면 reconvert를 1로 하고 다시 컨버팅 하도록 한다.
36
        private int ReConvert;
37

    
38

    
39
        private StationServiceClient StationServiceClient; 
40

    
41
        /// <summary>
42
        /// 프로세스 초기화
43
        /// </summary>
44
        /// <param name="convertContext"></param>
45
        public ConvertService(ProcessContext convertContext) : base()
46
        {
47
            logger = LogManager.GetLogger(typeof(ConvertService));
48

    
49
            ConvertProcessContext = convertContext;
50

    
51
            DbmsType = (Markus.Service.DataBase.DBMSType)Enum.Parse(typeof(Markus.Service.DataBase.DBMSType), ConvertProcessContext.DbmsType);
52

    
53
            BasicHttpBinding myBinding = new BasicHttpBinding { TransferMode = TransferMode.Buffered };
54

    
55
            myBinding.CloseTimeout = new TimeSpan(0, 10, 0);
56
            myBinding.ReceiveTimeout = new TimeSpan(0, 10, 0);
57
            myBinding.SendTimeout = new TimeSpan(0, 10, 0);
58
            myBinding.OpenTimeout = new TimeSpan(0, 10, 0);
59

    
60
            EndpointAddress myEndpoint = new EndpointAddress(UriHelper.UriCreate(ConvertProcessContext.ServiceStationUri));
61
            StationServiceClient = new StationServiceClient(myBinding, myEndpoint);
62
            gIsApiDownload = ConvertProcessContext.IsApiDownload;
63

    
64
             gMarkusPDF = new MarkusPDF();
65
            
66
            gSaveTask = new SaveTask();
67

    
68
            if (!string.IsNullOrWhiteSpace(ConvertProcessContext.FontsFolder))
69
            {
70
                gFontsFolder = ConvertProcessContext.FontsFolder;
71
                gSaveTask.SetFontsFolder(ConvertProcessContext.FontsFolder);
72
            }
73

    
74
            gSaveTask.StateChangeEvent += MarkusPdfStateChangeEvent;
75
        }
76

    
77
        public ConvertService()
78
        {
79
        }
80

    
81
        public void Dispose()
82
        {
83
            try
84
            {
85
                if(gMarkusPDF != null)
86
                {
87
                    gMarkusPDF.Dispose();
88
                    gMarkusPDF = null;
89
                }
90

    
91
                if (gSaveTask != null)
92
                {
93
                    gSaveTask.StateChangeEvent -= MarkusPdfStateChangeEvent;
94
                    gSaveTask.Dispose();
95
                    gSaveTask = null;
96
                }
97

    
98
                //if (System.IO.File.Exists(gTempFileName))
99
                //{
100
                //    File.Delete(gTempFileName);
101
                //}
102

    
103
            }
104
            catch (Exception ex)
105
            {
106
               logger.Error("Convert Service Dispose Error", ex);
107
            }
108
            finally
109
            {
110
                GC.Collect(2);
111
                GC.Collect(2);
112
            }
113
        }
114

    
115
        /// <summary>
116
        ///  markus lib에서 받는 이벤트
117
        /// </summary>
118
        /// <param name="sender"></param>
119
        /// <param name="e"></param>
120
        private void MarkusPdfStateChangeEvent(object sender, Markus.Message.StateEventArgs e)
121
        {
122
            try
123
            {
124
                int currentPage = e.SaveItem.CurrentPage;
125

    
126
                if (e.SaveItem.CurrentPage == 0)    /// 초기 wait status인 경우 0일수 있다. %계산시 오류 방지
127
                {
128
                    currentPage = 1;
129
                }
130

    
131
                switch (e.SaveItem.Status)
132
                {
133
                    case Message.StatusCodeType.None:
134
                        break;
135
                    case Message.StatusCodeType.Wait:
136
                        break;
137
                    case Message.StatusCodeType.PageLoading:
138
                        break;
139
                    case Message.StatusCodeType.Saving:
140
                        break;
141
                    case Message.StatusCodeType.Completed:
142
                        break;
143
                    case Message.StatusCodeType.FileError:
144
                        break;
145
                    case Message.StatusCodeType.PageError:
146
                        break;
147
                    case Message.StatusCodeType.FontNotFound:
148
                        break;
149
                    case Message.StatusCodeType.NeedsPassword:
150
                        break;
151
                    case Message.StatusCodeType.Error:
152
                        break;
153
                    default:
154
                        break;
155
                }
156
#if PROCESS_TEST
157
                Console.WriteLine($"send wcf service {e.SaveItem.Status}  currentPage : {e.SaveItem.CurrentPage} error message : {(string.IsNullOrWhiteSpace(e.SaveItem.ErrorMessage)?"null":e.SaveItem.ErrorMessage)}");
158
#endif
159
                StationServiceClient.ConvertProcessState(ConvertProcessContext.ConvertID, (int)e.SaveItem.Status, e.SaveItem.CurrentPage, e.SaveItem.TotalPages, e.SaveItem.ErrorMessage);
160

    
161
            }
162
            catch (Exception ex)
163
            {
164
                logger.Error($"Status Change Error", ex);
165
            }
166
        }
167

    
168
        [System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions]
169
        [System.Security.Permissions.FileIOPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
170
        public SaveItem SetFile()
171
        {
172
            SaveItem saveitem = new SaveItem
173
            {
174
                Id = ConvertProcessContext.ConvertID,
175
                PdfFilePath = ConvertProcessContext.OriginFilePath,
176
                SavePath = ConvertProcessContext.SaveDirectory,
177
                Status = StatusCodeType.None,
178
                MinimumFontSize = ConvertProcessContext.MinFontSize,
179
                UseResolution = ConvertProcessContext.UseResolution
180
            };
181

    
182
            try
183
            {
184
#if PROCESS_TEST
185

    
186
            Console.WriteLine($"ConvertID : {ConvertProcessContext.ConvertID} : {StatusCodeType.Wait.ToString()}");
187

    
188
#endif
189
                StationServiceClient.ConvertProcessState(ConvertProcessContext.ConvertID, (int)StatusCodeType.Wait, 0, 0, "");
190

    
191
                var result = Convert(saveitem);
192

    
193
                saveitem.Status = result.StatusCode;
194
                saveitem.ErrorMessage = result.Message;
195
                
196
                if (saveitem.Status < StatusCodeType.Completed)
197
                {
198
                    saveitem.Status = StatusCodeType.Error;
199
                    saveitem.ErrorMessage = "unknown error";
200
                }
201

    
202
                MarkusPdfStateChangeEvent(this, new StateEventArgs(new SaveItem
203
                {
204
                    ErrorMessage = saveitem.ErrorMessage,
205
                    Id = saveitem.Id,
206
                    CurrentPage = saveitem.CurrentPage,
207
                    TotalPages = saveitem.TotalPages,
208
                    Status = saveitem.Status
209
                }));
210

    
211

    
212
                StationServiceClient.ConvertFinish(saveitem.Id, (int)saveitem.Status, saveitem.CurrentPage, saveitem.TotalPages, saveitem.ErrorMessage);
213
            }
214
            catch (Exception ex)
215
            {
216
                if (saveitem.Status <= StatusCodeType.Completed)
217
                {
218
                    saveitem.Status = StatusCodeType.Error;
219
                }
220

    
221
                saveitem.ErrorMessage = saveitem.ErrorMessage  + "    Exception : " +  ex.ToString();
222

    
223
                if( ex.InnerException != null)
224
                {
225
                    saveitem.ErrorMessage = saveitem.ErrorMessage + "  InnerException : " + ex.InnerException.ToString();
226
                }
227

    
228
                logger.Error($"File Convert Error", ex);
229

    
230
                logger.Error($"saveitem.Id : {saveitem.Id} , StatusCode:{(int)saveitem.Status}, CurrentPage : {saveitem.CurrentPage}, TotalPages : {saveitem.TotalPages} , Error : {saveitem.ErrorMessage}");
231
                StationServiceClient.ConvertFinish(saveitem.Id, (int)saveitem.Status, saveitem.CurrentPage, saveitem.TotalPages, $"ConvertService Error    {saveitem.Id} {saveitem.ErrorMessage }");
232
            }
233

    
234
            try
235
            {
236
                // 플러그인 실행
237
#if PROCESS_TEST
238

    
239
                Console.WriteLine($"run Plugin : {saveitem.Id}");
240
#endif
241
                PluginService.Run(saveitem.Id);
242

    
243
#if PROCESS_TEST
244

    
245
                Console.WriteLine($"finish!!!");
246
#endif
247
            }
248
            catch (Exception ex)
249
            {
250

    
251
                throw;
252
            }
253

    
254
            return saveitem;
255
        }
256

    
257
        private bool MoveOldFiles(string originPath)
258
        {
259
            bool result = false;
260

    
261
            try
262
            {
263
                DirectoryInfo dir = new DirectoryInfo(originPath);
264
            }
265
            catch (Exception)
266
            {
267
            }
268

    
269
            return result;
270
        }
271

    
272
        private SaveResult Convert(SaveItem saveitem)
273
        { 
274
            SaveResult result = new SaveResult();
275
         
276
            try
277
            {
278
                DateTime deleteTime = DateTime.Now;
279

    
280
                while (System.IO.Directory.Exists(saveitem.SavePath))
281
                {
282
                    try
283
                    {
284
                        System.IO.Directory.Delete(saveitem.SavePath, true);
285
                    }
286
                    catch (Exception ex)
287
                    {
288
#if PROCESS_TEST
289
                        Console.WriteLine(ex.ToString());
290
#endif
291
                    }
292

    
293
                    if ((DateTime.Now - deleteTime) > new TimeSpan(0, 5, 0))
294
                    {
295
                        string msg = $"ConvertService Error {saveitem.SavePath} Delete Error";
296
                        logger.Error(msg);
297
                        result.StatusCode = StatusCodeType.FileError;
298
                        result.Message =  LogHelper.GetStack() + " " +LogHelper.GetStack() + " " + msg;
299
#if PROCESS_TEST
300
                        Console.WriteLine($"{StatusCodeType.FileError.ToString()} : {result.Message} ");
301
#endif
302
                        return result;
303
                    }
304

    
305
                    System.Threading.Thread.SpinWait(10);
306
                }
307

    
308
                System.IO.Directory.CreateDirectory(saveitem.SavePath);
309

    
310
                //파일 다운로드
311
                var fileDownloadResult = DownloadFile(saveitem);
312

    
313
                if (fileDownloadResult.IsSuccess)
314
                {
315
                    string downloadFilePath = fileDownloadResult.DownloadFilePath;
316

    
317
                    var status =  gMarkusPDF.pdfLoad(downloadFilePath, saveitem.MinimumFontSize, saveitem.UseResolution, gFontsFolder);
318

    
319
                    if (gMarkusPDF.PageCount() > 0)
320
                    {
321
                        saveitem.TotalPages = gMarkusPDF.PageCount();
322

    
323
                        /// 설정된 MultiThreadMaxPages에 따른 컨버터 분기
324
                        if (gMarkusPDF.PageCount() > ConvertProcessContext.MultiThreadMaxPages)
325
                        {
326
                            // 큰 사이즈의 파일 컨버팅
327
                            result = ConvertBigFileProcess(saveitem.TotalPages, saveitem.Id, downloadFilePath,saveitem.SavePath, saveitem.MinimumFontSize,saveitem.UseResolution,gFontsFolder);
328
                        }
329
                        else
330
                        {
331
                            /// 작은 사이즈의 컨버팅
332
                            result = gSaveTask.SaveFile(new Markus.Message.SaveItem
333
                            {
334
                                PdfFilePath = downloadFilePath,
335
                                SavePath = saveitem.SavePath,
336
                                MinimumFontSize = saveitem.MinimumFontSize,
337
                                UseResolution = saveitem.UseResolution
338
                            });
339
                        }
340
                        
341
                        saveitem.Status = result.StatusCode;
342
                        saveitem.ErrorMessage = result.Message;
343

    
344
                        if ((int)result.StatusCode <= (int)StatusCodeType.Completed)
345
                        {
346
                            // 파일 체크 후 갯수가 안맞으면 다시 컨버팅한다.
347
                            if (ReConvert < 1 && (result.PageInfoList?.Count() != saveitem.TotalPages
348
                                           || Directory.EnumerateFiles(saveitem.SavePath, "*.png").Count() != saveitem.TotalPages
349
                                               || Directory.EnumerateFiles(saveitem.SavePath, "*.jpg").Count() != saveitem.TotalPages))
350
                            {
351
                            
352
                                ///statuscode가 완료 또는 정상인데 페이지가 맞지 않는 경우 pageError로 처리
353
                                if (result.StatusCode <= StatusCodeType.Completed)
354
                                {
355
                                    result.StatusCode = StatusCodeType.PageError;
356
                                    result.Message = LogHelper.GetStack() + "Page Error : " + result.Message;
357
                                }
358

    
359
                                ReConvert = 1;
360

    
361
                                result = ConvertBigFileProcess(saveitem.TotalPages, saveitem.Id, downloadFilePath, saveitem.SavePath, saveitem.MinimumFontSize, saveitem.UseResolution, gFontsFolder);
362

    
363
                                saveitem.Status = result.StatusCode;
364
                                saveitem.ErrorMessage = result.Message;
365
                            }
366

    
367
                            ///  페이지 정보 저장
368
                            if (result.PageInfoList?.Count() > 0)
369
                            {
370
                                bool docSetResult = false;
371

    
372
                                try
373
                                {
374
                                    string docinfoID = null;
375

    
376
                                    using (DOCINFORepository dOCINFORepository = new DOCINFORepository(ConvertProcessContext.ConnectionString,DbmsType))
377
                                    {
378
                                        docinfoID = dOCINFORepository.CreateAsync(convertDocID: saveitem.Id, PageCount: result.PageInfoList.Count()).GetAwaiter().GetResult();
379
                                    }
380

    
381
                                    if (docinfoID != null)
382
                                    {
383
                                        using (DOCPAGERepository database = new DOCPAGERepository(ConvertProcessContext.ConnectionString, DbmsType))
384
                                        {
385
                                            var docPageList = result.PageInfoList.Select(f => new DOCPAGE
386
                                            {
387
                                                DOCINFO_ID = docinfoID,
388
                                                PAGE_ANGLE = 0,
389
                                                PAGE_WIDTH = f.Width.ToString(),
390
                                                PAGE_HEIGHT = f.Height.ToString(),
391
                                                PAGE_NUMBER = f.PageNo
392
                                            });
393

    
394
                                            docSetResult = database.CreateAsync(docPageList).GetAwaiter().GetResult();
395
                                        }
396

    
397
                                        saveitem.CurrentPage = result.PageInfoList.Max(x => x.PageNo);
398
                                    }
399
                                    else
400
                                    {
401
                                        result.StatusCode = StatusCodeType.Error;
402
                                        result.Message += LogHelper.GetStack() + " " + $"DocInfo Insert Error.";
403
                                    }
404
                                }
405
                                catch (Exception ex)
406
                                {
407
                                    result.Message += LogHelper.GetStack() + " " + $"Doc Set Error. {ex.Message}";
408
                                }
409

    
410
                                if (docSetResult)
411
                                {
412
                                    result.StatusCode = StatusCodeType.Completed;
413
                                }
414
                                else
415
                                {
416
                                    result.StatusCode = StatusCodeType.FileError;
417
                                    result.Message = LogHelper.GetStack() + " " + $"Doc Set Error. {result.Message}";
418
                                }
419
                            }
420
                            else
421
                            {
422
                                result.StatusCode = StatusCodeType.FileError;
423
                                result.Message = LogHelper.GetStack() + " " + $"Page List Get Error. {result.Message} ";
424
                            }
425
                        }
426
                    }
427
                    else
428
                    {
429
                        result.Message = $"{status.Message}. File path : { saveitem.PdfFilePath}";
430
                        result.StatusCode = status.StatusCode;
431
                    }
432
                }
433
                else
434
                {
435
                    result.Message  = $"File Download Error  - File path : { saveitem.PdfFilePath}";
436
                    result.StatusCode = StatusCodeType.FileError;
437
                }
438
            }
439
            catch (Exception ex)
440
            {
441
                result.Message =  LogHelper.GetStack() + " " +"ConvertService Convert Error " + ex.Message;
442
                result.StatusCode = StatusCodeType.Error;
443

    
444
                logger.Error(ex);
445
            }
446
            finally
447
            {
448
                if (gMarkusPDF != null)
449
                {
450
                    gMarkusPDF.Dispose();
451
                    gMarkusPDF = null;
452
                }
453

    
454
            }
455

    
456
            return result;
457
        }
458

    
459
        public FileDownloadResult DownloadFile(SaveItem saveItem)
460
        {
461
            FileDownloadResult result = new FileDownloadResult();
462

    
463
            try
464
            {
465
                result = DownloadPluginService.Download(saveItem.PdfFilePath, saveItem.SavePath);
466
            }
467
            catch (Exception ex)
468
            {
469
                logger.Error(ex);
470
                result.IsSuccess = false;
471
                result.Exception = new Exception(ex.ToString());
472
            }
473

    
474
            return result;
475
        }
476

    
477
        ///// <summary>
478
        ///// 파일 다운로드
479
        ///// </summary>
480
        ///// <param name="saveItem"></param>
481
        ///// <returns></returns>
482
        //public async Task<bool> DownloadFileAsync(SaveItem saveItem)
483
        //{
484
        //    bool result = false;
485

    
486
        //    try
487
        //    {
488
        //        Uri pdfFileUri = null;
489

    
490
        //        //if (saveItem.PdfFilePath.Contains("VPCS_DOCLIB"))
491
        //        //{
492
        //        //    FileName = DocUri.Remove(0, DocUri.LastIndexOf("/") + 1);
493
        //        //    ProjectFolderPath = DownloadDir_PDF + "\\" + ConverterItem.PROJECT_NO + "_Tile"; //프로젝트 폴더
494
        //        //    ItemListPath = ProjectFolderPath + "\\" + (System.Convert.ToInt64(ConverterItem.DOCUMENT_ID) / 100).ToString();
495
        //        //    ItemPath = ItemListPath + "\\" + ConverterItem.DOCUMENT_ID;
496
        //        //    DownloadFilePath = ItemPath + "\\" + FileName;
497
        //        //}
498
        //        //else
499
        //        //{
500
        //        //    ProjectFolderPath = DownloadDir_PDF + "\\" + ConverterItem.PROJECT_NO + "_Tile"; //프로젝트 폴더
501
        //        //    ItemListPath = ProjectFolderPath + "\\" + (System.Convert.ToInt64(ConverterItem.DOCUMENT_ID) / 100).ToString();
502
        //        //    ItemPath = ItemListPath + "\\" + ConverterItem.DOCUMENT_ID;
503
        //        //    FileName = HttpUtility.ParseQueryString(new Uri(DocUri).Query).Get("fileName");
504
        //        //    DownloadFilePath = string.IsNullOrWhiteSpace(FileName) ? ItemPath + "\\" + FileName : ItemPath + "\\" + FileName;
505

    
506
        //        //}
507

    
508
        //        saveItem.PdfFilePath = HttpUtility.UrlDecode(saveItem.PdfFilePath); //PDF 전체 경로
509

    
510

    
511
        //        string FileName = "";
512
        //        string downloadFilePath = "";
513

    
514
        //        // 드라이브 경로가 포함되었는지 판단.
515
        //        if (Path.IsPathRooted(saveItem.PdfFilePath))
516
        //        {
517
        //            FileInfo file = new FileInfo(saveItem.PdfFilePath);
518

    
519
        //            if (file.Exists)
520
        //            {
521
        //                FileName = file.Name;
522
        //                downloadFilePath = System.IO.Path.Combine(saveItem.SavePath, FileName);
523
        //                file.CopyTo(downloadFilePath, true);
524
        //            }
525
        //            else
526
        //            {
527
        //                throw new Exception("File Not Found. Please, check the file path.");
528
        //            }
529
        //        }
530
        //        else if (Uri.TryCreate(saveItem.PdfFilePath, UriKind.RelativeOrAbsolute, out pdfFileUri))
531
        //        {
532
        //            try
533
        //            {
534
        //                if (gIsApiDownload)
535
        //                {
536
        //                    ///read api download 
537
        //                    ///벽산
538
        //                    downloadFilePath = await RestDownloadAsync(pdfFileUri, saveItem.SavePath);
539
        //                }
540
        //                else
541
        //                {
542
        //                    FileName = DownloadUri.GetFileName(saveItem.PdfFilePath);
543
        //                    downloadFilePath = System.IO.Path.Combine(saveItem.SavePath, FileName);
544

    
545
        //                    using (System.Net.WebClient webClient = new System.Net.WebClient())
546
        //                    {
547
        //                        webClient.UseDefaultCredentials = true;
548
        //                        webClient.Headers.Add("Authorization: BASIC SGVsbG8="); //가상의 인증
549
        //                        webClient.Proxy = null;
550
        //                        if (!System.IO.Directory.Exists(ConvertProcessContext.TempDirectory))
551
        //                        {
552
        //                            System.IO.Directory.CreateDirectory(ConvertProcessContext.TempDirectory);
553
        //                        }
554

    
555
        //                        webClient.DownloadFile(pdfFileUri, downloadFilePath);
556

    
557
        //                        webClient.Dispose();
558
        //                    }
559
        //                }
560
        //                await Task.Delay(300);
561
        //            }
562
        //            catch (Exception ex)
563
        //            {
564
        //                logger.Error(ex);
565
        //                throw new Exception($"File Download Error. Please, check the file path. {pdfFileUri}");
566
        //            }
567
        //        }
568
        //        else
569
        //        {
570
        //            throw new Exception("Please, check the file path.");
571
        //        }
572

    
573
        //        try
574
        //        {
575
        //            if (File.Exists(downloadFilePath))
576
        //            {
577
        //                var file = File.Open(downloadFilePath, FileMode.Open);
578

    
579
        //                if (file.Length == 0)
580
        //                {
581
        //                    throw new Exception("File Size 0. Please, check the file path.");
582
        //                }
583

    
584
        //                file.Close();
585
        //                file.Dispose();
586

    
587
        //                saveItem.PdfFilePath = downloadFilePath;
588
        //                result = true;
589

    
590
        //            }
591
        //        }
592
        //        catch (Exception ex)
593
        //        {
594
        //            logger.Error(ex);
595
        //            throw new Exception("File Error ." + downloadFilePath);
596
        //        }
597
        //    }
598
        //    catch (Exception ex)
599
        //    {
600
        //        logger.Error(ex);
601
        //        throw new Exception(ex.ToString());
602
        //    }
603

    
604
        //    return result;
605
        //}
606

    
607
        //private  async Task<string> RestDownloadAsync(Uri uri,string savePath)
608
        //{
609
        //    string downloadFilePath = "";
610

    
611
        //    var client = new RestClient(uri);
612
        //    client.Timeout = -1;
613
        //    var request = new RestRequest(Method.GET);
614
        //    IRestResponse response = await client.ExecuteAsync(request);
615

    
616
        //    if (response.StatusCode == System.Net.HttpStatusCode.OK)
617
        //    {
618
        //        var fileName = DownloadUri.GetFileNameInDisposition(new System.Net.Mime.ContentDisposition(response.Headers.Where(x => x.Name == "Content-Disposition").First().Value.ToString()));
619

    
620
        //        downloadFilePath = System.IO.Path.Combine(savePath, fileName);
621

    
622
        //        var fs = File.Create(downloadFilePath);
623

    
624
        //        await fs.WriteAsync(response.RawBytes, 0, response.RawBytes.Length);
625
        //        fs.Close();
626
        //    }
627

    
628
        //    return downloadFilePath;
629
        //}
630

    
631
        /// <summary>
632
        /// 큰파일 변환
633
        /// </summary>
634
        /// <param name="saveitem"></param>
635
        /// <returns></returns>
636
        private SaveResult ConvertBigFileProcess(int totalPages,string convertId, string downloadFilePath, string savePath, int minimumFontSize,int useResolution,string fontsFolder)
637
        {
638
            SaveResult result = new SaveResult();
639
            
640
            try
641
            {
642
                for (int currentPageNo = 1; currentPageNo <= totalPages; currentPageNo++)
643
                {
644
                    try
645
                    {
646
                        string saveFile = Path.Combine(savePath, $"{currentPageNo}.png");
647

    
648
                        if (ReConvert < 1 || (ReConvert == 1 && !File.Exists(saveFile)))
649
                        {
650
                            SaveResult saveResult = new SaveResult { StatusCode = StatusCodeType.None };
651
                            StatusCodeType stateCode = StatusCodeType.Saving;
652

    
653
                            try
654
                            {
655
                                saveResult = gMarkusPDF.SavePage(currentPageNo, saveFile);
656
                            }
657
                            catch (Exception ex)
658
                            {
659
                                result.Message = LogHelper.GetStack() + " " + ex.ToString() + " " + result.Message;
660
                            }
661

    
662
                            result.StatusCode = saveResult.StatusCode;
663

    
664
                            if (result.StatusCode != StatusCodeType.Completed)
665
                            {
666
                                stateCode = result.StatusCode;
667
                            }
668

    
669
                            MarkusPdfStateChangeEvent(this, new StateEventArgs(new SaveItem
670
                            {
671
                                ErrorMessage = result.Message,
672
                                Id = convertId,
673
                                CurrentPage = currentPageNo,
674
                                TotalPages = totalPages,
675
                                Status = stateCode
676
                            }));
677

    
678
                            if (saveResult.StatusCode == StatusCodeType.Completed)
679
                            {
680
                                result.PageInfoAdd(saveResult.SavePageInfo);
681

    
682
                                Console.WriteLine($"CurrentPage : {currentPageNo}");
683

    
684
                                /// 설정된 최대 페이지이거나 설정된 메모리보다 크면 릴리즈
685
                                if ((currentPageNo % ConvertProcessContext.MultiThreadMaxPages == 0 && ConvertProcessContext.MultiThreadMaxPages > 0)
686
                                    || ConvertProcessContext.ReleaseWorkMemory < Environment.WorkingSet)
687
                                {
688
                                    Console.WriteLine($"physical memory : {Environment.WorkingSet}");
689

    
690
                                    gMarkusPDF.Dispose();
691
                                    gMarkusPDF = null;
692
                                    System.Threading.Thread.SpinWait(5);
693

    
694
                                    gMarkusPDF = new MarkusPDF();
695
                                    gMarkusPDF.pdfLoad(downloadFilePath,minimumFontSize,useResolution, fontsFolder);
696
                                }
697

    
698
                                System.Threading.Thread.SpinWait(2);
699
                            }
700
                            else
701
                            {
702
                                Console.WriteLine($"CurrentPage : {currentPageNo}");
703
                                Console.WriteLine($"convert ID : {convertId}");
704
                                Console.WriteLine($"pdf file Path : {downloadFilePath}");
705
                                Console.WriteLine($"save file path : {savePath}");
706
                                Console.WriteLine($"last status code : {result.StatusCode}");
707
                                Console.WriteLine($"error message : {result.Message}");
708

    
709
                                break;
710
                            }
711
                        }
712
                    }
713
                    catch (Exception ex)
714
                    {
715
                        result.StatusCode = StatusCodeType.PageError;
716
                        result.Message =  LogHelper.GetStack() + " " +"Save Error - " + ex.Message;
717

    
718
                        if (gMarkusPDF != null)
719
                        {
720
                            gMarkusPDF.Dispose();
721
                            gMarkusPDF = null;
722
                        }
723

    
724
                        gMarkusPDF = new MarkusPDF();
725
                        gMarkusPDF.pdfLoad(downloadFilePath, minimumFontSize, useResolution, fontsFolder);
726

    
727
                        currentPageNo = currentPageNo - 1;
728
                    }
729
                    finally
730
                    {
731
                     
732
                    }
733
                }
734
            }
735
            catch (Exception ex)
736
            {
737
                result.StatusCode = StatusCodeType.Error;
738
                result.Message =  LogHelper.GetStack() + " " +ex.Message;
739
            }
740

    
741
            return result;
742
        }
743

    
744
        public bool Stop()
745
        {
746
            try
747
            {
748
                gSaveTask.Dispose();
749
            }
750
            catch (Exception ex)
751
            {
752
                System.Diagnostics.Debug.WriteLine(ex.ToString());
753
            }
754

    
755
            return true;
756
        }
757

    
758

    
759
        /// <summary>
760
        /// 사용안함
761
        /// </summary>
762
        /// <param name="param"></param>
763
        /// <returns></returns>
764
        //[System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions]
765
        //[System.Security.Permissions.FileIOPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
766
        //private SaveResult SetFile()
767
        //{
768
        //    var saveitem = new SaveItem
769
        //    {
770
        //        Id = ConvertProcessContext.ConvertID,
771
        //        PdfFilePath = ConvertProcessContext.OriginFilePath,
772
        //        SavePath = ConvertProcessContext.SaveDirectory,
773
        //        Status = StatusCodeType.None
774
        //    };
775

    
776
        //    if (System.IO.Directory.Exists(saveitem.SavePath))
777
        //    {
778
        //        System.IO.Directory.Delete(saveitem.SavePath, true);
779
        //    }
780

    
781
        //    System.IO.Directory.CreateDirectory(saveitem.SavePath);
782

    
783
        //    try
784
        //    {
785
        //        Uri pdfFileUri = null;
786

    
787
        //        if (Uri.TryCreate(saveitem.PdfFilePath, UriKind.RelativeOrAbsolute, out pdfFileUri))
788
        //        {
789
        //            using (System.Net.WebClient webClient = new System.Net.WebClient())
790
        //            {
791
        //                webClient.UseDefaultCredentials = true;//.Headers.Add("Authorization: BASIC SGVsbG8="); //가상의 인증
792

    
793
        //                if (!System.IO.Directory.Exists(ConvertProcessContext.TempDirectory))
794
        //                {
795
        //                    System.IO.Directory.CreateDirectory(ConvertProcessContext.TempDirectory);
796
        //                }
797

    
798
        //                var downloadFilePath = System.IO.Path.Combine(ConvertProcessContext.TempDirectory, saveitem.Id.Replace("-", "") + ".pdf");
799
        //                webClient.DownloadFile(pdfFileUri, downloadFilePath);
800

    
801
        //                saveitem.PdfFilePath = downloadFilePath;
802
        //            }
803
        //        }
804
        //    }
805
        //    catch (Exception ex)
806
        //    {
807
        //        throw new Exception($"File Download Error  - File path : {saveitem.PdfFilePath}");
808
        //    }
809

    
810
        //    StationServiceClient.ConvertProcessStateAsync(saveitem.Id, (int)saveitem.Status, saveitem.CurrentPage, saveitem.TotalPages, saveitem.ErrorMessage);
811

    
812
        //    var result = gSaveTask.SaveFile(saveitem);
813

    
814
        //    return result;
815
        //}
816

    
817
    }
818
}
클립보드 이미지 추가 (최대 크기: 500 MB)