프로젝트

일반

사용자정보

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

markus / FinalService / KCOM_FinalService / MarkupToPDF / MarkupToPDF.cs @ 73dfc330

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

1
using IFinalPDF;
2
using iTextSharp.text.pdf;
3
using KCOMDataModel.Common;
4
using KCOMDataModel.DataModel;
5
using MarkupToPDF.Controls.Common;
6
using MarkupToPDF.Serialize.Core;
7
using MarkupToPDF.Serialize.S_Control;
8
using Markus.Fonts;
9
using System;
10
using System.Collections.Generic;
11
using System.Configuration;
12
using System.IO;
13
using System.Linq;
14
using System.Net;
15
using System.Runtime.InteropServices;
16
using System.Text;
17
using System.Web;
18
using System.Windows;
19
using System.Windows.Media;
20

    
21
namespace MarkupToPDF
22
{
23
    public class MarkupToPDF : IDisposable
24
    {
25
        public MarkupToPDF()
26
        {
27
        }
28

    
29
        #region 초기 데이터
30
        private FileInfo PdfFilePath = null;
31
        private FileInfo FinalPDFPath = null;
32
        private string _FinalPDFStorgeLocal = null;
33
        private string _FinalPDFStorgeRemote = null;
34
        private string OriginFileName = null;
35
        public FINAL_PDF FinalItem;
36
        public DOCINFO DocInfoItem = null;
37
        public List<DOCPAGE> DocPageItem = null;
38
        public MARKUP_INFO MarkupInfoItem = null;
39
        public List<MARKUP_DATA> MarkupDataSet = null;
40
        //private string _PrintPDFStorgeLocal = null;
41
        //private string _PrintPDFStorgeRemote = null;
42
        public event EventHandler<MakeFinalErrorArgs> FinalMakeError;
43
        public event EventHandler<EndFinalEventArgs> EndFinal;
44
        public event EventHandler<StatusChangedEventArgs> StatusChanged;
45

    
46
        private iTextSharp.text.Rectangle pdfSize { get; set; }
47
        private double pageW = 0;
48
        private double pageH = 0;
49

    
50
        //private const double zoomLevel = 3.0;
51
        private const double zoomLevel = 1.0; // 지금은 3배수로 곱하지 않고 있음
52
        #endregion
53

    
54
        #region 메서드        
55
        public static bool IsLocalIPAddress(string host)
56
        {
57
            try
58
            {
59
                IPAddress[] hostIPs = Dns.GetHostAddresses(host);
60
                IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
61

    
62
                foreach (IPAddress hostIP in hostIPs)
63
                {
64
                    if (IPAddress.IsLoopback(hostIP)) return true;
65

    
66
                    foreach (IPAddress localIP in localIPs)
67
                    {
68
                        if (hostIP.Equals(localIP)) return true;
69
                    }
70
                }
71
            }
72
            catch { }
73
            return false;
74
        }
75

    
76
        private void SetNotice(string finalID, string message)
77
        {
78
            if (FinalMakeError != null)
79
            {
80
                FinalMakeError(this, new MakeFinalErrorArgs { FinalID = finalID, Message = message });
81
            }
82
        }
83

    
84
        private string GetFileName(string hrefLink)
85
        {
86
            try
87
            {
88
                if (hrefLink.Contains("vpcs_doclib"))
89
                {
90
                    return System.IO.Path.GetFileName(hrefLink.Replace("/", "\\"));
91
                }
92
                else
93
                {
94
                    Uri fileurl = new Uri(hrefLink);
95
                    int index = hrefLink.IndexOf("?");
96
                    string filename = HttpUtility.ParseQueryString(fileurl.Query).Get("fileName");
97
                    return filename;
98
                }
99
            }
100
            catch (Exception ex)
101
            {
102
                throw ex;
103
            }
104
        }
105

    
106
        public Point GetPdfPointSystem(Point point)
107
        {
108
            /// 주어진 좌표를 pdf의 (Left, Top - Bottom(?)) 좌표에 맞추어 변환한다.
109
            /// Rotation 90 일 경우 pdfsize box 와 media box 가 달라 다른 계산식 적용
110
            if (pdfSize.Rotation == 90)
111
            {
112
                return new Point(pdfSize.Left + (float)(point.X / scaleWidth), pdfSize.Top - (float)(point.Y / scaleHeight) - pdfSize.Bottom);
113
            }
114
            else
115
            {
116
                return new Point(pdfSize.Left + (float)(point.X / scaleWidth), pdfSize.Height - (float)(point.Y / scaleHeight) + pdfSize.Bottom);
117
            }  
118
        }
119

    
120
        public double GetPdfSize(double size)
121
        {
122
            return (size / scaleWidth);
123
        }
124

    
125
        public List<Point> GetPdfPointSystem(List<Point> point)
126
        {
127
            List<Point> dummy = new List<Point>();
128
            foreach (var item in point)
129
            {
130
                dummy.Add(GetPdfPointSystem(item));
131
            }
132
            return dummy;
133
        }
134

    
135
        public double returnAngle(Point start, Point end)
136
        {
137
            double angle = MathSet.getAngle(start.X, start.Y, end.X, end.Y);
138
            //angle *= -1;
139

    
140
            angle += 90;
141
            //if (angle < 0)
142
            //{
143
            //    angle = angle + 360;
144
            //}
145
            return angle;
146
        }
147

    
148
        #endregion
149

    
150
        public bool AddStamp(string stampData)
151
        {
152
            bool result = false;
153

    
154
            try
155
            {
156
                using (KCOMEntities _entity = new KCOMEntities(KCOMDataModel.Common.ConnectStringBuilder.KCOMConnectionString().ToString()))
157
                {
158
                    var stamp = _entity.PROPERTIES.Where(x => x.TYPE == "STAMP");
159

    
160
                    if(stamp.Count() > 0)
161
                    {
162
                        var xamldata = Serialize.Core.JsonSerializerHelper.CompressStamp(stampData);
163

    
164
                        stamp.First().VALUE = xamldata;
165
                        _entity.SaveChanges();
166
                        result = true;
167
                    }
168
                }
169
            }
170
            catch (Exception)
171
            {
172

    
173
                throw;
174
            }
175

    
176
            return result;
177

    
178
        }
179

    
180
        #region 생성자 & 소멸자
181
        public void MakeFinalPDF(object _FinalPDF)
182
        {
183
            DOCUMENT_ITEM documentItem;
184
            FINAL_PDF FinalPDF = (FINAL_PDF)_FinalPDF;
185
            FinalItem = FinalPDF;
186

    
187

    
188
            string PdfFilePathRoot = null;
189
            string TestFile = System.IO.Path.GetTempFileName();
190

    
191
            #region 문서 경로를 가져오는 것과 Status를 Create (1단계) 로 수정
192
            try
193
            {
194
                using (KCOMEntities _entity = new KCOMEntities(KCOMDataModel.Common.ConnectStringBuilder.KCOMConnectionString().ToString()))
195
                {
196
                    var _properties = _entity.PROPERTIES.Where(pro => pro.PROPERTY == FinalPDF.PROJECT_NO);
197

    
198
                    if (_properties.Count() > 0)
199
                    {
200
                        if (_properties.Where(t => t.TYPE == PropertiesType.Const_TileSorcePath).Count() == 0)
201
                        {
202
                            SetNotice(FinalPDF.ID, $"Project {FinalPDF.PROJECT_NO} : TileSourcePath Not Found.");
203
                            return;
204
                        }
205
                        else
206
                        {
207
                            PdfFilePathRoot = _properties.Where(t => t.TYPE == PropertiesType.Const_TileSorcePath).First().VALUE;
208
                        }
209

    
210
                        if (_properties.Where(t => t.TYPE == PropertiesType.Const_FinalPDFStorgeLocal).Count() == 0)
211
                        {
212
                            SetNotice(FinalPDF.ID, $"Project {FinalPDF.PROJECT_NO} : FinalPDFStorgeLocal Not Found.");
213
                            return;
214
                        }
215
                        else
216
                        {
217
                            _FinalPDFStorgeLocal = _properties.Where(t => t.TYPE == PropertiesType.Const_FinalPDFStorgeLocal).First().VALUE;
218
                        }
219

    
220

    
221
                        if (_properties.Where(t => t.TYPE == PropertiesType.Const_FinalPDFStorgeRemote).Count() == 0)
222
                        {
223
                            SetNotice(FinalPDF.ID, $"Project {FinalPDF.PROJECT_NO} : FinalPDFStorgeRemote Not Found.");
224
                            return;
225
                        }
226
                        else
227
                        {
228
                            _FinalPDFStorgeRemote = _properties.Where(t => t.TYPE == PropertiesType.Const_FinalPDFStorgeRemote).First().VALUE;
229
                        }
230
                    }
231
                    else
232
                    {
233
                        SetNotice(FinalPDF.ID, $"Project {FinalPDF.PROJECT_NO} : Final PDF Properties Not Found.");
234
                        return;
235
                    }
236

    
237
                    var finalList = _entity.FINAL_PDF.Where(final => final.ID == FinalPDF.ID);
238

    
239
                    if (finalList.Count() > 0)
240
                    {
241
                        finalList.FirstOrDefault().START_DATETIME = DateTime.Now;
242
                        finalList.FirstOrDefault().STATUS = (int)FinalStatus.Create;
243
                        _entity.SaveChanges();
244
                    }
245

    
246
                }
247
            }
248
            catch (Exception ex)
249
            {
250
                SetNotice(FinalPDF.ID, "프로퍼티 에러: " + ex.ToString());
251
                return;
252
            }
253
            #endregion
254

    
255
            #region 문서 복사
256
            try
257
            {
258
                using (CIEntities _entity = new CIEntities(KCOMDataModel.Common.ConnectStringBuilder.ProjectCIConnectString(FinalPDF.PROJECT_NO).ToString()))
259
                {
260
                    var _DOCINFO = _entity.DOCINFO.Where(doc => doc.ID == FinalPDF.DOCINFO_ID);
261

    
262
                    if (_DOCINFO.Count() > 0)
263
                    {
264
                        DocInfoItem = _DOCINFO.First();
265

    
266
                        DocPageItem = _entity.DOCPAGE.Where(x => x.DOCINFO_ID == DocInfoItem.ID).ToList();
267

    
268
                        PdfFilePathRoot = PdfFilePathRoot + @"\" + FinalPDF.PROJECT_NO + "_Tile" + @"\"
269
                                         + (FinalPDF.DOCUMENT_ID.All(char.IsDigit) ? (System.Convert.ToInt64(FinalPDF.DOCUMENT_ID) / 100).ToString() : FinalPDF.DOCUMENT_ID.Substring(0, 5))
270
                                         + @"\" + FinalPDF.DOCUMENT_ID + @"\";
271

    
272
                        var infoItems = _entity.MARKUP_INFO.Where(x => x.DOCINFO_ID == DocInfoItem.ID && x.CONSOLIDATE == 1 && x.AVOID_CONSOLIDATE == 0 && x.PART_CONSOLIDATE == 0);
273

    
274
                        if (infoItems.Count() == 0)
275
                        {
276
                            throw new InvalidOperationException("콘솔리데잇이 작업 요청 후에 수정 / 삭제 되었습니다");
277
                        }
278
                        else
279
                        {
280
                            MarkupInfoItem = infoItems.First();
281

    
282
                            var markupInfoVerItems = _entity.MARKUP_INFO_VERSION.Where(x => x.MARKUPINFO_ID == MarkupInfoItem.ID).ToList();
283

    
284
                            if (markupInfoVerItems.Count() > 0)
285
                            {
286
                                var markupInfoVerItem = markupInfoVerItems.OrderByDescending(x => x.CREATE_DATE).First();
287

    
288
                                MarkupDataSet = _entity.MARKUP_DATA.Where(x => x.MARKUPINFO_VERSION_ID == markupInfoVerItem.ID).OrderBy(d => d.PAGENUMBER).ToList();
289
                            }
290
                            else
291
                            {
292
                                throw new InvalidOperationException("MARKUP_INFO_VERSION 이 존재 하지 않습니다");
293
                            }
294
                        }
295

    
296
                        documentItem = _entity.DOCUMENT_ITEM.Where(data => data.DOCUMENT_ID == DocInfoItem.DOCUMENT_ID && data.PROJECT_NO == FinalPDF.PROJECT_NO).FirstOrDefault();
297
                        if (documentItem == null)
298
                        {
299
                            throw new InvalidOperationException("DocInfo와 DocumentItem의 documentItemID가 같지 않습니다. 데이터를 확인해주세요");
300
                        }
301

    
302
                        var _files = new DirectoryInfo(PdfFilePathRoot).GetFiles("*.pdf"); //해당 폴더에 파일을 
303

    
304
                        #region 파일 체크
305
                        if (_files.Count() == 1)
306
                        {
307
                            /// 문서 관리 시스템의 원본 PDF 파일과 비교 --> 삭제될 예정
308
                            //if (_files.First().Name.ToLower() == GetFileName(HttpUtility.UrlDecode(documentItem.ORIGINAL_FILE).ToLower()))
309
                            //{
310
                            OriginFileName = _files.First().Name;
311
                            PdfFilePath = _files.First().CopyTo(TestFile, true);
312
                            StatusChange($"Copy File  file Count = 1 : {PdfFilePath}", 0);
313
                            //}
314
                            //else
315
                            //{
316
                            //    throw new Exception("현재 폴더 내 파일명이 데이터베이스와 상이합니다.filename:" + _files.First().Name.ToLower() + ",url:" + HttpUtility.UrlDecode(documentItem.ORIGINAL_FILE).ToLower());
317
                            //}
318
                        }
319
                        else if (_files.Count() > 1)
320
                        {
321
                            var originalFile = _files.FirstOrDefault(data => data.Name == GetFileName(HttpUtility.UrlDecode(documentItem.ORIGINAL_FILE)));
322

    
323
                            if (originalFile == null)
324
                            {
325
                                throw new FileNotFoundException("해당 폴더에 복수로 PDF들 존재하고 document_Item의 문서는 존재하지 않습니다");
326
                            }
327
                            else
328
                            {
329
                                OriginFileName = originalFile.Name;
330
                                PdfFilePath = originalFile.CopyTo(TestFile, true);
331
                                StatusChange($"Copy File file Count  > 1 : {PdfFilePath}", 0);
332
                            }
333
                        }
334
                        else
335
                        {
336
                            throw new FileNotFoundException("PDF를 찾지 못하였습니다");
337
                        }
338
                        #endregion
339

    
340
                        #region 예외처리
341
                        if (PdfFilePath == null)
342
                        {
343
                            throw new InvalidOperationException("작업에 필요한 PDF가 정상적으로 복사되지 않았거나 DB정보가 상이합니다");
344
                        }
345
                        if (!PdfFilePath.Exists)
346
                        {
347
                            throw new FileNotFoundException("PDF원본이 존재하지 않습니다");
348
                        }
349
                        #endregion
350

    
351
                    }
352
                    else
353
                    {
354
                        throw new InvalidOperationException("일치하는 DocInfo가 없습니다");
355
                    }
356
                }
357
            }
358
            catch (Exception ex)
359
            {
360
                if (ex.Message == "사용 가능한" || ex.Message == "작업을 완료했습니다")
361
                {
362
                    SetNotice(FinalPDF.ID, "Desktop 내 힙메모리 부족으로 서비스 진행이 되지 않아 재시작 합니다");
363
                    //System.Diagnostics.Process process = new System.Diagnostics.Process();
364
                    //process.StartInfo.FileName = "cmd";
365
                    //process.StartInfo.Arguments = "/c net stop \"FinalService\" & net start \"FinalService\"";
366
                    //process.Start();
367
                }
368
                else
369
                {
370
                    SetNotice(FinalPDF.ID, "PDF를 Stamp 중 에러 : " + ex.Message);
371
                }
372
            }
373
            #endregion
374

    
375
            try
376
            {
377

    
378
                using (KCOMEntities _entity = new KCOMEntities(KCOMDataModel.Common.ConnectStringBuilder.KCOMConnectionString().ToString()))
379
                {
380
                    var finalList = _entity.FINAL_PDF.Where(final => final.ID == FinalPDF.ID);
381
                    if (finalList.Count() > 0)
382
                    {
383
                        //TestFile = SetFlattingPDF(TestFile);
384
                        //StatusChange($"SetFlattingPDF : {TestFile}", 0);
385

    
386
                        SetStampInPDF(FinalItem, TestFile, MarkupInfoItem);
387

    
388
                        StatusChange($"SetStampInPDF : {TestFile}", 0);
389
                    }
390
                }
391
                if (EndFinal != null)
392
                {
393
                    EndFinal(this, new EndFinalEventArgs
394
                    {
395
                        FinalPDFRemotePath = _FinalPDFStorgeRemote + @"\" + FinalPDFPath.Name,
396
                        OriginPDFName = OriginFileName,
397
                        FinalPDFPath = FinalPDFPath.FullName,
398
                        Error = "",
399
                        Message = "",
400
                        FinalPDF = FinalPDF,
401
                    });
402
                }
403
            }
404
            catch (Exception ex)
405
            {
406
                SetNotice(FinalPDF.ID, "MarkFinalPDF Error : " + ex.Message);
407
            }
408
        }
409
        #endregion
410

    
411
        #region PDF
412
        public static float scaleWidth { get; set; } = 0;
413
        public static float scaleHeight { get; set; } = 0;
414

    
415
        private string SetFlattingPDF(string tempFileInfo)
416
        {
417
            if (File.Exists(tempFileInfo))
418
            {
419
                FileInfo TestFile = new FileInfo(System.IO.Path.GetTempFileName());
420

    
421
                PdfReader pdfReader = new PdfReader(tempFileInfo);
422

    
423
                for (int i = 1; i <= pdfReader.NumberOfPages; i++)
424
                {
425
                    var mediaBox = pdfReader.GetPageSize(i);
426
                    var cropbox = pdfReader.GetCropBox(i);
427

    
428
                    //using (CIEntities _entity = new CIEntities(ConnectStringBuilder.ProjectCIConnectString().ToString()))
429
                    //{
430
                    //    _entity.DOCPAGE.Where(d=>d.DOCINFO_ID == DocInfoItem.DOCPAGE)
431
                    //}
432
                    var currentPage = DocPageItem.Find(d => d.PAGE_NUMBER == i);
433

    
434
                    //scaleWidth = float.Parse(currentPage.PAGE_WIDTH) / mediaBox.Width;
435
                    //scaleHeight = float.Parse(currentPage.PAGE_HEIGHT) / mediaBox.Height;
436
                    //scaleWidth = 2.0832634F;
437
                    //scaleHeight = 3.0F;
438

    
439
                    PdfRectangle rect = new PdfRectangle(cropbox, pdfReader.GetPageRotation(i));
440
                    //강인구 수정
441
                    //if (cropbox != null && (cropbox.Width < mediaBox.Width || cropbox.Height < cropbox.Height))
442
                    //if (cropbox != null && (cropbox.Width < mediaBox.Width || cropbox.Height < mediaBox.Height))
443
                    //{
444
                    //    var pageDict = pdfReader.GetPageN(i);
445
                    //    pageDict.Put(PdfName.MEDIABOX, rect);
446
                    //}
447
                }
448

    
449
                var memStream = new MemoryStream();
450
                var stamper = new PdfStamper(pdfReader, memStream)
451
                {
452
                    FormFlattening = true,                     
453
                    //FreeTextFlattening = true,
454
                    //AnnotationFlattening = true,                     
455
                };
456
                
457
                stamper.Close();
458
                pdfReader.Close();
459
                var array = memStream.ToArray();
460
                File.Delete(tempFileInfo);
461
                File.WriteAllBytes(TestFile.FullName, array);
462

    
463
                return TestFile.FullName;
464
            }
465
            else
466
            {
467
                return tempFileInfo;
468
            }
469
        }
470

    
471
        public void flattenPdfFile(string src, ref string dest)
472
        {
473
            PdfReader reader = new PdfReader(src);
474
            var memStream = new MemoryStream();
475
            var stamper = new PdfStamper(reader, memStream)
476
            {
477
                FormFlattening = true,
478
                FreeTextFlattening = true,
479
                AnnotationFlattening = true,
480
            };
481

    
482
            stamper.Close();
483
            var array = memStream.ToArray();
484
            File.WriteAllBytes(dest, array);
485
        }
486

    
487
        public void StatusChange(string message,int CurrentPage)
488
        {
489
            if(StatusChanged != null)
490
            {
491
                //var sb = new StringBuilder();
492
                //sb.AppendLine(message);
493

    
494
                StatusChanged(this, new StatusChangedEventArgs { CurrentPage = CurrentPage, Message = message });
495
            }
496
        }
497

    
498
        /// <summary>
499
        /// PDF에 Markup 데이터를 쓴다.
500
        /// </summary>
501
        /// <param name="finaldata"></param>
502
        /// <param name="testFile"></param>
503
        /// <param name="markupInfo"></param>
504
        /// <returns></returns>
505
        public bool SetStampInPDF(FINAL_PDF finaldata, string testFile, MARKUP_INFO markupInfo)
506
        {
507
            try
508
            {
509
                FileInfo tempFileInfo = new FileInfo(testFile);
510

    
511
                if (!Directory.Exists(_FinalPDFStorgeLocal))
512
                {
513
                    Directory.CreateDirectory(_FinalPDFStorgeLocal);
514
                }
515

    
516
                string pdfFilePath = Path.Combine(_FinalPDFStorgeLocal, tempFileInfo.Name);
517
          
518

    
519
                using (KCOMEntities _entity = new KCOMEntities(ConnectStringBuilder.KCOMConnectionString().ToString()))
520
                {
521
                    FINAL_PDF pdfLink = _entity.FINAL_PDF.Where(data => data.ID == finaldata.ID).FirstOrDefault();
522

    
523
                    #region 코멘트 적용 + 커버시트
524
                    using (Stream pdfStream = new FileInfo(testFile).Open(FileMode.Open, FileAccess.ReadWrite)) //
525
                    {
526
                        StatusChange("comment Cover",0);
527

    
528
                        using (PdfReader pdfReader = new PdfReader(pdfStream))
529
                        { 
530
                            //List<Dictionary<string, object>> lstoutlineTop = new List<Dictionary<string, object>>();
531
                            Dictionary<string, object> bookmark;
532
                            List<Dictionary<string, object>> outlines;
533

    
534
                            outlines = new List<Dictionary<string, object>>();
535
                            List<Dictionary<string, object>> root = new List<Dictionary<string, object>>();
536

    
537
                            var dic = new Dictionary<string, object>();
538

    
539
                            #region  북마크 생성
540
                            foreach (var data in MarkupDataSet)
541
                            {
542
                                //StatusChange("MarkupDataSet", 0);
543

    
544
                                string userid = data.MARKUP_INFO_VERSION.MARKUP_INFO.USER_ID;
545

    
546
                                string username = "";
547
                                string userdept = "";
548

    
549
                                using (CIEntities cIEntities = new CIEntities(KCOMDataModel.Common.ConnectStringBuilder.ProjectCIConnectString(finaldata.PROJECT_NO).ToString()))
550
                                {
551
                                    var memberlist = KCOMDataModel.Common.ObjectQuery.GetMemberQuery(cIEntities, userid);
552

    
553
                                    if(memberlist.Any())
554
                                    {
555
                                        username = memberlist[0].NAME;
556
                                        userdept = memberlist[0].DEPARTMENT;
557
                                    }
558
                                }
559

    
560
                                bookmark = new Dictionary<string, object>();
561
                                bookmark.Add("Title", string.Format("User:{0}[{1}] Commented Page : {2}", username, userdept, data.PAGENUMBER));
562
                                bookmark.Add("Page", data.PAGENUMBER + " Fit");
563
                                bookmark.Add("Action", "GoTo");
564
                                bookmark.Add("Kids", outlines);
565
                                root.Add(bookmark);
566
                            }
567
                            #endregion
568

    
569
                            iTextSharp.text.Version.GetInstance();
570

    
571
                            using (PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(pdfFilePath, FileMode.Create)))
572
                            {
573
                                try
574
                                {
575
                                    if (pdfStamper.AcroFields != null && pdfStamper.AcroFields.GenerateAppearances != true)
576
                                    {
577
                                        pdfStamper.AcroFields.GenerateAppearances = true;
578
                                    }
579
                                }
580
                                catch (Exception ex)
581
                                {
582
                                    SetNotice(FinalItem.ID, "this pdf is not AcroForm.");
583
                                }
584

    
585
                                #region Markup 색상을 설정한다.(DB에 값이 있으면 DB 값으로 설정한다.)
586
                                System.Drawing.Color _SetColor = System.Drawing.Color.FromArgb(255, System.Drawing.Color.Red);
587
                                #endregion
588

    
589
                                string[] delimiterChars = { "|DZ|" };
590
                                string[] delimiterChars2 = { "|" };
591

    
592
                                //pdfStamper.FormFlattening = true; //이미 선처리 작업함
593
                                pdfStamper.SetFullCompression();
594
                                _SetColor = System.Drawing.Color.FromArgb(255, System.Drawing.Color.Red);
595

    
596
                                StringBuilder strLog = new StringBuilder();
597
                                int lastPageNo = 0;
598

    
599
                                var groups = MarkupDataSet.GroupBy(x => x.PAGENUMBER);
600
                                foreach (var group in groups)
601
                                {
602
                                    int PageNumber = group.Key;
603
                                    #region ZIndex 값으로 정렬한다.
604
                                    var items = new List<Tuple<string, S_BaseControl>>();
605
                                    foreach (var item in group)
606
                                    {
607
                                        var tokens = item.DATA.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries).ToList();
608
                                        items.AddRange(tokens.ConvertAll(x =>
609
                                        {
610
                                            var str = JsonSerializerHelper.UnCompressString(x);
611
                                            var control = JsonSerializerHelper.JsonDeserialize<S_BaseControl>(str);
612
                                            return new Tuple<string, S_BaseControl>(str, control);
613
                                        }));
614
                                    }
615

    
616
                                    var zgroups = items.GroupBy(x => x.Item2.ZIndex).OrderBy(x => x.Key);
617
                                    #endregion
618

    
619
                                    foreach (var zgroup in zgroups)
620
                                    {
621
                                        var ordered = zgroup.OrderBy(x => x.Item2.Index);
622
                                        foreach (var order in ordered)
623
                                        {
624
                                            /// 2020.11.13 김태성
625
                                            /// 원본 PDF의 페이지수가 변경된 경우 이전 markup의 페이지를 찾지 못해 수정함.
626
                                            var pageitems = DocPageItem.Where(d => d.PAGE_NUMBER == PageNumber);
627
                                            if (pageitems.Any())
628
                                            {
629
                                                var currentPage = pageitems.First();
630
                                                pdfSize = pdfReader.GetPageSizeWithRotation(PageNumber);
631
                                                lastPageNo = PageNumber;
632

    
633
                                                iTextSharp.text.Rectangle mediaBox = pdfReader.GetPageSize(PageNumber);
634
                                                var cropBox = pdfReader.GetCropBox(PageNumber);
635

    
636
                                                /// media box와 crop box가 다를 경우 media box를 crop box와 일치시킨다
637
                                                if (cropBox != null &&
638
                                                    (cropBox.Left != mediaBox.Left || cropBox.Top != mediaBox.Top || cropBox.Right != mediaBox.Right || cropBox.Bottom != mediaBox.Bottom))
639
                                                {
640
                                                    PdfDictionary dict = pdfReader.GetPageN(PageNumber);
641

    
642
                                                    PdfArray oNewMediaBox = new PdfArray();
643
                                                    oNewMediaBox.Add(new PdfNumber(cropBox.Left));
644
                                                    oNewMediaBox.Add(new PdfNumber(cropBox.Top));
645
                                                    oNewMediaBox.Add(new PdfNumber(cropBox.Right));
646
                                                    oNewMediaBox.Add(new PdfNumber(cropBox.Bottom));
647
                                                    dict.Put(PdfName.MEDIABOX, oNewMediaBox);
648

    
649
                                                    pdfSize = cropBox;
650
                                                }
651

    
652
                                                scaleWidth = float.Parse(currentPage.PAGE_WIDTH) / pdfSize.Width;
653
                                                scaleHeight = float.Parse(currentPage.PAGE_HEIGHT) / pdfSize.Height;
654

    
655
                                                pdfLink.CURRENT_PAGE = PageNumber;
656
                                                _entity.SaveChanges();
657

    
658
                                                PdfContentByte contentByte = pdfStamper.GetOverContent(PageNumber);
659
                                                var item = order.Item1;
660
                                                var ControlT = order.Item2;
661

    
662
                                                try
663
                                                {
664
                                                    switch (ControlT.Name)
665
                                                    {
666
                                                        #region LINE
667
                                                        case "LineControl":
668
                                                            {
669
                                                                using (S_LineControl control = JsonSerializerHelper.JsonDeserialize<S_LineControl>(item))
670
                                                                {
671
                                                                    DrawLine(control, contentByte, delimiterChars, delimiterChars2, _SetColor);
672
                                                                }
673
                                                            }
674
                                                            break;
675
                                                        #endregion
676
                                                        #region ArrowControlMulti
677
                                                        case "ArrowControl_Multi":
678
                                                            {
679
                                                                using (S_ArrowControl_Multi control = JsonSerializerHelper.JsonDeserialize<S_ArrowControl_Multi>(item))
680
                                                                {
681
                                                                    DrawMultiArrowLine(control, contentByte, delimiterChars, delimiterChars2, _SetColor);
682
                                                                }
683
                                                            }
684
                                                            break;
685
                                                        #endregion
686
                                                        #region PolyControl
687
                                                        case "PolygonControl":
688
                                                            using (S_PolyControl control = JsonSerializerHelper.JsonDeserialize<S_PolyControl>(item))
689
                                                            {
690
                                                                string[] InnerData = control.SizeSet.Split(delimiterChars2, StringSplitOptions.RemoveEmptyEntries);
691
                                                                Point StartPoint = GetPdfPointSystem(control.StartPoint);
692
                                                                var PaintStyle = control.PaintState;
693
                                                                Point EndPoint = GetPdfPointSystem(control.EndPoint);
694
                                                                List<Point> PointSet = GetPdfPointSystem(control.PointSet);
695
                                                                double LineSize = Common.ConverterLineSize.Convert(Convert.ToInt32(InnerData.First()), scaleWidth);
696
                                                                double Opacity = control.Opac;
697
                                                                DoubleCollection DashSize = control.DashSize;
698

    
699
                                                                Controls_PDF.DrawSet_Shape.DrawPolygon(PointSet, LineSize, contentByte, DashSize, _SetColor, PaintStyle | PaintSet.Outline, Opacity);
700
                                                                //Controls_PDF.DrawSet_Line.DrawLine(PointSet, LineSize, contentByte, DashSize, _SetColor, Opacity);
701
                                                            }
702
                                                            break;
703
                                                        #endregion
704
                                                        #region ArcControl or ArrowArcControl
705
                                                        case "ArcControl":
706
                                                        case "ArrowArcControl":
707
                                                            {
708
                                                                using (S_ArcControl control = JsonSerializerHelper.JsonDeserialize<S_ArcControl>(item))
709
                                                                {
710
                                                                    string[] InnerData = control.SizeSet.Split(delimiterChars2, StringSplitOptions.RemoveEmptyEntries);
711
                                                                    Point StartPoint = GetPdfPointSystem(control.StartPoint);
712
                                                                    Point EndPoint = GetPdfPointSystem(control.EndPoint);
713
                                                                    Point MidPoint = GetPdfPointSystem(control.MidPoint);
714
                                                                    DoubleCollection DashSize = control.DashSize;
715
                                                                    List<Point> PointSet = GetPdfPointSystem(control.PointSet);
716

    
717
                                                                    var Opacity = control.Opac;
718
                                                                    string UserID = control.UserID;
719
                                                                    double LineSize = Common.ConverterLineSize.Convert(Convert.ToInt32(InnerData.First()), scaleWidth);
720
                                                                    bool IsTransOn = control.IsTransOn;
721

    
722
                                                                    if (control.IsTransOn)
723
                                                                    {
724
                                                                        Controls_PDF.DrawSet_Arrow.SingleAllow(MidPoint, StartPoint, (int)LineSize, contentByte, _SetColor, Opacity, true);
725
                                                                        Controls_PDF.DrawSet_Arrow.SingleAllow(MidPoint, EndPoint, (int)LineSize, contentByte, _SetColor, Opacity, true);
726
                                                                    }
727
                                                                    else
728
                                                                    {
729
                                                                        Controls_PDF.DrawSet_Arc.DrawArc(StartPoint, MidPoint, EndPoint, LineSize, contentByte, _SetColor, Opacity);
730
                                                                    }
731

    
732
                                                                    if (ControlT.Name == "ArrowArcControl")
733
                                                                    {
734
                                                                        Controls_PDF.DrawSet_Arrow.SingleAllow(StartPoint, MidPoint, LineSize, contentByte, _SetColor, Opacity);
735
                                                                        Controls_PDF.DrawSet_Arrow.SingleAllow(EndPoint, MidPoint, LineSize, contentByte, _SetColor, Opacity);
736
                                                                    }
737
                                                                }
738
                                                            }
739
                                                            break;
740
                                                        #endregion
741
                                                        #region RectangleControl
742
                                                        case "RectangleControl":
743
                                                            using (S_RectControl control = JsonSerializerHelper.JsonDeserialize<S_RectControl>(item))
744
                                                            {
745
                                                                string[] data2 = control.SizeSet.Split(delimiterChars2, StringSplitOptions.RemoveEmptyEntries);
746
                                                                double LineSize = Common.ConverterLineSize.Convert(Convert.ToInt32(data2.First()), scaleWidth);
747
                                                                var PaintStyle = control.PaintState;
748
                                                                double Angle = control.Angle;
749
                                                                DoubleCollection DashSize = control.DashSize;
750
                                                                double Opacity = control.Opac;
751
                                                                List<Point> PointSet = GetPdfPointSystem(control.PointSet);
752

    
753
                                                                Controls_PDF.DrawSet_Shape.DrawRectangle(PointSet, LineSize, contentByte, DashSize, _SetColor, PaintStyle, Opacity);
754
                                                            }
755
                                                            break;
756
                                                        #endregion
757
                                                        #region TriControl
758
                                                        case "TriControl":
759
                                                            using (S_TriControl control = JsonSerializerHelper.JsonDeserialize<S_TriControl>(item))
760
                                                            {
761
                                                                string[] data2 = control.SizeSet.Split(delimiterChars2, StringSplitOptions.RemoveEmptyEntries);
762
                                                                double LineSize = Common.ConverterLineSize.Convert(Convert.ToInt32(data2.First()), scaleWidth);
763
                                                                var PaintStyle = control.Paint;
764
                                                                double Angle = control.Angle;
765
                                                                //StrokeColor = _SetColor, //색상은 레드
766
                                                                DoubleCollection DashSize = control.DashSize;
767
                                                                double Opacity = control.Opac;
768
                                                                List<Point> PointSet = GetPdfPointSystem(control.PointSet);
769

    
770
                                                                Controls_PDF.DrawSet_Shape.DrawTriangle(PointSet, LineSize, contentByte, DashSize, _SetColor, PaintStyle | PaintSet.Outline, Opacity);
771
                                                            }
772
                                                            break;
773
                                                        #endregion
774
                                                        #region CircleControl
775
                                                        case "CircleControl":
776
                                                            using (S_CircleControl control = JsonSerializerHelper.JsonDeserialize<S_CircleControl>(item))
777
                                                            {
778
                                                                string[] data2 = control.SizeSet.Split(delimiterChars2, StringSplitOptions.RemoveEmptyEntries);
779
                                                                double LineSize = Common.ConverterLineSize.Convert(Convert.ToInt32(data2.First()), scaleWidth);
780
                                                                var StartPoint = GetPdfPointSystem(control.StartPoint);
781
                                                                var EndPoint = GetPdfPointSystem(control.EndPoint);
782
                                                                var PaintStyle = control.PaintState;
783
                                                                double Angle = control.Angle;
784
                                                                DoubleCollection DashSize = control.DashSize;
785
                                                                double Opacity = control.Opac;
786
                                                                List<Point> PointSet = GetPdfPointSystem(control.PointSet);
787
                                                                Controls_PDF.DrawSet_Shape.DrawCircle(StartPoint, EndPoint, LineSize, contentByte, DashSize, _SetColor, PaintStyle, Opacity, Angle, PointSet);
788

    
789
                                                            }
790
                                                            break;
791
                                                        #endregion
792
                                                        #region RectCloudControl
793
                                                        case "RectCloudControl":
794
                                                            using (S_RectCloudControl control = JsonSerializerHelper.JsonDeserialize<S_RectCloudControl>(item))
795
                                                            {
796
                                                                string[] data2 = control.SizeSet.Split(delimiterChars2, StringSplitOptions.RemoveEmptyEntries);
797
                                                                double LineSize = Common.ConverterLineSize.Convert(Convert.ToInt32(data2.First()), scaleWidth);
798
                                                                List<Point> PointSet = GetPdfPointSystem(control.PointSet);
799
                                                                double size = MathSet.DistanceTo(GetPdfPointSystem(control.StartPoint), GetPdfPointSystem(control.EndPoint));
800

    
801
                                                                double ArcLength = (control.ArcLength == 0 ? 10 : control.ArcLength) / (scaleWidth > scaleHeight ? scaleWidth : scaleHeight);
802

    
803
                                                                var PaintStyle = control.PaintState;
804
                                                                double Opacity = control.Opac;
805
                                                                DoubleCollection DashSize = control.DashSize;
806

    
807
                                                                //드로잉 방식이 표현되지 않음
808
                                                                var rotate = returnAngle(GetPdfPointSystem(control.StartPoint), GetPdfPointSystem(control.EndPoint));
809

    
810
                                                                double area = MathSet.AreaOf(GetPdfPointSystem(control.PointSet));
811
                                                                bool reverse = (area < 0);
812

    
813
                                                                Controls_PDF.DrawSet_Cloud.DrawCloudRect(PointSet, LineSize, (int)rotate, ArcLength, contentByte, control.DashSize, _SetColor, _SetColor, PaintStyle, Opacity);
814
                                                            }
815
                                                            break;
816
                                                        #endregion
817
                                                        #region CloudControl
818
                                                        case "CloudControl":
819
                                                            using (S_CloudControl control = JsonSerializerHelper.JsonDeserialize<S_CloudControl>(item))
820
                                                            {
821
                                                                string[] data2 = control.SizeSet.Split(delimiterChars2, StringSplitOptions.RemoveEmptyEntries);
822
                                                                double LineSize = Common.ConverterLineSize.Convert(Convert.ToInt32(data2.First()), scaleWidth);
823
                                                                double Toler = control.Toler;
824
                                                                List<Point> PointSet = GetPdfPointSystem(control.PointSet);
825
                                                                double ArcLength = (control.ArcLength == 0 ? 10 : control.ArcLength) / (scaleWidth > scaleHeight ? scaleWidth : scaleHeight);
826
                                                                var PaintStyle = control.PaintState;
827
                                                                double Opacity = control.Opac;
828
                                                                bool isTransOn = control.IsTrans;
829
                                                                bool isChain = control.IsChain;
830

    
831
                                                                DoubleCollection DashSize = control.DashSize;
832

    
833
                                                                if (isChain)
834
                                                                {
835
                                                                    Controls_PDF.DrawSet_Line.DrawLine(PointSet, LineSize, contentByte, DashSize, _SetColor, Opacity);
836
                                                                }
837
                                                                else
838
                                                                {
839
                                                                    if (isTransOn)
840
                                                                    {
841
                                                                        double area = MathSet.AreaOf(GetPdfPointSystem(control.PointSet));
842
                                                                        bool reverse = (area < 0);
843

    
844
                                                                        if (PaintStyle == PaintSet.None)
845
                                                                        {
846
                                                                            Controls_PDF.DrawSet_Cloud.DrawCloud(PointSet, LineSize, ArcLength, contentByte, control.DashSize, _SetColor, _SetColor, PaintStyle, Opacity);
847
                                                                        }
848
                                                                        else
849
                                                                        {
850
                                                                            Controls_PDF.DrawSet_Cloud.DrawCloud(PointSet, LineSize, ArcLength, contentByte, control.DashSize, _SetColor, _SetColor, PaintStyle, Opacity);
851
                                                                        }
852
                                                                    }
853
                                                                    else
854
                                                                    {
855
                                                                        Controls_PDF.DrawSet_Shape.DrawPolygon(PointSet, LineSize, contentByte, control.DashSize, _SetColor, PaintStyle, Opacity);
856
                                                                    }
857
                                                                }
858
                                                            }
859
                                                            break;
860
                                                        #endregion
861
                                                        #region TEXT
862
                                                        case "TextControl":
863
                                                            using (S_TextControl control = JsonSerializerHelper.JsonDeserialize<S_TextControl>(item))
864
                                                            {
865
                                                                DrawTextBox(control, contentByte, delimiterChars, delimiterChars2, _SetColor);
866
                                                            }
867
                                                            break;
868
                                                        #endregion
869
                                                        #region ArrowTextControl
870
                                                        case "ArrowTextControl":
871
                                                            using (S_ArrowTextControl control = JsonSerializerHelper.JsonDeserialize<S_ArrowTextControl>(item))
872
                                                            {
873
                                                                string[] data2 = control.SizeSet.Split(delimiterChars2, StringSplitOptions.RemoveEmptyEntries);
874
                                                                Point tempStartPoint = GetPdfPointSystem(control.StartPoint);
875
                                                                Point tempMidPoint = GetPdfPointSystem(control.MidPoint);
876
                                                                Point tempEndPoint = GetPdfPointSystem(control.EndPoint);
877
                                                                bool isUnderLine = false;
878
                                                                string Text = "";
879
                                                                double fontsize = 30;
880

    
881
                                                                System.Drawing.SizeF sizeF = new System.Drawing.SizeF((float)control.BoxWidth, (float)control.BoxHeight);
882
                                                                List<Point> Connections = new List<Point>(control.GetConnectionPoints(tempEndPoint, scaleWidth, scaleHeight));
883

    
884
                                                                double Angle = control.Angle;
885

    
886
                                                                var newStartPoint = tempStartPoint;
887
                                                                var ConnectionPoint = MathSet.getNearPoint(Connections, tempMidPoint);
888

    
889
                                                                double LineSize = Common.ConverterLineSize.Convert(Convert.ToInt32(data2[0]), scaleWidth);
890
                                                                System.Drawing.Color FontColor = _SetColor;
891
                                                                bool isHighlight = control.isHighLight;
892
                                                                double Opacity = control.Opac;
893
                                                                PaintSet Paint = PaintSet.None;
894

    
895
                                                                switch (control.ArrowStyle)
896
                                                                {
897
                                                                    case Controls.Text.ArrowTextControl.ArrowTextStyleSet.Normal:
898
                                                                        {
899
                                                                            Paint = PaintSet.None;
900
                                                                        }
901
                                                                        break;
902
                                                                    case Controls.Text.ArrowTextControl.ArrowTextStyleSet.Cloud:
903
                                                                        {
904
                                                                            Paint = PaintSet.Hatch;
905
                                                                        }
906
                                                                        break;
907
                                                                    case Controls.Text.ArrowTextControl.ArrowTextStyleSet.Rect:
908
                                                                        {
909
                                                                            Paint = PaintSet.Fill;
910
                                                                        }
911
                                                                        break;
912
                                                                    default:
913
                                                                        break;
914
                                                                }
915
                                                                if (control.isHighLight) Paint |= PaintSet.Highlight;
916

    
917
                                                                if (Paint == PaintSet.Hatch)
918
                                                                {
919
                                                                    Text = control.ArrowText;
920
                                                                }
921
                                                                else
922
                                                                {
923
                                                                    Text = control.ArrowText;
924
                                                                }
925

    
926
                                                                try
927
                                                                {
928
                                                                    if (control.fontConfig.Count == 4)
929
                                                                    {
930
                                                                        fontsize = Convert.ToDouble(control.fontConfig[3]);
931
                                                                    }
932

    
933
                                                                    //강인구 수정(2018.04.17)
934
                                                                    var TextStyle = Common.StringToFont.ConFontStyle(control.fontConfig[1]);
935

    
936
                                                                    FontStyle fontStyle = FontStyles.Normal;
937
                                                                    if (FontStyles.Italic == TextStyle)
938
                                                                    {
939
                                                                        fontStyle = FontStyles.Italic;
940
                                                                    }
941

    
942
                                                                    FontWeight fontWeight = FontWeights.Black;
943

    
944
                                                                    var TextWeight = Common.StringToFont.ConFontWeight(control.fontConfig[2]);
945
                                                                    if (FontWeights.Bold == TextWeight)
946
                                                                    {
947
                                                                        fontWeight = FontWeights.Bold;
948
                                                                    }
949

    
950
                                                                    TextDecorationCollection decoration = TextDecorations.Baseline;
951
                                                                    if (control.fontConfig.Count == 5)
952
                                                                    {
953
                                                                        decoration = TextDecorations.Underline;
954
                                                                    }
955

    
956
                                                                    if (control.isTrans)
957
                                                                    {
958
                                                                        var border = control.GetBorderRectangle(tempEndPoint, scaleWidth, scaleHeight);
959
                                                                        Controls_PDF.DrawSet_Text.DrawString_ArrowText(border,
960
                                                                        newStartPoint, tempMidPoint, ConnectionPoint, control.isFixed,
961
                                                                        LineSize, contentByte, _SetColor, Paint, fontsize, isHighlight, FontHelper.GetFontFamily(control.fontConfig[0]), fontStyle, fontWeight, decoration, Text, sizeF, Opacity, Angle);
962
                                                                    }
963
                                                                    else
964
                                                                    {
965
                                                                        if (control.isFixed)
966
                                                                        {
967
                                                                            var testP = new Point(0, 0);
968
                                                                            if (control.isFixed)
969
                                                                            {
970
                                                                                if (Connections[1] == ConnectionPoint)
971
                                                                                {
972
                                                                                    testP = new Point(ConnectionPoint.X, ConnectionPoint.Y - 10);
973
                                                                                }
974
                                                                                else if (Connections[3] == ConnectionPoint)
975
                                                                                {
976
                                                                                    testP = new Point(ConnectionPoint.X, ConnectionPoint.Y + 10);
977
                                                                                }
978
                                                                                else if (Connections[0] == ConnectionPoint)
979
                                                                                {
980
                                                                                    testP = new Point(ConnectionPoint.X - 10, ConnectionPoint.Y);
981
                                                                                }
982
                                                                                else if (Connections[2] == ConnectionPoint)
983
                                                                                {
984
                                                                                    testP = new Point(ConnectionPoint.X + 10, ConnectionPoint.Y);
985
                                                                                }
986
                                                                            }
987

    
988
                                                                            var border = control.GetBorderRectangle(tempEndPoint, scaleWidth, scaleHeight);
989
                                                                            Controls_PDF.DrawSet_Text.DrawString_ArrowText(border,
990
                                                                                tempStartPoint, testP, ConnectionPoint, control.isFixed,
991
                                                                                LineSize, contentByte, _SetColor, Paint, fontsize, isHighlight,
992
                                                                            FontHelper.GetFontFamily(control.fontConfig[0]), fontStyle, fontWeight, decoration, Text, sizeF, Opacity, Angle);
993
                                                                        }
994
                                                                        else
995
                                                                        {
996
                                                                            var border = control.GetBorderRectangle(tempEndPoint, scaleWidth, scaleHeight);
997
                                                                            Controls_PDF.DrawSet_Text.DrawString_ArrowText(border,
998
                                                                                newStartPoint, tempMidPoint, ConnectionPoint, control.isFixed,
999
                                                                                LineSize, contentByte, _SetColor, Paint, fontsize, isHighlight, FontHelper.GetFontFamily(control.fontConfig[0]), fontStyle, fontWeight, decoration, Text, sizeF, Opacity, Angle);
1000
                                                                        }
1001
                                                                    }
1002
                                                                }
1003
                                                                catch (Exception ex)
1004
                                                                {
1005
                                                                    throw ex;
1006
                                                                }
1007
                                                            }
1008
                                                            break;
1009
                                                        #endregion
1010
                                                        #region SignControl
1011
                                                        case "SignControl":
1012
                                                            using (S_SignControl control = JsonSerializerHelper.JsonDeserialize<S_SignControl>(item))
1013
                                                            {
1014

    
1015
                                                                double Angle = control.Angle;
1016
                                                                Point StartPoint = GetPdfPointSystem(control.StartPoint);
1017
                                                                Point TopRightPoint = GetPdfPointSystem(control.TR);
1018
                                                                Point EndPoint = GetPdfPointSystem(control.EndPoint);
1019
                                                                Point LeftBottomPoint = GetPdfPointSystem(control.LB);
1020
                                                                List<Point> PointSet = GetPdfPointSystem(control.PointSet);
1021
                                                                double Opacity = control.Opac;
1022
                                                                string UserNumber = control.UserNumber;
1023
                                                                Controls_PDF.DrawSet_Image.DrawSign(StartPoint, EndPoint, PointSet, contentByte, UserNumber, Angle, Opacity, finaldata.PROJECT_NO);
1024
                                                            }
1025
                                                            break;
1026
                                                        #endregion
1027
                                                        #region MyRegion
1028
                                                        case "DateControl":
1029
                                                            using (S_DateControl control = JsonSerializerHelper.JsonDeserialize<S_DateControl>(item))
1030
                                                            {
1031
                                                                string[] data2 = control.SizeSet.Split(delimiterChars2, StringSplitOptions.RemoveEmptyEntries);
1032
                                                                string Text = control.Text;
1033
                                                                Point StartPoint = GetPdfPointSystem(control.StartPoint);
1034
                                                                Point EndPoint = GetPdfPointSystem(control.EndPoint);
1035
                                                                List<Point> pointSet = GetPdfPointSystem(control.PointSet);
1036
                                                                System.Drawing.Color FontColor = _SetColor;
1037
                                                                double Angle = control.Angle;
1038
                                                                double Opacity = control.Opac;
1039
                                                                Controls_PDF.PDFLib_DrawSet_Text.DrawDate(StartPoint, EndPoint, pointSet, contentByte, _SetColor, Text, Angle, Opacity);
1040
                                                            }
1041
                                                            break;
1042
                                                        #endregion
1043
                                                        #region SymControlN (APPROVED)
1044
                                                        case "SymControlN":
1045
                                                            using (S_SymControl control = JsonSerializerHelper.JsonDeserialize<S_SymControl>(item))
1046
                                                            {
1047
                                                                Point StartPoint = GetPdfPointSystem(control.StartPoint);
1048
                                                                Point EndPoint = GetPdfPointSystem(control.EndPoint);
1049
                                                                List<Point> pointSet = GetPdfPointSystem(control.PointSet);
1050
                                                                System.Drawing.Color FontColor = _SetColor;
1051
                                                                double Angle = control.Angle;
1052
                                                                double Opacity = control.Opac;
1053

    
1054
                                                                var stamp = _entity.PROPERTIES.Where(x => x.TYPE == "STAMP");
1055

    
1056
                                                                if (stamp.Count() > 0)
1057
                                                                {
1058
                                                                    var xamldata = Serialize.Core.JsonSerializerHelper.UnCompressString_NonPrefix(stamp.First().VALUE);
1059

    
1060
                                                                    var Contents = _entity.PROPERTIES.Where(x => x.TYPE == "STAMP_CONTENTS");
1061

    
1062
                                                                    if (Contents?.Count() > 0)
1063
                                                                    {
1064
                                                                        foreach (var content in Contents)
1065
                                                                        {
1066
                                                                            xamldata = xamldata.Replace(content.PROPERTY, System.Security.SecurityElement.Escape(content.VALUE));
1067
                                                                        }
1068
                                                                    }
1069

    
1070
                                                                    Controls_PDF.PDFLib_DrawSet_Symbol.DrawApprovalXamlData(StartPoint, EndPoint, pointSet, contentByte, _SetColor, Angle, Opacity, xamldata);
1071
                                                                }
1072

    
1073
                                                                string imgpath = CommonLib.Common.GetConfigString("ApprovedImgPath", "URL", "");
1074

    
1075
                                                            }
1076
                                                            break;
1077
                                                        case "SymControl":
1078
                                                            using (S_SymControl control = JsonSerializerHelper.JsonDeserialize<S_SymControl>(item))
1079
                                                            {
1080
                                                                Point StartPoint = GetPdfPointSystem(control.StartPoint);
1081
                                                                Point EndPoint = GetPdfPointSystem(control.EndPoint);
1082
                                                                List<Point> pointSet = GetPdfPointSystem(control.PointSet);
1083
                                                                System.Drawing.Color FontColor = _SetColor;
1084
                                                                double Angle = control.Angle;
1085
                                                                double Opacity = control.Opac;
1086

    
1087
                                                                string imgpath = CommonLib.Common.GetConfigString("CheckmarkImgPath", "URL", "");
1088
                                                                Controls_PDF.PDFLib_DrawSet_Symbol.DrawCheckMark(StartPoint, EndPoint, pointSet, contentByte, _SetColor, Angle, Opacity, imgpath);
1089
                                                            }
1090
                                                            break;
1091
                                                        #endregion
1092
                                                        #region Image
1093
                                                        case "ImgControl":
1094
                                                            using (S_ImgControl control = JsonSerializerHelper.JsonDeserialize<S_ImgControl>(item))
1095
                                                            {
1096
                                                                double Angle = control.Angle;
1097
                                                                Point StartPoint = GetPdfPointSystem(control.StartPoint);
1098
                                                                Point TopRightPoint = GetPdfPointSystem(control.TR);
1099
                                                                Point EndPoint = GetPdfPointSystem(control.EndPoint);
1100
                                                                Point LeftBottomPoint = GetPdfPointSystem(control.LB);
1101
                                                                List<Point> PointSet = GetPdfPointSystem(control.PointSet);
1102
                                                                double Opacity = control.Opac;
1103
                                                                string FilePath = control.ImagePath;
1104
                                                                //Uri uri = new Uri(s.ImagePath);
1105

    
1106
                                                                Controls_PDF.DrawSet_Image.DrawImage(StartPoint, EndPoint, PointSet, contentByte, FilePath, Angle, Opacity);
1107
                                                            }
1108
                                                            break;
1109
                                                        #endregion
1110
                                                        default:
1111
                                                            StatusChange($"{ControlT.Name} Not Support", 0);
1112
                                                            break;
1113
                                                    }
1114

    
1115
                                                }
1116
                                                catch (Exception ex)
1117
                                                {
1118
                                                    StatusChange($"markupItem : {ControlT.Name}" + ex.ToString(), 0);
1119
                                                }
1120
                                                finally
1121
                                                {
1122
                                                }
1123
                                            }
1124
                                        }
1125
                                    }
1126
                                }
1127

    
1128
                                if (StatusChanged != null)
1129
                                {
1130
                                    StatusChanged(this, new StatusChangedEventArgs { CurrentPage = lastPageNo, Message = "" });
1131
                                }
1132
                                //PdfFileSpecification pfs = PdfFileSpecification.FileEmbedded(pdfStamper.Writer, @"C:\Users\kts\Documents\업무\CARS\엑셀양식\F-000-5378-702_R2_계장 Cable Schedule Sample.xlsx", "F-000-5378-702_R2_계장 Cable Schedule Sample.xlsx", null);
1133
                                //pdfStamper.AddFileAttachment("F-000-5378-702_R2_계장 Cable Schedule Sample.xlsx", pfs);
1134

    
1135
                                pdfStamper.Outlines = root;
1136
                                pdfStamper.Close();
1137
                                pdfReader.Close();
1138
                            }
1139
                        }
1140
                    }
1141
                    #endregion
1142
                }
1143

    
1144
                if (tempFileInfo.Exists)
1145
                {
1146
#if !DEBUG
1147
                    tempFileInfo.Delete();
1148
#endif
1149
                }
1150

    
1151
                if (File.Exists(pdfFilePath))
1152
                {
1153
                    string destfilepath = null;
1154
                    try
1155
                    {
1156
                        FinalPDFPath = new FileInfo(pdfFilePath);
1157

    
1158
                        /// 정리 필요함. DB로 변경
1159
                        string pdfmovepath = CommonLib.Common.GetConfigString("PDFMovePath", "URL", "");
1160

    
1161
                        if(!string.IsNullOrEmpty(pdfmovepath))
1162
                        {
1163
                            _FinalPDFStorgeLocal = pdfmovepath;
1164
                        }
1165

    
1166
                        destfilepath = Path.Combine(_FinalPDFStorgeLocal, FinalPDFPath.Name.Replace(".tmp", ".pdf"));
1167

    
1168
                        if (File.Exists(destfilepath))
1169
                            File.Delete(destfilepath);
1170

    
1171
                        File.Move(FinalPDFPath.FullName, destfilepath);
1172
                        FinalPDFPath = new FileInfo(destfilepath);
1173
                        File.Delete(pdfFilePath);
1174
                    }
1175
                    catch (Exception ex)
1176
                    {
1177
                        SetNotice(finaldata.ID, $"File move error - Source File : {FinalPDFPath.FullName} dest File : {destfilepath}" + ex.ToString());
1178
                    }
1179

    
1180
                    return true;
1181
                }
1182
            }
1183
            catch (Exception ex)
1184
            {
1185
                SetNotice(finaldata.ID, "SetStempinPDF error: " + ex.ToString());
1186
            }
1187
            return false;
1188
        }
