프로젝트

일반

사용자정보

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

markus / ConvertService / ServiceBase / Markus.Service.Convert / ConvertService.cs @ a5e5fff6

이력 | 보기 | 이력해설 | 다운로드 (32 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 System.Web.UI;
19
using Markus.Service.DataBase.Entities;
20
using Markus.Service.DataBase.Repositories;
21

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

    
29
        readonly ProcessContext ConvertProcessContext;
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
            BasicHttpBinding myBinding = new BasicHttpBinding { TransferMode = TransferMode.Buffered };
52

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

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

    
62
             gMarkusPDF = new MarkusPDF();
63
            
64
            gSaveTask = new SaveTask();
65

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

    
72
            gSaveTask.StateChangeEvent += MarkusPdfStateChangeEvent;
73
        }
74

    
75
        public ConvertService()
76
        {
77
        }
78

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

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

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

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

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

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

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

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

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

    
180
            try
181
            {
182
#if PROCESS_TEST
183

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

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

    
189
                var result = Convert(saveitem);
190

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

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

    
209

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

    
219
                saveitem.ErrorMessage = saveitem.ErrorMessage  + "    Exception : " +  ex.ToString();
220

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

    
226
                logger.Error($"File Convert Error", ex);
227

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

    
232
            try
233
            {
234
                // 플러그인 실행
235
#if PROCESS_TEST
236

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

    
241
#if PROCESS_TEST
242

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

    
249
                throw;
250
            }
251

    
252
            return saveitem;
253
        }
254

    
255
        private bool MoveOldFiles(string originPath)
256
        {
257
            bool result = false;
258

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

    
267
            return result;
268
        }
269

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

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

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

    
303
                    System.Threading.Thread.SpinWait(10);
304
                }
305

    
306
                System.IO.Directory.CreateDirectory(saveitem.SavePath);
307

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

    
311
                if (fileDownloadResult.IsSuccess)
312
                {
313
                    string downloadFilePath = fileDownloadResult.DownloadFilePath;
314

    
315
                    var status =  gMarkusPDF.pdfLoad(downloadFilePath, saveitem.MinimumFontSize, saveitem.UseResolution, gFontsFolder);
316

    
317
                    if (gMarkusPDF.PageCount() > 0)
318
                    {
319
                        saveitem.TotalPages = gMarkusPDF.PageCount();
320

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

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

    
357
                                ReConvert = 1;
358

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

    
361
                                saveitem.Status = result.StatusCode;
362
                                saveitem.ErrorMessage = result.Message;
363
                            }
364

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

    
370
                                try
371
                                {
372
                                    using (DOCINFORepository dOCINFORepository = new DOCINFORepository(ConvertProcessContext.ConnectionString))
373
                                    {
374
                                        var docinfoId = dOCINFORepository.CreateAsync(convertDocID: saveitem.Id, PageCount: result.PageInfoList.Count()).GetAwaiter().GetResult();
375

    
376
                                        using (DOCPAGERepository database = new DOCPAGERepository(ConvertProcessContext.ConnectionString))
377
                                        {
378
                                            var docPageList = result.PageInfoList.Select(f => new DOCPAGE
379
                                            {
380
                                                DOCINFO_ID = docinfoId,
381
                                                PAGE_ANGLE = 0,
382
                                                PAGE_WIDTH = f.Width.ToString(),
383
                                                PAGE_HEIGHT = f.Height.ToString(),
384
                                                PAGE_NUMBER = f.PageNo
385
                                            });
386

    
387
                                            docSetResult = database.CreateAsync(docPageList).GetAwaiter().GetResult();
388
                                        }
389
                                    }
390

    
391
                                    saveitem.CurrentPage = result.PageInfoList.Max(x => x.PageNo);
392

    
393
                                }
394
                                catch (Exception ex)
395
                                {
396
                                    result.Message += LogHelper.GetStack() + " " + $"Doc Set Error. {ex.Message}";
397
                                }
398

    
399
                                if (docSetResult)
400
                                {
401
                                    result.StatusCode = StatusCodeType.Completed;
402
                                }
403
                                else
404
                                {
405
                                    result.StatusCode = StatusCodeType.FileError;
406
                                    result.Message = LogHelper.GetStack() + " " + $"Doc Set Error. {result.Message}";
407
                                }
408
                            }