1189

    
1190
        /// <summary>
1191
        /// kcom의 화살표방향과 틀려 추가함
1192
        /// </summary>
1193
        /// <param name="PageAngle"></param>
1194
        /// <param name="endP"></param>
1195
        /// <param name="ps">box Points</param>
1196
        /// <param name="IsFixed"></param>
1197
        /// <returns></returns>
1198
        private Point GetArrowTextControlTestPoint(double PageAngle,Point endP,List<Point> ps,bool IsFixed)
1199
        {
1200
            Point testP = endP;
1201

    
1202
            try
1203
            {
1204
                switch (Math.Abs(PageAngle).ToString())
1205
                {
1206
                    case "90":
1207
                        testP = new Point(endP.X + 50, endP.Y);
1208
                        break;
1209
                    case "270":
1210
                        testP = new Point(endP.X - 50, endP.Y);
1211
                        break;
1212
                }
1213

    
1214
                //20180910 LJY 각도에 따라.
1215
                switch (Math.Abs(PageAngle).ToString())
1216
                {
1217
                    case "90":
1218
                        if (IsFixed)
1219
                        {
1220
                            if (ps[0] == endP) //상단
1221
                            {
1222
                                testP = new Point(endP.X, endP.Y + 50);
1223
                                //System.Diagnostics.Debug.WriteLine("상단"+ testP);
1224
                            }
1225
                            else if (ps[1] == endP) //하단
1226
                            {
1227
                                testP = new Point(endP.X, endP.Y - 50);
1228
                                //System.Diagnostics.Debug.WriteLine("하단"+ testP);
1229
                            }
1230
                            else if (ps[2] == endP) //좌단
1231
                            {
1232
                                testP = new Point(endP.X - 50, endP.Y);
1233
                                //System.Diagnostics.Debug.WriteLine("좌단"+ testP);
1234
                            }
1235
                            else if (ps[3] == endP) //우단
1236
                            {
1237
                                testP = new Point(endP.X + 50, endP.Y);
1238
                                //System.Diagnostics.Debug.WriteLine("우단"+ testP);
1239
                            }
1240
                        }
1241
                        break;
1242
                    case "270":
1243
                        if (IsFixed)
1244
                        {
1245
                            if (ps[0] == endP) //상단
1246
                            {
1247
                                testP = new Point(endP.X, endP.Y - 50);
1248
                                //System.Diagnostics.Debug.WriteLine("상단" + testP);
1249
                            }
1250
                            else if (ps[1] == endP) //하단
1251
                            {
1252
                                testP = new Point(endP.X, endP.Y + 50);
1253
                                //System.Diagnostics.Debug.WriteLine("하단" + testP);
1254
                            }
1255
                            else if (ps[2] == endP) //좌단
1256
                            {
1257
                                testP = new Point(endP.X + 50, endP.Y);
1258
                                //System.Diagnostics.Debug.WriteLine("좌단" + testP);
1259
                            }
1260
                            else if (ps[3] == endP) //우단
1261
                            {
1262
                                testP = new Point(endP.X - 50, endP.Y);
1263
                                //System.Diagnostics.Debug.WriteLine("우단" + testP);
1264
                            }
1265
                        }
1266
                        break;
1267
                    default:
1268
                        if (IsFixed)
1269
                        {
1270

    
1271
                            if (ps[0] == endP) //상단
1272
                            {
1273
                                testP = new Point(endP.X, endP.Y - 50);
1274
                                //System.Diagnostics.Debug.WriteLine("상단");
1275
                            }
1276
                            else if (ps[1] == endP) //하단
1277
                            {
1278
                                testP = new Point(endP.X, endP.Y + 50);
1279
                                //System.Diagnostics.Debug.WriteLine("하단");
1280
                            }
1281
                            else if (ps[2] == endP) //좌단
1282
                            {
1283
                                testP = new Point(endP.X - 50, endP.Y);
1284
                                //System.Diagnostics.Debug.WriteLine("좌단");
1285
                            }
1286
                            else if (ps[3] == endP) //우단
1287
                            {
1288
                                testP = new Point(endP.X + 50, endP.Y);
1289
                                //System.Diagnostics.Debug.WriteLine("우단");
1290
                            }
1291
                        }
1292
                        break;
1293
                }
1294

    
1295
            }
1296
            catch (Exception)
1297
            {
1298
            }
1299

    
1300
            return testP;
1301
        }
1302

    
1303
        private Point Test(Rect rect,Point point)
1304
        {
1305
            Point result = new Point();
1306

    
1307
            Point newPoint = new Point();
1308

    
1309
            double oldNear = 0;
1310
            double newNear = 0;
1311

    
1312
            oldNear = MathSet.GetShortestDistance(point, rect.TopLeft, rect.TopRight, out result);
1313

    
1314
            newNear = MathSet.GetShortestDistance(point, rect.TopLeft, rect.BottomLeft, out newPoint);
1315

    
1316
            if (newNear < oldNear)
1317
            {
1318
                oldNear = newNear;
1319
                result = newPoint;
1320
            }
1321

    
1322
            newNear = MathSet.GetShortestDistance(point, rect.TopRight, rect.BottomRight, out newPoint);
1323

    
1324
            if (newNear < oldNear)
1325
            {
1326
                oldNear = newNear;
1327
                result = newPoint;
1328
            }
1329

    
1330

    
1331
            newNear = MathSet.GetShortestDistance(point, rect.BottomLeft, rect.BottomRight, out newPoint);
1332

    
1333
            if (newNear < oldNear)
1334
            {
1335
                oldNear = newNear;
1336
                result = newPoint;
1337
            }
1338

    
1339
            return result;
1340
        }