409
                            else
410
                            {
411
                                result.StatusCode = StatusCodeType.FileError;
412
                                result.Message = LogHelper.GetStack() + " " + $"Page List Get Error. {result.Message} ";
413
                            }
414
                        }
415
                    }
416
                    else
417
                    {
418
                        result.Message = $"{status.Message}. File path : { saveitem.PdfFilePath}";
419
                        result.StatusCode = status.StatusCode;
420
                    }
421
                }
422
                else
423
                {
424
                    result.Message  = $"File Download Error  - File path : { saveitem.PdfFilePath}";
425
                    result.StatusCode = StatusCodeType.FileError;
426
                }
427
            }
428
            catch (Exception ex)
429
            {
430
                result.Message =  LogHelper.GetStack() + " " +"ConvertService Convert Error " + ex.Message;
431
                result.StatusCode = StatusCodeType.Error;
432

    
433
                logger.Error(ex);
434
            }
435
            finally
436
            {
437
                if (gMarkusPDF != null)
438
                {
439
                    gMarkusPDF.Dispose();
440
                    gMarkusPDF = null;
441
                }
442

    
443
            }
444

    
445
            return result;
446
        }
447

    
448
        public FileDownloadResult DownloadFile(SaveItem saveItem)
449
        {
450
            FileDownloadResult result = new FileDownloadResult();
451

    
452
            try
453
            {
454
                result = DownloadPluginService.Download(saveItem.PdfFilePath, saveItem.SavePath);
455
            }
456
            catch (Exception ex)
457
            {
458
                logger.Error(ex);
459
                result.IsSuccess = false;
460
                result.Exception = new Exception(ex.ToString());
461
            }
462

    
463
            return result;
464
        }
465

    
466
        ///// <summary>
467
        ///// 파일 다운로드
468
        ///// </summary>
469
        ///// <param name="saveItem"></param>
470
        ///// <returns></returns>
471
        //public async Task<bool> DownloadFileAsync(SaveItem saveItem)
472
        //{
473
        //    bool result = false;
474

    
475
        //    try
476
        //    {
477
        //        Uri pdfFileUri = null;
478

    
479
        //        //if (saveItem.PdfFilePath.Contains("VPCS_DOCLIB"))
480
        //        //{
481
        //        //    FileName = DocUri.Remove(0, DocUri.LastIndexOf("/") + 1);
482
        //        //    ProjectFolderPath = DownloadDir_PDF + "\\" + ConverterItem.PROJECT_NO + "_Tile"; //프로젝트 폴더
483
        //        //    ItemListPath = ProjectFolderPath + "\\" + (System.Convert.ToInt64(ConverterItem.DOCUMENT_ID) / 100).ToString();
484
        //        //    ItemPath = ItemListPath + "\\" + ConverterItem.DOCUMENT_ID;
485
        //        //    DownloadFilePath = ItemPath + "\\" + FileName;
486
        //        //}
487
        //        //else
488
        //        //{
489
        //        //    ProjectFolderPath = DownloadDir_PDF + "\\" + ConverterItem.PROJECT_NO + "_Tile"; //프로젝트 폴더
490
        //        //    ItemListPath = ProjectFolderPath + "\\" + (System.Convert.ToInt64(ConverterItem.DOCUMENT_ID) / 100).ToString();
491
        //        //    ItemPath = ItemListPath + "\\" + ConverterItem.DOCUMENT_ID;
492
        //        //    FileName = HttpUtility.ParseQueryString(new Uri(DocUri).Query).Get("fileName");