1341

    
1342
        private void DrawMultiArrowLine(S_ArrowControl_Multi control, PdfContentByte contentByte, string[] delimiterChars, string[] delimiterChars2, System.Drawing.Color setColor)
1343
        {
1344
            string[] InnerData = control.SizeSet.Split(delimiterChars2, StringSplitOptions.RemoveEmptyEntries);
1345
            Point StartPoint = GetPdfPointSystem(control.StartPoint);
1346
            Point MidPoint = GetPdfPointSystem(control.MidPoint);
1347
            Point EndPoint = GetPdfPointSystem(control.EndPoint);
1348
            DoubleCollection DashSize = control.DashSize;
1349
            List<Point> PointSet = GetPdfPointSystem(control.PointSet);
1350
            double LineSize = Common.ConverterLineSize.Convert(Convert.ToInt32(InnerData.First()), scaleWidth);
1351

    
1352
            double Opacity = control.Opac;
1353

    
1354
            if (EndPoint == MidPoint)
1355
            {
1356
                Controls_PDF.DrawSet_Arrow.SingleAllow(MidPoint, StartPoint, LineSize, contentByte, setColor, Opacity);
1357
            }
1358
            else
1359
            {
1360
                Controls_PDF.DrawSet_Arrow.SingleAllow(EndPoint, MidPoint, LineSize, contentByte, setColor, Opacity);
1361
            }
1362

    
1363
            Controls_PDF.DrawSet_Line.DrawLine(PointSet, LineSize, contentByte, DashSize, setColor, Opacity);
1364

    
1365
        }
1366

    
1367
        private void DrawLine(S_LineControl control, PdfContentByte contentByte, string[] delimiterChars, string[] delimiterChars2, System.Drawing.Color setColor)
1368
        {
1369
            string[] InnerData = control.SizeSet.Split(delimiterChars2, StringSplitOptions.RemoveEmptyEntries);
1370
            Point StartPoint = GetPdfPointSystem(control.StartPoint);
1371
            Point EndPoint = GetPdfPointSystem(control.EndPoint);
1372
            DoubleCollection DashSize = control.DashSize;
1373
            List<Point> PointSet = GetPdfPointSystem(control.PointSet);
1374

    
1375
            var Opacity = control.Opac;
1376
            string UserID = control.UserID;
1377
            double Interval = control.Interval;
1378
            double LineSize = Common.ConverterLineSize.Convert(Convert.ToInt32(InnerData.First()), scaleWidth);
1379
            Controls_PDF.DrawSet_Line.DrawLine(StartPoint, EndPoint, LineSize, contentByte, control.DashSize, setColor, Opacity);
1380
            switch (control.LineStyleSet)
1381
            {
1382
                case LineStyleSet.ArrowLine:
1383
                    Controls_PDF.DrawSet_Arrow.SingleAllow(EndPoint, StartPoint, LineSize, contentByte, setColor, Opacity);
1384
                    break;
1385
                case LineStyleSet.CancelLine:
1386
                    {
1387
                        var x = Math.Abs((Math.Abs(control.StartPoint.X) - Math.Abs(control.EndPoint.X)));
1388
                        var y = Math.Abs((Math.Abs(control.StartPoint.Y) - Math.Abs(control.EndPoint.Y)));
1389

    
1390
                        Point newStartPoint = new Point();
1391
                        Point newEndPoint = new Point();
1392

    
1393
                        if (x > y)
1394
                        {
1395
                            newStartPoint = new Point(control.StartPoint.X, control.StartPoint.Y + control.Interval);
1396
                            newEndPoint = new Point(control.EndPoint.X, control.EndPoint.Y + control.Interval);
1397
                        }
1398
                        else
1399
                        {
1400
                            newStartPoint = new Point(control.StartPoint.X + control.Interval, control.StartPoint.Y);
1401
                            newEndPoint = new Point(control.EndPoint.X + control.Interval, control.EndPoint.Y);
1402
                        }
1403

    
1404
                        newStartPoint = GetPdfPointSystem(newStartPoint);
1405
                        newEndPoint = GetPdfPointSystem(newEndPoint);
1406

    
1407
                        Controls_PDF.DrawSet_Line.DrawLine(newStartPoint, newEndPoint, LineSize, contentByte, DashSize, setColor, Opacity);
1408
                    }
1409
                    break;
1410
                case LineStyleSet.TwinLine:
1411
                    {
1412
                        Controls_PDF.DrawSet_Arrow.SingleAllow(EndPoint, StartPoint, LineSize, contentByte, setColor, Opacity);
1413
                        Controls_PDF.DrawSet_Arrow.SingleAllow(StartPoint, EndPoint, LineSize, contentByte, setColor, Opacity);
1414
                    }
1415
                    break;
1416
                case LineStyleSet.DimLine:
1417
                    {
1418
                        Controls_PDF.DrawSet_Arrow.DimAllow(StartPoint, EndPoint, LineSize, contentByte, setColor, Opacity);
1419
                        Controls_PDF.DrawSet_Arrow.SingleAllow(EndPoint, StartPoint, LineSize, contentByte, setColor, Opacity);
1420
                        Controls_PDF.DrawSet_Arrow.SingleAllow(StartPoint, EndPoint, LineSize, contentByte, setColor, Opacity);
1421
                    }
1422
                    break;
1423
                default:
1424
                    break;
1425
            }
1426

    
1427
        }