493
        //        //    DownloadFilePath = string.IsNullOrWhiteSpace(FileName) ? ItemPath + "\\" + FileName : ItemPath + "\\" + FileName;
494

    
495
        //        //}
496

    
497
        //        saveItem.PdfFilePath = HttpUtility.UrlDecode(saveItem.PdfFilePath); //PDF 전체 경로
498

    
499

    
500
        //        string FileName = "";
501
        //        string downloadFilePath = "";
502

    
503
        //        // 드라이브 경로가 포함되었는지 판단.
504
        //        if (Path.IsPathRooted(saveItem.PdfFilePath))
505
        //        {
506
        //            FileInfo file = new FileInfo(saveItem.PdfFilePath);
507

    
508
        //            if (file.Exists)
509
        //            {
510
        //                FileName = file.Name;
511
        //                downloadFilePath = System.IO.Path.Combine(saveItem.SavePath, FileName);
512
        //                file.CopyTo(downloadFilePath, true);
513
        //            }
514
        //            else
515
        //            {
516
        //                throw new Exception("File Not Found. Please, check the file path.");
517
        //            }
518
        //        }
519
        //        else if (Uri.TryCreate(saveItem.PdfFilePath, UriKind.RelativeOrAbsolute, out pdfFileUri))
520
        //        {
521
        //            try
522
        //            {
523
        //                if (gIsApiDownload)
524
        //                {
525
        //                    ///read api download 
526
        //                    ///벽산
527
        //                    downloadFilePath = await RestDownloadAsync(pdfFileUri, saveItem.SavePath);
528
        //                }
529
        //                else
530
        //                {
531
        //                    FileName = DownloadUri.GetFileName(saveItem.PdfFilePath);
532
        //                    downloadFilePath = System.IO.Path.Combine(saveItem.SavePath, FileName);
533

    
534
        //                    using (System.Net.WebClient webClient = new System.Net.WebClient())
535
        //                    {
536
        //                        webClient.UseDefaultCredentials = true;
537
        //                        webClient.Headers.Add("Authorization: BASIC SGVsbG8="); //가상의 인증
538
        //                        webClient.Proxy = null;
539
        //                        if (!System.IO.Directory.Exists(ConvertProcessContext.TempDirectory))
540
        //                        {
541
        //                            System.IO.Directory.CreateDirectory(ConvertProcessContext.TempDirectory);
542
        //                        }
543

    
544
        //                        webClient.DownloadFile(pdfFileUri, downloadFilePath);
545

    
546
        //                        webClient.Dispose();
547
        //                    }
548
        //                }
549
        //                await Task.Delay(300);
550
        //            }
551
        //            catch (Exception ex)
552
        //            {
553
        //                logger.Error(ex);
554
        //                throw new Exception($"File Download Error. Please, check the file path. {pdfFileUri}");
555
        //            }
556
        //        }
557
        //        else
558
        //        {
559
        //            throw new Exception("Please, check the file path.");
560
        //        }
561

    
562
        //        try
563
        //        {
564
        //            if (File.Exists(downloadFilePath))
565
        //            {
566
        //                var file = File.Open(downloadFilePath, FileMode.Open);
567

    
568
        //                if (file.Length == 0)
569
        //                {
570
        //                    throw new Exception("File Size 0. Please, check the file path.");
571
        //                }
572

    
573
        //                file.Close();
574
        //                file.Dispose();
575

    
576
        //                saveItem.PdfFilePath = downloadFilePath;
577
        //                result = true;
578

    
579
        //            }
580
        //        }
581
        //        catch (Exception ex)
582
        //        {
583
        //            logger.Error(ex);
584
        //            throw new Exception("File Error ." + downloadFilePath);
585
        //        }
586
        //    }
587
        //    catch (Exception ex)
588
        //    {
589
        //        logger.Error(ex);
590
        //        throw new Exception(ex.ToString());
591
        //    }
592

    
593
        //    return result;
594
        //}
595

    
596
        //private  async Task<string> RestDownloadAsync(Uri uri,string savePath)