1428

    
1429
        private void DrawTextBox(S_TextControl control,PdfContentByte contentByte, string[] delimiterChars, string[] delimiterChars2,System.Drawing.Color setColor)
1430
        {
1431
            string[] data2 = control.SizeSet.Split(delimiterChars2, StringSplitOptions.RemoveEmptyEntries);
1432
            string Text = control.Text;
1433

    
1434
            bool isUnderline = false;
1435
            control.BoxW -= scaleWidth;
1436
            control.BoxH -= scaleHeight;
1437
            System.Drawing.SizeF sizeF = new System.Drawing.SizeF((float)control.BoxW, (float)control.BoxH);
1438
            Point StartPoint = GetPdfPointSystem(control.StartPoint);
1439
            Point EndPoint = GetPdfPointSystem(new Point(control.StartPoint.X + control.BoxW, control.StartPoint.Y + control.BoxH));
1440

    
1441
            List<Point> pointSet = new List<Point>();
1442
            pointSet.Add(StartPoint);
1443
            pointSet.Add(EndPoint);
1444
            
1445
            PaintSet paint = PaintSet.None;
1446
            switch (control.paintMethod)
1447
            {
1448
                case 1:
1449
                    {
1450
                        paint = PaintSet.Fill;
1451
                    }
1452
                    break;
1453
                case 2:
1454
                    {
1455
                        paint = PaintSet.Hatch;
1456
                    }
1457
                    break;
1458
                default:
1459
                    break;
1460
            }
1461
            if (control.isHighLight) paint |= PaintSet.Highlight;
1462

    
1463
            double LineSize = Common.ConverterLineSize.Convert(Convert.ToInt32(data2.First()), scaleWidth);
1464
            double TextSize = Convert.ToDouble(data2[1]);
1465
            System.Drawing.Color FontColor = setColor;
1466
            double Angle = control.Angle;
1467
            double Opacity = control.Opac;
1468
            FontFamily fontfamilly = FontHelper.GetFontFamily(control.fontConfig[0]);
1469
            var TextStyle = Common.StringToFont.ConFontStyle(control.fontConfig[1]);
1470

    
1471
            FontStyle fontStyle = FontStyles.Normal;
1472
            if (FontStyles.Italic == TextStyle)
1473
            {
1474
                fontStyle = FontStyles.Italic;
1475
            }
1476

    
1477
            FontWeight fontWeight = FontWeights.Black;
1478

    
1479
            var TextWeight = Common.StringToFont.ConFontWeight(control.fontConfig[2]);
1480
            //강인구 수정(2018.04.17)
1481
            if (FontWeights.Bold == TextWeight)
1482
            //if (FontWeights.ExtraBold == TextWeight)
1483
            {
1484
                fontWeight = FontWeights.Bold;
1485
            }
1486

    
1487
            TextDecorationCollection decoration = TextDecorations.Baseline;
1488
            if (control.fontConfig.Count() == 4)
1489
            {
1490
                decoration = TextDecorations.Underline;
1491
            }
1492

    
1493
            Controls_PDF.DrawSet_Text.DrawString(StartPoint, EndPoint, LineSize, contentByte, setColor, paint, TextSize, fontfamilly, fontStyle, fontWeight, decoration, Text, sizeF, Opacity, Angle);
1494
        }
1495
    
1496

    
1497
        ~MarkupToPDF()
1498
        {
1499
            this.Dispose(false);
1500
        }
1501

    
1502
        private bool disposed;
1503

    
1504
        public void Dispose()
1505
        {
1506
            this.Dispose(true);
1507
            GC.SuppressFinalize(this);
1508
        }
1509

    
1510
        protected virtual void Dispose(bool disposing)
1511
        {
1512
            if (this.disposed) return;
1513
            if (disposing)
1514
            {
1515
                // IDisposable 인터페이스를 구현하는 멤버들을 여기서 정리합니다.
1516
            }
1517
            // .NET Framework에 의하여 관리되지 않는 외부 리소스들을 여기서 정리합니다.
1518
            this.disposed = true;
1519
        }
1520

    
1521
#endregion
1522
    }
1523
}
클립보드 이미지 추가 (최대 크기: 500 MB)