597
        //{
598
        //    string downloadFilePath = "";
599

    
600
        //    var client = new RestClient(uri);
601
        //    client.Timeout = -1;
602
        //    var request = new RestRequest(Method.GET);
603
        //    IRestResponse response = await client.ExecuteAsync(request);
604

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

    
609
        //        downloadFilePath = System.IO.Path.Combine(savePath, fileName);
610

    
611
        //        var fs = File.Create(downloadFilePath);
612

    
613
        //        await fs.WriteAsync(response.RawBytes, 0, response.RawBytes.Length);
614
        //        fs.Close();
615
        //    }
616

    
617
        //    return downloadFilePath;
618
        //}
619

    
620
        /// <summary>
621
        /// 큰파일 변환
622
        /// </summary>
623
        /// <param name="saveitem"></param>
624
        /// <returns></returns>
625
        private SaveResult ConvertBigFileProcess(int totalPages,string convertId, string downloadFilePath, string savePath, int minimumFontSize,int useResolution,string fontsFolder)
626
        {
627
            SaveResult result = new SaveResult();
628
            
629
            try
630
            {
631
                for (int currentPageNo = 1; currentPageNo <= totalPages; currentPageNo++)
632
                {
633
                    try
634
                    {
635
                        string saveFile = Path.Combine(savePath, $"{currentPageNo}.png");
636

    
637
                        if (ReConvert < 1 || (ReConvert == 1 && !File.Exists(saveFile)))
638
                        {
639
                            SaveResult saveResult = new SaveResult { StatusCode = StatusCodeType.None };
640
                            StatusCodeType stateCode = StatusCodeType.Saving;
641

    
642
                            try
643
                            {
644
                                saveResult = gMarkusPDF.SavePage(currentPageNo, saveFile);
645
                            }
646
                            catch (Exception ex)
647
                            {
648
                                result.Message = LogHelper.GetStack() + " " + ex.ToString() + " " + result.Message;
649
                            }
650

    
651
                            result.StatusCode = saveResult.StatusCode;
652

    
653
                            if (result.StatusCode != StatusCodeType.Completed)
654
                            {
655
                                stateCode = result.StatusCode;
656
                            }
657

    
658
                            MarkusPdfStateChangeEvent(this, new StateEventArgs(new SaveItem
659
                            {
660
                                ErrorMessage = result.Message,
661
                                Id = convertId,
662
                                CurrentPage = currentPageNo,
663
                                TotalPages = totalPages,
664
                                Status = stateCode
665
                            }));
666

    
667
                            if (saveResult.StatusCode == StatusCodeType.Completed)
668
                            {
669
                                result.PageInfoAdd(saveResult.SavePageInfo);
670

    
671
                                Console.WriteLine($"CurrentPage : {currentPageNo}");
672

    
673
                                /// 설정된 최대 페이지이거나 설정된 메모리보다 크면 릴리즈
674
                                if ((currentPageNo % ConvertProcessContext.MultiThreadMaxPages == 0 && ConvertProcessContext.MultiThreadMaxPages > 0)
675
                                    || ConvertProcessContext.ReleaseWorkMemory < Environment.WorkingSet)
676
                                {
677
                                    Console.WriteLine($"physical memory : {Environment.WorkingSet}");
678

    
679
                                    gMarkusPDF.Dispose();
680
                                    gMarkusPDF = null;
681
                                    System.Threading.Thread.SpinWait(5);
682

    
683
                                    gMarkusPDF = new MarkusPDF();
684
                                    gMarkusPDF.pdfLoad(downloadFilePath,minimumFontSize,useResolution, fontsFolder);
685
                                }
686

    
687
                                System.Threading.Thread.SpinWait(2);
688
                            }
689
                            else
690
                            {
691
                                Console.WriteLine($"CurrentPage : {currentPageNo}");
692
                                Console.WriteLine($"convert ID : {convertId}");
693
                                Console.WriteLine($"pdf file Path : {downloadFilePath}");
694
                                Console.WriteLine($"save file path : {savePath}");
695
                                Console.WriteLine($"last status code : {result.StatusCode}");
696
                                Console.WriteLine($"error message : {result.Message}");
697

    
698
                                break;
699
                            }
700
                        }
701
                    }
702
                    catch (Exception ex)
703
                    {
704
                        result.StatusCode = StatusCodeType.PageError;
705
                        result.Message =  LogHelper.GetStack() + " " +"Save Error - " + ex.Message;
706

    
707
                        if (gMarkusPDF != null)
708
                        {
709
                            gMarkusPDF.Dispose();
710
                            gMarkusPDF = null;
711
                        }
712

    
713
                        gMarkusPDF = new MarkusPDF();
714
                        gMarkusPDF.pdfLoad(downloadFilePath, minimumFontSize, useResolution, fontsFolder);
715

    
716
                        currentPageNo = currentPageNo - 1;
717
                    }
718
                    finally
719
                    {
720
                     
721
                    }
722
                }
723
            }
724
            catch (Exception ex)
725
            {
726
                result.StatusCode = StatusCodeType.Error;
727
                result.Message =  LogHelper.GetStack() + " " +ex.Message;
728
            }
729

    
730
            return result;
731
        }
732

    
733
        public bool Stop()
734
        {
735
            try
736
            {
737
                gSaveTask.Dispose();
738
            }
739
            catch (Exception ex)
740
            {
741
                System.Diagnostics.Debug.WriteLine(ex.ToString());
742
            }
743

    
744
            return true;
745
        }
746

    
747

    
748
        /// <summary>
749
        /// 사용안함
750
        /// </summary>
751
        /// <param name="param"></param>
752
        /// <returns></returns>
753
        //[System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions]
754
        //[System.Security.Permissions.FileIOPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
755
        //private SaveResult SetFile()
756
        //{
757
        //    var saveitem = new SaveItem
758
        //    {
759
        //        Id = ConvertProcessContext.ConvertID,
760
        //        PdfFilePath = ConvertProcessContext.OriginFilePath,
761
        //        SavePath = ConvertProcessContext.SaveDirectory,
762
        //        Status = StatusCodeType.None
763
        //    };
764

    
765
        //    if (System.IO.Directory.Exists(saveitem.SavePath))
766
        //    {
767
        //        System.IO.Directory.Delete(saveitem.SavePath, true);
768
        //    }
769

    
770
        //    System.IO.Directory.CreateDirectory(saveitem.SavePath);
771

    
772
        //    try
773
        //    {
774
        //        Uri pdfFileUri = null;
775

    
776
        //        if (Uri.TryCreate(saveitem.PdfFilePath, UriKind.RelativeOrAbsolute, out pdfFileUri))
777
        //        {
778
        //            using (System.Net.WebClient webClient = new System.Net.WebClient())
779
        //            {
780
        //                webClient.UseDefaultCredentials = true;//.Headers.Add("Authorization: BASIC SGVsbG8="); //가상의 인증
781

    
782
        //                if (!System.IO.Directory.Exists(ConvertProcessContext.TempDirectory))
783
        //                {
784
        //                    System.IO.Directory.CreateDirectory(ConvertProcessContext.TempDirectory);
785
        //                }
786

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

    
790
        //                saveitem.PdfFilePath = downloadFilePath;
791
        //            }
792
        //        }
793
        //    }
794
        //    catch (Exception ex)
795
        //    {
796
        //        throw new Exception($"File Download Error  - File path : {saveitem.PdfFilePath}");
797
        //    }
798

    
799
        //    StationServiceClient.ConvertProcessStateAsync(saveitem.Id, (int)saveitem.Status, saveitem.CurrentPage, saveitem.TotalPages, saveitem.ErrorMessage);
800

    
801
        //    var result = gSaveTask.SaveFile(saveitem);
802

    
803
        //    return result;
804
        //}
805

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