Пример #1
0
        public ActionResult Aircrafts()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return(Redirect("/Account/Login"));
            }
            IEnumerable <Base> bases = db.Bases;

            using (MemoryStream ms = new MemoryStream())
            {
                DocX document = DocX.Create(ms);
                document.SetDefaultFont(new Xceed.Document.NET.Font("Times New Roman"), 12);
                document.MarginLeft   = 85;
                document.MarginTop    = 56.7f;
                document.MarginBottom = 56.7f;
                document.MarginRight  = 42.5f;

                document.InsertParagraph("Розподілення яхт за портами\n").Bold().Alignment = Alignment.center;
                foreach (Base airbase in bases)
                {
                    IEnumerable <Aircraft> aircrafts = db.Aircrafts.Include(m => m.Base).Where(m => m.BaseId == airbase.Id);
                    if (aircrafts.Count() == 0)
                    {
                        continue;
                    }
                    document.InsertParagraph($"Індекс: {airbase.PostIndex}").Alignment = Alignment.center;
                    document.InsertParagraph($"Місто: {airbase.City}").Alignment       = Alignment.center;
                    document.InsertParagraph($"Адреса: {airbase.Adress}").Alignment    = Alignment.center;
                    Table table = document.AddTable(aircrafts.Count() + 1, 6);
                    table.Alignment = Alignment.center;
                    table.Design    = TableDesign.TableGrid;
                    string[] names = { "Реєстраційний номер", "Виробник", "Модель", "Клас", "Рік виробництва", "Статус" };
                    for (int k = 0; k < names.Length; ++k)
                    {
                        table.Rows[0].Cells[k].Paragraphs[0].Append(names[k]).Bold().Alignment = Alignment.center;
                    }
                    int j = 0;
                    foreach (Aircraft aircraft in aircrafts)
                    {
                        table.Rows[j + 1].Cells[0].Paragraphs[0].Append(aircraft.RegistrationNumber).Alignment = Alignment.center;
                        table.Rows[j + 1].Cells[1].Paragraphs[0].Append(aircraft.Manufacturer).Alignment       = Alignment.center;
                        table.Rows[j + 1].Cells[2].Paragraphs[0].Append(aircraft.Model).Alignment = Alignment.center;
                        table.Rows[j + 1].Cells[3].Paragraphs[0].Append(aircraft.Class).Alignment = Alignment.center;
                        table.Rows[j + 1].Cells[4].Paragraphs[0].Append(aircraft.YearOfProduction.ToString()).Alignment = Alignment.center;
                        table.Rows[j + 1].Cells[5].Paragraphs[0].Append(aircraft.Status).Alignment = Alignment.center;
                        j++;
                    }
                    document.InsertParagraph().InsertTableAfterSelf(table);
                    document.InsertParagraph();
                }
                document.InsertParagraph($"\n\n\n Дата формування: {DateTime.Now}").Alignment = Alignment.right;
                document.Save();

                Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                Response.AddHeader("content-disposition",
                                   "attachment;filename=Aircrafts.docx");
                Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
            }
            return(null);
        }
Пример #2
0
        public string getReport(int candidateId, string candidateName, string templateName, IList <Question> questions)
        {
            string fileName = $"{Path.GetTempPath()}\\Candidate {candidateId}.docx";

            using (DocX document = DocX.Create(fileName))
            {
                document.SetDefaultFont(new Font("Arial"));

                // Generate the Headers/Footers for this document
                document.AddHeaders();
                document.AddFooters();
                // Insert a Paragraph in the Headers/Footers
                string  headerImagePath = "./Images/Header.jpg";
                Image   headerImage     = document.AddImage(headerImagePath);
                Picture headerPicture   = headerImage.CreatePicture();

                string  FooterImagePath = "./Images/Footer.jpg";
                Image   footerImage     = document.AddImage(FooterImagePath);
                Picture footerPicture   = footerImage.CreatePicture();

                document.Headers.Even.InsertParagraph(candidateName);
                document.Headers.Even.InsertParagraph(templateName);
                var p = document.Headers.Even.InsertParagraph();
                p.AppendPicture(headerPicture);
                p.Alignment = Alignment.right;
                document.Headers.Odd.InsertParagraph(candidateName);
                document.Headers.Odd.InsertParagraph(templateName);
                p = document.Headers.Odd.InsertParagraph();
                p.AppendPicture(headerPicture);
                p.Alignment = Alignment.right;

                p = document.Footers.Even.InsertParagraph();
                footerPicture.Width  = footerPicture.Width * .7f;
                footerPicture.Height = footerPicture.Height * .7f;
                p.AppendPicture(footerPicture);
                document.Footers.Even.InsertParagraph("1 university ave, 3rd floor, toronto, ontario  canada m5j 2p1,  416.599.0000  paralucent.com");
                p = document.Footers.Odd.InsertParagraph();
                p.AppendPicture(footerPicture);
                p.Alignment = Alignment.center;
                document.Footers.Odd.InsertParagraph("1 university ave, 3rd floor, toronto, ontario  canada m5j 2p1,  416.599.0000  paralucent.com");

                foreach (var q in questions)
                {
                    document.InsertParagraph($"{q.Index}. {q.Title}").Bold();
                    document.InsertParagraph(q.Content);
                    document.InsertParagraph();
                }

                // Save the document.
                document.Save();
            }
            return(fileName);
        }
Пример #3
0
 public void OpenTask(Exam exam, Ticket ticket, bool markAnswers)
 {
     CloseWord();
     OneAnswerQuestion[] questions = ticket.GetQuestions().Cast <OneAnswerQuestion>().ToArray();
     using (DocX docXdocument = DocX.Create(path.ToString()))
     {
         int i, j;
         docXdocument.AddFooters();
         docXdocument.SetDefaultFont(new Xceed.Document.NET.Font("Times New Roman"));
         Xceed.Document.NET.Paragraph headerParagraph = docXdocument.InsertParagraph();
         Xceed.Document.NET.Paragraph paragraph       = docXdocument.InsertParagraph();
         headerParagraph.Append($"Перегляд завдання")
         .Bold()
         .FontSize(28);
         paragraph.Append($"Завдання білету \"{ticket.TicketName}\":")
         .FontSize(24);
         Xceed.Document.NET.Table table = docXdocument.AddTable(questions.Length, 2);
         table.SetWidthsPercentage(new[] { 50f, 50 }, docXdocument.PageWidth - docXdocument.PageWidth / 5);
         table.SetBorder(TableBorderType.Bottom, new Xceed.Document.NET.Border(BorderStyle.Tcbs_double, BorderSize.two, 0, Color.Black));
         table.SetBorder(TableBorderType.Top, new Xceed.Document.NET.Border(BorderStyle.Tcbs_double, BorderSize.two, 0, Color.Black));
         table.SetBorder(TableBorderType.Left, new Xceed.Document.NET.Border(BorderStyle.Tcbs_double, BorderSize.two, 0, Color.Black));
         table.SetBorder(TableBorderType.Right, new Xceed.Document.NET.Border(BorderStyle.Tcbs_double, BorderSize.two, 0, Color.Black));
         table.SetBorder(TableBorderType.InsideV, new Xceed.Document.NET.Border(BorderStyle.Tcbs_double, BorderSize.two, 0, Color.Black));
         for (i = 0; i < questions.Length; i++)
         {
             table.Rows[i].Cells[0]
             .InsertParagraph()
             .Append($"{questions[i].QuestionNumber + exam.FirstQuestionNumber}) {questions[i].QuestionContent.Text}")
             .FontSize(12);
             Xceed.Document.NET.Paragraph tableParagraph = table.Rows[i].Cells[1].InsertParagraph();
             for (j = 0; j < questions[i].QuestionContent.Answers.Count; j++)
             {
                 Xceed.Document.NET.Paragraph tempParagraph = tableParagraph.Append($"{(j < questions[i].QuestionContent.Letters.Length ? questions[i].QuestionContent.Letters[j].ToString() : "*")}{questions[i].QuestionContent.Devider} { questions[i].QuestionContent.Answers[j]};{Environment.NewLine}");
                 if (markAnswers && questions[i].Answer.Content == questions[i].QuestionContent.Answers[j])
                 {
                     tempParagraph.Bold()
                     .FontSize(12);
                 }
             }
         }
         docXdocument.InsertTable(table);
         docXdocument.Footers.Odd.InsertParagraph()
         .Append("Створено за допомогою SimplEx Program")
         .FontSize(10)
         .UnderlineStyle(UnderlineStyle.singleLine)
         .Alignment = Alignment.right;
         docXdocument.Save();
     }
     OpenWord();
 }
Пример #4
0
        public IActionResult exportrequest2(long id, string userId)
        {
            //var exportexcutiveorderdata = _context.ExecutiveOrders
            //    .Where(m => m.Id == id)
            //   .FirstOrDefault();
            System.Console.WriteLine("1 : " + userId + " : " + id);

            var exportexcutiveorderdata = _context.RequestOrderAnswers
                                          .Include(m => m.RequestOrder)
                                          .Include(m => m.RequestOrderAnswerDetails)
                                          //.Where(m => m.RequestOrder.Draft == 0)
                                          .Where(m => m.Id == id)
                                          .Where(m => m.UserID == userId)
                                          .OrderByDescending(x => x.Id)
                                          .FirstOrDefault();

            var detail = _context.RequestOrderAnswerDetails
                         .Where(m => m.RequestOrderAnswerId == exportexcutiveorderdata.Id)
                         .FirstOrDefault();

            System.Console.WriteLine("1.2 : " + exportexcutiveorderdata.RequestOrder.UserID);
            //ผู้สั่งการ
            var users = _context.Users
                        .Where(m => m.Id == exportexcutiveorderdata.RequestOrder.UserID)
                        .FirstOrDefault();

            System.Console.WriteLine("1.3 : ");

            //ผู้รับข้อสั่งการ
            var username = _context.ApplicationUsers
                           .Where(m => m.Id == userId)
                           .Select(m => m.Name)
                           .FirstOrDefault();

            System.Console.WriteLine("export2 : " + id);

            if (!Directory.Exists(_environment.WebRootPath + "//reportrequestorder//"))         //ถ้ามีไฟล์อยู่แล้ว
            {
                Directory.CreateDirectory(_environment.WebRootPath + "//reportrequestorder//"); //สร้าง Folder reportexecutive ใน wwwroot
            }

            var filePath        = _environment.WebRootPath + "/reportrequestorder/"; // เก็บไฟล์ logo
            var filename        = DateTime.Now.ToString("dd MM yyyy") + ".docx";     // ชื่อไฟล์
            var createfile      = filePath + filename;                               //
            var myImageFullPath = filePath + "logo01.png";

            System.Console.WriteLine("3");
            System.Console.WriteLine("in create");
            using (DocX document = DocX.Create(createfile)) //สร้าง

            {
                document.SetDefaultFont(new Xceed.Document.NET.Font("ThSarabunNew"));
                document.AddHeaders();
                document.AddFooters();

                // Force the first page to have a different Header and Footer.
                document.DifferentFirstPage = true;
                // Force odd & even pages to have different Headers and Footers.
                document.DifferentOddAndEvenPages = true;

                // Insert a Paragraph into the first Header.
                document.Footers.First.InsertParagraph("วันที่ออกรายงาน: ").Append(DateTime.Now.ToString("dd MMMM yyyy HH:mm", new CultureInfo("th-TH"))).Append(" น.").Alignment = Alignment.right;
                // Insert a Paragraph into the even Header.
                document.Footers.Even.InsertParagraph("วันที่ออกรายงาน: ").Append(DateTime.Now.ToString("dd MMMM yyyy HH:mm", new CultureInfo("th-TH"))).Append(" น.").Alignment = Alignment.right;
                // Insert a Paragraph into the odd Header.
                document.Footers.Odd.InsertParagraph("วันที่ออกรายงาน: ").Append(DateTime.Now.ToString("dd MMMM yyyy HH:mm", new CultureInfo("th-TH"))).Append(" น.").Alignment = Alignment.right;

                // Add the page number in the first Footer.
                document.Headers.First.InsertParagraph("").AppendPageNumber(PageNumberFormat.normal).Alignment = Alignment.center;
                // Add the page number in the even Footers.
                document.Headers.Even.InsertParagraph("").AppendPageNumber(PageNumberFormat.normal).Alignment = Alignment.center;
                // Add the page number in the odd Footers.
                document.Headers.Odd.InsertParagraph("").AppendPageNumber(PageNumberFormat.normal).Alignment = Alignment.center;
                System.Console.WriteLine("5");


                document.InsertParagraph("รายงานคำร้องขอของหน่วยงานของรัฐ/หน่วยรับตรวจ (รายเรื่อง)").FontSize(16d)
                .SpacingBefore(15d)
                .SpacingAfter(15d)
                .Bold()     //ตัวหนา
                .Alignment = Alignment.center;

                var name = document.InsertParagraph(users.Name);
                name.Alignment = Alignment.center;
                name.SpacingAfter(10d);
                name.FontSize(14d); //ขนาดตัวอักษร
                name.Bold();
                System.Console.WriteLine("7");

                Thread.CurrentThread.CurrentCulture = new CultureInfo("th-TH");
                var Commanded_date = exportexcutiveorderdata.RequestOrder.Commanded_date.Value.ToString("dd MMMM yyyy");
                var CreatedAt      = exportexcutiveorderdata.RequestOrder.CreatedAt.Value.ToString("dd MMMM yyyy");
                var beaware_date   = exportexcutiveorderdata.beaware_date.Value.ToString("dd MMMM yyyy");


                document.InsertParagraph(" วันที่มีคำร้องขอ" + Commanded_date + "วันที่แจ้งคำร้องขอ" + CreatedAt).FontSize(14d)
                .SpacingBefore(15d)
                .SpacingAfter(15d)
                .Alignment = Alignment.center;

                document.InsertParagraph("เรื่อง :" + exportexcutiveorderdata.RequestOrder.Subject).FontSize(14d)
                .SpacingBefore(15d)
                .SpacingAfter(15d)
                .Alignment = Alignment.left;


                document.InsertParagraph("ผู้รับคำร้องขอ  :" + username).FontSize(14d)
                .SpacingBefore(15d)
                .SpacingAfter(15d)

                .Alignment = Alignment.left;

                document.InsertParagraph("รายละเอียด  :").FontSize(14d)
                .SpacingBefore(15d)
                .SpacingAfter(15d)
                .Alignment = Alignment.left;

                document.InsertParagraph("\n\n");

                document.InsertParagraph("การดำเนินการตามคำร้องขอ ").FontSize(16d)
                .SpacingBefore(15d)
                .SpacingAfter(15d)
                .Bold()    //ตัวหนา
                .Alignment = Alignment.center;

                document.InsertParagraph("วันที่มีคำร้องขอ  " + Commanded_date + "  วันที่รับทราบคำร้องขอ  " + beaware_date).FontSize(14d)
                .SpacingBefore(15d)
                .SpacingAfter(15d)
                .Alignment = Alignment.center;


                document.InsertParagraph("รายละเอียด :" + detail.Answerdetail).FontSize(14d)
                .SpacingBefore(15d)
                .SpacingAfter(15d)
                //.Bold() //ตัวหนา
                .Alignment = Alignment.left;

                document.InsertParagraph("ปัญหา/อุปสรรค :" + detail.AnswerProblem).FontSize(14d)
                .SpacingBefore(15d)
                .SpacingAfter(15d)
                //.Bold() //ตัวหนา
                .Alignment = Alignment.left;

                document.InsertParagraph("ข้อเสนอแนะ :" + detail.AnswerCounsel).FontSize(14d)
                .SpacingBefore(15d)
                .SpacingAfter(15d)
                //.Bold() //ตัวหนา
                .Alignment = Alignment.left;

                System.Console.WriteLine("11");
                document.Save(); //save เอกสาร
                Console.WriteLine("\tCreated: InsertHorizontalLine.docx\n");

                System.Console.WriteLine("12");
                return(Ok(new { data = filename }));
            }
        }
Пример #5
0
        public IActionResult Getexport3([FromBody] UserViewModel body)
        {
            System.Console.WriteLine("id " + body.Id);
            var userId     = body.Id;
            var random     = RandomString(3);
            var Eexcutive3 = _context.RequestOrderAnswers
                             .Include(m => m.RequestOrder)
                             .Include(m => m.RequestOrderAnswerDetails)
                             .Where(m => m.RequestOrder.Draft == 0)
                             .Where(m => m.UserID == userId).ToList();

            var users = _context.Users
                        .Where(m => m.Id == userId)
                        .FirstOrDefault();

            var appDataPath = _environment.WebRootPath + "//reportrequest//";

            if (!Directory.Exists(appDataPath))
            {
                Directory.CreateDirectory(appDataPath);
            }
            System.Console.WriteLine("export_ : " + userId);
            //if (!Directory.Exists(_environment.WebRootPath + "//reportexecutive//")) //ถ้ามีไฟล์อยู่แล้ว
            //{
            //    Directory.CreateDirectory(_environment.WebRootPath + "//reportexecutive//"); //สร้าง Folder reportexecutive ใน wwwroot
            //}

            var filePath        = _environment.WebRootPath + "/reportrequest/";                                                            // เก็บไฟล์ logo
            var filename        = "ทะเบียนคำร้องขอจากหน่วยงานของรัฐหน่วยรับตรวจ" + DateTime.Now.ToString("dd MM yyyy") + random + ".docx"; // ชื่อไฟล์
            var createfile      = filePath + filename;                                                                                     //
            var myImageFullPath = filePath + "logo01.png";

            System.Console.WriteLine("3");
            System.Console.WriteLine("in create");
            using (DocX document = DocX.Create(createfile)) //สร้าง
            {
                document.SetDefaultFont(new Xceed.Document.NET.Font("ThSarabunNew"));
                document.AddHeaders();
                document.AddFooters();

                // Force the first page to have a different Header and Footer.
                document.DifferentFirstPage = true;
                // Force odd & even pages to have different Headers and Footers.
                document.DifferentOddAndEvenPages = true;

                // Insert a Paragraph into the first Header.
                document.Footers.First.InsertParagraph("วันที่ออกรายงาน: ").Append(DateTime.Now.ToString("dd MMMM yyyy HH:mm", new CultureInfo("th-TH"))).Append(" น.").Alignment = Alignment.right;
                // Insert a Paragraph into the even Header.
                document.Footers.Even.InsertParagraph("วันที่ออกรายงาน: ").Append(DateTime.Now.ToString("dd MMMM yyyy HH:mm", new CultureInfo("th-TH"))).Append(" น.").Alignment = Alignment.right;
                // Insert a Paragraph into the odd Header.
                document.Footers.Odd.InsertParagraph("วันที่ออกรายงาน: ").Append(DateTime.Now.ToString("dd MMMM yyyy HH:mm", new CultureInfo("th-TH"))).Append(" น.").Alignment = Alignment.right;

                // Add the page number in the first Footer.
                document.Headers.First.InsertParagraph("").AppendPageNumber(PageNumberFormat.normal).Alignment = Alignment.center;
                // Add the page number in the even Footers.
                document.Headers.Even.InsertParagraph("").AppendPageNumber(PageNumberFormat.normal).Alignment = Alignment.center;
                // Add the page number in the odd Footers.
                document.Headers.Odd.InsertParagraph("").AppendPageNumber(PageNumberFormat.normal).Alignment = Alignment.center;
                System.Console.WriteLine("5");

                // Add a title
                document.InsertParagraph("ทะเบียนคำร้องขอจากหน่วยงานของรัฐ/หน่วยรับตรวจ").FontSize(16d)
                .SpacingBefore(15d)
                .SpacingAfter(15d)
                .Bold()     //ตัวหนา
                .Alignment = Alignment.center;

                var name = document.InsertParagraph(users.Name);
                name.Alignment = Alignment.center;
                name.SpacingAfter(10d);
                name.FontSize(12d); //ขนาดตัวอักษร
                System.Console.WriteLine("7");

                Thread.CurrentThread.CurrentCulture = new CultureInfo("th-TH");
                var Date = DateTime.Now.ToString("dd MMMM yyyy");
                var year = document.InsertParagraph("วันที่เรียกรายงาน" + Date);
                year.Alignment = Alignment.center;
                year.SpacingAfter(10d);

                int dataCount = 0;
                dataCount  = Eexcutive3.Count; //เอาที่ select มาใช้
                dataCount += 1;
                System.Console.WriteLine("Data Count: " + dataCount);
                // Add a table in a document of 1 row and 3 columns.
                var columnWidths = new float[] { 300f, 300f, 300f, 300f, 300f, 300f, 300f };
                var t            = document.InsertTable(dataCount, columnWidths.Length);

                System.Console.WriteLine("8");

                // Set the table's column width and background
                t.SetWidths(columnWidths);
                t.AutoFit = AutoFit.Contents;

                var row = t.Rows.First();

                // Fill in the columns of the first row in the table.
                //for (int i = 0; i < row.Cells.Count; ++i)
                //{
                row.Cells[0].Paragraphs.First().Append("ลำดับที่");
                row.Cells[1].Paragraphs.First().Append("วัน/เดือน/ปี ที่มีคำร้องขอ");
                row.Cells[2].Paragraphs.First().Append("ผู้แจ้ง คำร้องขอ/ หน่วยงาน");
                row.Cells[3].Paragraphs.First().Append("ประเด็น/เรื่อง");
                row.Cells[4].Paragraphs.First().Append("สถานะเรื่อง");
                row.Cells[5].Paragraphs.First().Append("วัน/เดือน/ปี ที่รับทราบคำร้องขอ");
                row.Cells[6].Paragraphs.First().Append("การดำเนินการ");

                // Add rows in the table.
                int j = 0;
                for (int i = 0; i < Eexcutive3.Count; i++)
                {
                    j += 1;
                    //System.Console.WriteLine(i+=1);
                    var username = _context.ApplicationUsers
                                   .Where(m => m.Id == Eexcutive3[i].RequestOrder.UserID)
                                   .Select(m => m.Name)
                                   .FirstOrDefault();
                    System.Console.WriteLine("JJJJJ: " + j);

                    var Commanded_date = Eexcutive3[i].RequestOrder.Commanded_date.Value.ToString("dd MMMM yyyy");
                    var beaware_date   = Eexcutive3[i].beaware_date.Value.ToString("dd MMMM yyyy");

                    t.Rows[j].Cells[0].Paragraphs[0].Append(j.ToString());
                    t.Rows[j].Cells[1].Paragraphs[0].Append(Commanded_date);
                    t.Rows[j].Cells[2].Paragraphs[0].Append(username);
                    t.Rows[j].Cells[3].Paragraphs[0].Append(Eexcutive3[i].RequestOrder.Subject);
                    t.Rows[j].Cells[4].Paragraphs[0].Append(Eexcutive3[i].Status);
                    t.Rows[j].Cells[5].Paragraphs[0].Append(beaware_date.ToString());
                    t.Rows[j].Cells[6].Paragraphs[0].Append("-");
                }

                // Set a blank border for the table's top/bottom borders.
                var blankBorder = new Border(BorderStyle.Tcbs_none, 0, 0, Color.White);
                //t.SetBorder(TableBorderType.Bottom, blankBorder);
                //t.SetBorder(TableBorderType.Top, blankBorder);

                System.Console.WriteLine("11");
                document.Save(); //save เอกสาร
                Console.WriteLine("\tCreated: InsertHorizontalLine.docx\n");

                return(Ok(new { data = filename }));
            }
        }
Пример #6
0
        private void CreateOrder(int course, string code, string direct)
        {
            string file = "order.docx";
            // создаём документ
            DocX document = DocX.Create(dir + file);

            document.SetDefaultFont(new Font("Times New Roman"), fontSize: 12); // Устанавливаем стандартный для документа шрифт и размер шрифта
            document.MarginLeft   = 42.5f;
            document.MarginTop    = 34.1f;
            document.MarginRight  = 34.1f;
            document.MarginBottom = 34.1f;

            document.InsertParagraph($"Проект приказа\n\n").Bold().Alignment = Alignment.center;
            document.InsertParagraph($"\tВ соответствии с календарным графиком учебного процесса допустить " +
                                     $"и направить для прохождения {form_pract.SelectedItem.ToString().ToLower()} практики {combobox_type.SelectedItem} " +
                                     $"следующих студентов {course} курса, очной формы, направление подготовки {code} «{direct}», " +
                                     $"профиль «Прикладная информатика в государственном и муниципальном управлении», факультета " +
                                     $"«Информационные системы в управлении» с {first_date.Text}г. по {second_date.Text}.\n");
            document.InsertParagraph($"\tСпособ проведения практики: выездная и стационарная.");
            document.InsertParagraph($"\tСтационарная практика (без оплаты)\n").Bold();
            document.InsertParagraph($"\tОбучающихся за счет бюджетных ассигнований федерального бюджета");

            IEnumerable <Fill_data> studentsF = fill_data.Where(k => k.payable.Equals("Бюджет"));
            IEnumerable <Fill_data> studentsB = fill_data.Where(k => k.payable.Equals("Внебюджет"));

            Xceed.Document.NET.Table table     = document.AddTable(studentsF.Count() + 1, 4);
            Xceed.Document.NET.Table tabpe_pay = document.AddTable(studentsB.Count() + 1, 4);

            table.Alignment = Alignment.center;
            table.AutoFit   = AutoFit.Contents;

            tabpe_pay.Alignment = Alignment.center;
            tabpe_pay.AutoFit   = AutoFit.Contents;

            table.Rows[0].Cells[0].Paragraphs[0].Append("ФИО студента").Alignment = Alignment.center;
            table.Rows[0].Cells[1].Paragraphs[0].Append("Группа").Alignment       = Alignment.center;
            table.Rows[0].Cells[2].Paragraphs[0].Append("Место прохождения практики").Alignment = Alignment.center;
            table.Rows[0].Cells[3].Paragraphs[0].Append("Руководитель практики").Alignment      = Alignment.center;

            tabpe_pay.Rows[0].Cells[0].Paragraphs[0].Append("ФИО студента").Alignment = Alignment.center;
            tabpe_pay.Rows[0].Cells[1].Paragraphs[0].Append("Группа").Alignment       = Alignment.center;
            tabpe_pay.Rows[0].Cells[2].Paragraphs[0].Append("Место прохождения практики").Alignment = Alignment.center;
            tabpe_pay.Rows[0].Cells[3].Paragraphs[0].Append("Руководитель практики").Alignment      = Alignment.center;

            for (int i = 0; i < studentsF.Count(); i++)
            {
                table.Rows[i + 1].Cells[0].Paragraphs[0].Append(studentsF.ElementAt(i).fio);
                table.Rows[i + 1].Cells[1].Paragraphs[0].Append(combobox_groupe.SelectedItem.ToString());
                table.Rows[i + 1].Cells[2].Paragraphs[0].Append(studentsF.ElementAt(i).place);
                table.Rows[i + 1].Cells[3].Paragraphs[0].Append(combobox_otvetsven.SelectedItem.ToString());
            }

            for (int i = 0; i < studentsB.Count(); i++)
            {
                tabpe_pay.Rows[i + 1].Cells[0].Paragraphs[0].Append(studentsB.ElementAt(i).fio);
                tabpe_pay.Rows[i + 1].Cells[1].Paragraphs[0].Append(combobox_groupe.SelectedItem.ToString());
                tabpe_pay.Rows[i + 1].Cells[2].Paragraphs[0].Append(studentsB.ElementAt(i).place);
                tabpe_pay.Rows[i + 1].Cells[3].Paragraphs[0].Append(combobox_otvetsven.SelectedItem.ToString());
            }
            document.InsertParagraph().InsertTableAfterSelf(table);

            if (studentsB.Count() > 0)
            {
                document.InsertParagraph($"\tОбучающихся на платной основе");
                document.InsertParagraph().InsertTableAfterSelf(tabpe_pay);
            }
            document.InsertParagraph($"\tОтветственный по {form_pract.SelectedItem.ToString().ToLower()}  практики по кафедре в период с {first_date.Text} г. по  {second_date.Text} г. -  {combobox_otvetsven.Text} ст. преподаватель кафедры ПИЭ.");

            Classes.Direction directions = Helper.ODirections.Where(k => k.name.Equals(direct)).ElementAt(0);
            Cathedra          cathedra   = Helper.OCathedras.Where(k => k.cathedra.Equals(directions.id_cathedra)).ElementAt(0);

            document.InsertParagraph($@"
        Проректор по УР                    ________«____» ________ {first_date.SelectedDate.Value.Year}г.   С.В. Мельник
        Главный бухгалтер                ________«____» ________ {first_date.SelectedDate.Value.Year} г.  Г.И. Вилисова
        Начальник ПЭО                     ________«____» ________ {first_date.SelectedDate.Value.Year}г.   Т.В. Грачева
        Начальник ООП и СТВ          ________«____» ________{first_date.SelectedDate.Value.Year}г.   Ю.С. Сачук 
        Декан факультета «{directions.id_cathedra}»  ________«____» ________ {first_date.SelectedDate.Value.Year}г.   {cathedra.name.Remove(1)}.{cathedra.patronymic.Remove(1)}. {cathedra.surname}
        Ответственный за практику 
        и содействие трудоустройству
        на факультете                 ________«____» __________ {first_date.SelectedDate.Value.Year}г.   {cathedra.name.Remove(1)}.{cathedra.patronymic.Remove(1)}.{cathedra.surname}
");
            document.Save();
            MessageBox.Show("Документ успешно сформирован!", "Документ", MessageBoxButton.OK, MessageBoxImage.Information);
        }
        public IActionResult PrintReport([FromBody] ExportReportViewModel model)
        {
            var electronicBook = _context.ElectronicBooks
                                 .Include(x => x.User)
                                 .Include(x => x.ElectronicBookFiles)
                                 .Where(x => x.Id == model.electronicBookId)
                                 .FirstOrDefault();

            System.Console.WriteLine("in printtttt");

            if (!Directory.Exists(_environment.WebRootPath + "//Uploads//"))
            {
                Directory.CreateDirectory(_environment.WebRootPath + "//Uploads//"); //สร้าง Folder Upload ใน wwwroot
            }
            var filePath        = _environment.WebRootPath + "/Uploads/";
            var filePath2       = _environment.WebRootPath + "/Signature/";
            var filename        = "สมุดตรวจราชการอิเล็กทรอนิกส์" + DateTime.Now.ToString("dd MM yyyy") + ".docx";
            var createfile      = filePath + filename;
            var myImageFullPath = filePath + "logo01.png";

            System.Console.WriteLine("3");
            System.Console.WriteLine("in create");
            using (DocX document = DocX.Create(createfile))
            {
                Image   image   = document.AddImage(myImageFullPath);
                Picture picture = image.CreatePicture(85, 85);
                var     logo    = document.InsertParagraph();
                logo.AppendPicture(picture).Alignment = Alignment.center;
                document.SetDefaultFont(new Xceed.Document.NET.Font("ThSarabunNew"));

                document.AddHeaders();
                document.AddFooters();

                // Force the first page to have a different Header and Footer.
                document.DifferentFirstPage = true;
                // Force odd & even pages to have different Headers and Footers.
                document.DifferentOddAndEvenPages = true;

                // Insert a Paragraph into the first Header.
                document.Footers.First.InsertParagraph("วันที่ออกรายงาน: ").Append(DateTime.Now.ToString("dd MMMM yyyy HH:mm", new CultureInfo("th-TH"))).Append(" น.").Alignment = Alignment.right;
                // Insert a Paragraph into the even Header.
                document.Footers.Even.InsertParagraph("วันที่ออกรายงาน: ").Append(DateTime.Now.ToString("dd MMMM yyyy HH:mm", new CultureInfo("th-TH"))).Append(" น.").Alignment = Alignment.right;
                // Insert a Paragraph into the odd Header.
                document.Footers.Odd.InsertParagraph("วันที่ออกรายงาน: ").Append(DateTime.Now.ToString("dd MMMM yyyy HH:mm", new CultureInfo("th-TH"))).Append(" น.").Alignment = Alignment.right;

                // Add the page number in the first Footer.
                document.Headers.First.InsertParagraph("").AppendPageNumber(PageNumberFormat.normal).Alignment = Alignment.center;
                // Add the page number in the even Footers.
                document.Headers.Even.InsertParagraph("").AppendPageNumber(PageNumberFormat.normal).Alignment = Alignment.center;
                // Add the page number in the odd Footers.
                document.Headers.Odd.InsertParagraph("").AppendPageNumber(PageNumberFormat.normal).Alignment = Alignment.center;

                System.Console.WriteLine("5");

                // Add a title

                var reportType = document.InsertParagraph("สมุดตรวจราชการอิเล็กทรอนิกส์");
                reportType.FontSize(18d);
                reportType.SpacingBefore(15d);
                reportType.SpacingAfter(5d);
                reportType.Bold();
                reportType.Alignment = Alignment.center;

                System.Console.WriteLine("6");

                Thread.CurrentThread.CurrentCulture = new CultureInfo("th-TH");
                var testDate  = electronicBook.StartDate.Value.ToString("dddd dd MMMM yyyy");
                var printDate = DateTime.Now.ToString("dd MMMM yyyy");
                // Insert a title paragraph.
                var title = document.InsertParagraph("วันที่ตรวจราชการ: " + testDate);
                title.Alignment = Alignment.center;
                title.SpacingAfter(15d);
                title.FontSize(16d);
                title.Bold();

                //var printReport = document.InsertParagraph("วันที่ออกรายงาน: " + printDate);
                //printReport.Alignment = Alignment.center;
                //printReport.SpacingAfter(25d);
                //printReport.FontSize(16d);
                //printReport.Bold();

                System.Console.WriteLine("7");

                //var year = document.InsertParagraph("ตรวจ ณ สถานที่: ");
                //year.Alignment = Alignment.center;
                //year.SpacingAfter(10d);
                //year.FontSize(16d);
                //System.Console.WriteLine("8");


                var subjectTitle = document.InsertParagraph("เรื่อง/ประเด็น/โครงการที่ตรวจติดตาม");
                subjectTitle.Alignment = Alignment.left;
                //subjectTitle.SpacingAfter(10d);
                subjectTitle.FontSize(16d);
                subjectTitle.Bold();
                System.Console.WriteLine("8");

                var subject = document.InsertParagraph("");

                int s = 0;
                for (var i = 0; i < model.subjectData.Length; i++)
                {
                    s += 1;
                    subject.FontSize(16d).Append(s.ToString()).Append(") ").Append(model.subjectData[i] + "\n").FontSize(16d);
                }

                var detailTitle = document.InsertParagraph("ผลการตรวจ");
                detailTitle.SpacingBefore(10d);
                detailTitle.FontSize(16d);
                detailTitle.Bold();
                var detail = document.InsertParagraph(electronicBook.Detail);
                detail.SpacingBefore(5d);
                detail.FontSize(16d);
                // detail.UnderlineColor(Color.Black);
                // detail.UnderlineStyle(UnderlineStyle.dotted);

                var suggestionTitle = document.InsertParagraph("ปัญหาและอุปสรรค");
                suggestionTitle.SpacingBefore(15d);
                suggestionTitle.FontSize(16d);
                suggestionTitle.Bold();
                var suggestion = document.InsertParagraph(electronicBook.Problem);
                suggestion.SpacingBefore(5d);
                suggestion.FontSize(16d);
                // suggestion.UnderlineColor(Color.Black);
                // suggestion.UnderlineStyle(UnderlineStyle.dotted);

                var commandTitle = document.InsertParagraph("ข้อเสนอแนะ");
                commandTitle.SpacingBefore(15d);
                commandTitle.FontSize(16d);
                commandTitle.Bold();
                var command = document.InsertParagraph(electronicBook.Suggestion);
                command.SpacingBefore(5d);
                command.FontSize(16d);
                // command.UnderlineColor(Color.Black);
                // command.UnderlineStyle(UnderlineStyle.dotted);
                //command.InsertPageBreakAfterSelf();
                System.Console.WriteLine("11");


                //System.Console.WriteLine("9");

                //var region = document.InsertParagraph("เขตตรวจราชการที่: " + model.reportData2[i].region + "(จังหวัด: " + model.reportData2[i].province + ")");
                //region.Alignment = Alignment.center;
                //region.SpacingAfter(30d);
                //region.FontSize(16d);

                //var statusReport = document.InsertParagraph("สถานะของรายงาน: " + exportData.Status);
                //statusReport.FontSize(16d);
                //statusReport.Alignment = Alignment.right;

                //var monitorTopic = document.InsertParagraph("หัวข้อการตรวจติดตาม: " + exportData.MonitoringTopics);
                //monitorTopic.SpacingBefore(15d);
                //monitorTopic.FontSize(16d);
                //monitorTopic.Bold();

                //System.Console.WriteLine("99");
                var inspectorTitle = document.InsertParagraph("คำแนะนำผู้ตรวจราชการ");
                inspectorTitle.SpacingBefore(30d);
                inspectorTitle.SpacingAfter(5d);
                inspectorTitle.FontSize(16d);
                inspectorTitle.Bold();

                int dataCount = 0;
                dataCount  = model.printReport.Count();
                dataCount += 1;
                System.Console.WriteLine("Data Count: " + dataCount);
                // Add a table in a document of 1 row and 3 columns.
                var columnWidths = new float[] { 40f, 250f, 90f, 120f, };
                var t            = document.InsertTable(dataCount, columnWidths.Length);

                //System.Console.WriteLine("8");

                //// Set the table's column width and background
                t.SetWidths(columnWidths);
                t.AutoFit   = AutoFit.Contents;
                t.Alignment = Alignment.center;

                var row = t.Rows.First();
                //System.Console.WriteLine("9");

                // Fill in the columns of the first row in the table.
                //for (int i = 0; i < row.Cells.Count; ++i)
                //{
                row.Cells[0].Paragraphs.First().Append("ลำดับ").FontSize(16d).Alignment = Alignment.center;
                row.Cells[1].Paragraphs.First().Append("คำแนะนำหรือสั่งการของผู้ตรวจ").FontSize(16d).Alignment = Alignment.center;
                row.Cells[2].Paragraphs.First().Append("ความเห็นผู้ตรวจ").FontSize(16d).Alignment   = Alignment.center;
                row.Cells[3].Paragraphs.First().Append("ลายมือชื่อผู้ตรวจ").FontSize(16d).Alignment = Alignment.center;

                System.Console.WriteLine("10");

                //}
                // Add rows in the table.
                int j = 0;
                for (int k = 0; k < model.printReport.Length; k++)
                {
                    j += 1;
                    System.Console.WriteLine("10.1");

                    System.Console.WriteLine("9.1: " + model.printReport[k].inspectorDescription);
                    t.Rows[j].Cells[0].Paragraphs[0].Append(j.ToString()).FontSize(16d).Alignment = Alignment.center;
                    t.Rows[j].Cells[1].Paragraphs[0].Append(model.printReport[k].inspectorDescription).FontSize(16d);
                    t.Rows[j].Cells[2].Paragraphs[0].Append(model.printReport[k].approve).FontSize(16d);
                    if (model.printReport[k].inspectorSign != null && model.printReport[k].inspectorSign != "null" && model.printReport[k].inspectorSign != "")
                    {
                        System.Console.WriteLine("9.3: " + model.printReport[k].inspectorSign);
                        var myImageFullPath2 = filePath2 + model.printReport[k].inspectorSign;

                        Image image2 = document.AddImage(myImageFullPath2);
                        System.Console.WriteLine("JJJJJ: ");
                        Picture picture2 = image2.CreatePicture(30, 30);
                        t.Rows[j].Cells[3].Paragraphs[0].AppendPicture(picture2).SpacingBefore(3d).Append("\n" + model.printReport[k].inspectorName).FontSize(16d).Alignment = Alignment.center;
                    }
                    else
                    {
                        System.Console.WriteLine("9.4: ");
                        t.Rows[j].Cells[3].Paragraphs[0].Append(model.printReport[k].inspectorName).FontSize(16d).Alignment = Alignment.center;
                    }
                    System.Console.WriteLine("10");
                }

                // Set a blank border for the table's top/bottom borders.
                var blankBorder = new Border(BorderStyle.Tcbs_none, 0, 0, Color.White);
                //t.SetBorder(TableBorderType.Bottom, blankBorder);
                //t.SetBorder(TableBorderType.Top, blankBorder);

                // document.InsertSectionPageBreak();

                System.Console.WriteLine("IN DEPARTMENT");

                var departmentTitle = document.InsertParagraph("การดำเนินการของหน่วยรับตรวจ");
                departmentTitle.SpacingBefore(30d);
                departmentTitle.SpacingAfter(5d);
                departmentTitle.FontSize(16d);
                departmentTitle.Bold();

                System.Console.WriteLine("IN DEPARTMENT2");

                int dataCount2 = 0;
                dataCount2  = model.printReport2.Count();
                dataCount2 += 1;
                System.Console.WriteLine("Data Count department: " + dataCount2);
                // Add a table in a document of 1 row and 3 columns.
                var columnWidths2 = new float[] { 40f, 250f, 80f, 120f, };
                var t2            = document.InsertTable(dataCount2, columnWidths2.Length);

                //System.Console.WriteLine("8");

                //// Set the table's column width and background
                t2.SetWidths(columnWidths2);
                t2.AutoFit   = AutoFit.Contents;
                t2.Alignment = Alignment.center;

                var row2 = t2.Rows.First();
                //System.Console.WriteLine("9");

                // Fill in the columns of the first row in the table.
                //for (int i = 0; i < row.Cells.Count; ++i)
                //{
                row2.Cells[0].Paragraphs.First().Append("ลำดับ").FontSize(16d).Alignment = Alignment.center;
                row2.Cells[1].Paragraphs.First().Append("การดำเนินการของหน่วยรับตรวจ").FontSize(16d).Alignment = Alignment.center;
                row2.Cells[2].Paragraphs.First().Append("หน่วยรับตรวจ").FontSize(16d).Alignment         = Alignment.center;
                row2.Cells[3].Paragraphs.First().Append("ลายมือชื่อผู้รับตรวจ").FontSize(16d).Alignment = Alignment.center;

                System.Console.WriteLine("10");
                //}
                // Add rows in the table.
                int j2 = 0;
                for (int k = 0; k < model.printReport2.Length; k++)
                {
                    j2 += 1;
                    t2.Rows[j2].Cells[0].Paragraphs[0].Append(j2.ToString()).FontSize(16d).Alignment = Alignment.center;
                    t2.Rows[j2].Cells[1].Paragraphs[0].Append(model.printReport2[k].departmentDescription).FontSize(16d);
                    t2.Rows[j2].Cells[2].Paragraphs[0].Append(model.printReport2[k].department).FontSize(16d);
                    if (model.printReport2[k].departmentSign != null && model.printReport2[k].departmentSign != "null" && model.printReport2[k].departmentSign != "")
                    {
                        var   myImageFullPath3 = filePath2 + model.printReport2[k].departmentSign;
                        Image image3           = document.AddImage(myImageFullPath3);
                        System.Console.WriteLine("JJJJJ: ");
                        Picture picture2 = image3.CreatePicture(30, 30);
                        t2.Rows[j2].Cells[3].Paragraphs[0].AppendPicture(picture2).SpacingBefore(3d).Append("\n" + model.printReport2[k].departmentName).FontSize(16d).Alignment = Alignment.center;
                    }
                    else
                    {
                        t2.Rows[j2].Cells[3].Paragraphs[0].Append(model.printReport2[k].departmentName).FontSize(16d);
                    }

                    System.Console.WriteLine("10");
                }

                // Set a blank border for the table's top/bottom borders.
                var blankBorder2 = new Border(BorderStyle.Tcbs_none, 0, 0, Color.White);


                document.Save();
                Console.WriteLine("\tCreated: InsertHorizontalLine.docx\n");
            }

            return(Ok(new { data = filename }));
        }
        private bool CreateContract_Attch2()
        {
            try
            {
                string file = $"Приложение 2.docx";

                SQLiteAdapter.DeleteRowById("attach", $"[id_contract]='{sel_items.id}'"); // Удаляем существующие данные

                // создаём документ
                DocX document = DocX.Create(dir + file);

                document.SetDefaultFont(new Font("Times New Roman"), fontSize: 12); // Устанавливаем стандартный для документа шрифт и размер шрифта
                document.MarginLeft             = 42.5f;
                document.MarginTop              = 34.1f;
                document.MarginRight            = 34.1f;
                document.MarginBottom           = 34.1f;
                document.PageLayout.Orientation = Xceed.Document.NET.Orientation.Landscape;

                document.InsertParagraph("Приложение 2").Alignment = Alignment.right;
                document.InsertParagraph($"к договору № {contract_num.Text} от {date.Text} г.").Alignment = Alignment.right;

                document.InsertParagraph("Список студентов ФГБОУ ВО «СибАДИ», направляемых на производственные объекты").Alignment = Alignment.center;
                document.InsertParagraph($"\t\t{contract_org.Text}\t\t\t").UnderlineStyle(UnderlineStyle.singleLine).Alignment     = Alignment.center;
                document.InsertParagraph("наименование предприятия, учреждения, организации").Script(Script.superscript).FontSize(12).Alignment = Alignment.center;
                document.InsertParagraph("для прохождения").Alignment = Alignment.center;
                Paragraph paragraph1 = document.InsertParagraph($"\t\t{form_pract.SelectedItem.ToString().Trim()}, {type_pract.Text}\t\t\t").UnderlineStyle(UnderlineStyle.singleLine);
                paragraph1.Append($"в {date.SelectedDate.Value.Year} г").Alignment = Alignment.center;
                document.InsertParagraph("вид и тип практики").Script(Script.superscript).FontSize(12).Alignment = Alignment.center;

                int _all_el = 0;
                foreach (List <string> tmp in selected_student)
                {
                    _all_el += tmp.Count;
                }

                // создаём таблицу с N строками и 3 столбцами
                Table table = document.AddTable(_all_el + 2, 9);
                // располагаем таблицу по центру
                table.Alignment = Alignment.center;
                table.AutoFit   = AutoFit.Contents;

                #region Стандартное заполнение
                table.Rows[0].Cells[0].Paragraphs[0].Append("№ п/п").Alignment = Alignment.center;
                table.Rows[0].Cells[1].Paragraphs[0].Append("Название факультета, кафедры, заявивших студентов на практику ").Alignment = Alignment.center;
                table.Rows[0].Cells[2].Paragraphs[0].Append("Направление/специальность").Alignment = Alignment.center;
                table.Rows[0].Cells[3].Paragraphs[0].Append("Сроки практики").Alignment            = Alignment.center;
                table.Rows[0].Cells[4].Paragraphs[0].Append("Курс").Alignment            = Alignment.center;
                table.Rows[0].Cells[5].Paragraphs[0].Append("Группа").Alignment          = Alignment.center;
                table.Rows[0].Cells[6].Paragraphs[0].Append("Ф.И.О. студента").Alignment = Alignment.center;
                table.Rows[0].Cells[7].Paragraphs[0].Append("Ф.И.О. руководителя практики от кафедры").Alignment           = Alignment.center;
                table.Rows[0].Cells[8].Paragraphs[0].Append("Контактные телефоны кафедры по вопросам практики ").Alignment = Alignment.center;

                table.Rows[1].Cells[0].Paragraphs[0].Append("1").Alignment = Alignment.center;
                table.Rows[1].Cells[1].Paragraphs[0].Append("2").Alignment = Alignment.center;
                table.Rows[1].Cells[2].Paragraphs[0].Append("3").Alignment = Alignment.center;
                table.Rows[1].Cells[3].Paragraphs[0].Append("4").Alignment = Alignment.center;
                table.Rows[1].Cells[4].Paragraphs[0].Append("5").Alignment = Alignment.center;
                table.Rows[1].Cells[5].Paragraphs[0].Append("6").Alignment = Alignment.center;
                table.Rows[1].Cells[6].Paragraphs[0].Append("7").Alignment = Alignment.center;
                table.Rows[1].Cells[7].Paragraphs[0].Append("8").Alignment = Alignment.center;
                table.Rows[1].Cells[8].Paragraphs[0].Append("9").Alignment = Alignment.center;
                #endregion

                int row = 2;
                for (int i = 0; i < selected_student.Count; i++)
                {
                    foreach (string tmp_st in selected_student[i])
                    {
                        table.Rows[row].Cells[0].Paragraphs[0].Append((i + 1).ToString()).Alignment = Alignment.center;
                        Group             group     = Helper.OGroups.Where(k => k.groupe.Equals(selected_group[i])).ElementAt(0);
                        Classes.Direction direction = Helper.ODirections.Where(k => k.name.Equals(group.direction)).ElementAt(0);
                        Cathedra          cathedra  = Helper.OCathedras.Where(k => k.cathedra.Equals(direction.id_cathedra)).ElementAt(0);

                        #region Вычисляем курс
                        int enroll = Convert.ToInt32(group.enroll_year); // Год поступления
                        int end    = Convert.ToInt32(group.end_year);    // Год окончания

                        int course = DateTime.Today.Year - enroll;
                        int month  = DateTime.Today.Month - 9;
                        if (month >= 0)
                        {
                            course++;
                        }
                        #endregion

                        table.Rows[row].Cells[1].Paragraphs[0].Append(cathedra.cathedra).Alignment = Alignment.center;                                                  // Кафедра
                        table.Rows[row].Cells[2].Paragraphs[0].Append(direction.code + " " + direction.name).Alignment = Alignment.center;                              // Направление
                        table.Rows[row].Cells[3].Paragraphs[0].Append(" - ").Alignment             = Alignment.center;                                                  // Сроки практики
                        table.Rows[row].Cells[4].Paragraphs[0].Append(course.ToString()).Alignment = Alignment.center;                                                  // Курс
                        table.Rows[row].Cells[5].Paragraphs[0].Append(group.groupe).Alignment      = Alignment.center;                                                  // Группа
                        table.Rows[row].Cells[6].Paragraphs[0].Append(tmp_st).Alignment            = Alignment.center;                                                  // Ф.И.О. студента
                        table.Rows[row].Cells[7].Paragraphs[0].Append(cathedra.surname + " " + cathedra.name + " " + cathedra.patronymic).Alignment = Alignment.center; // Ф.И.О. руководителя от кафедры
                        table.Rows[row].Cells[8].Paragraphs[0].Append(cathedra.phone).Alignment = Alignment.center;                                                     // Телефон кафедры
                        row++;

                        // Добавляем студента в БД Attach
                        // Разбиваем ФИО студента на состовляющие
                        var     fio    = tmp_st.Split();
                        Student st_tmp = Helper.OStudents.Where(k => k.surname.Equals(fio[0]) && k.name.Equals(fio[1]) && k.patronymic.Equals(fio[2])).ElementAt(0);

                        SQLiteAdapter.SetValue("attach", contract_num.Text, st_tmp.id); // и записываем новые
                    }
                }

                document.InsertParagraph().InsertTableAfterSelf(table);

                document.InsertParagraph();
                document.InsertParagraph("Согласовано:");
                document.InsertParagraph("Заведующий выпускающей кафедрой");
                document.InsertParagraph("«___________________________________»	______________ /______________________/");
                document.InsertParagraph("							подпись             расшифровка подписи").Script(Script.superscript).FontSize(10);
                document.InsertParagraph("Декан факультета / Директор института");
                document.InsertParagraph("«___________________________________»	______________ /______________________/");
                document.InsertParagraph("							подпись             расшифровка подписи").Script(Script.superscript).FontSize(10);
                document.InsertParagraph("Начальник отдела организации практики");
                document.InsertParagraph("и содействия трудоустройству выпускников    ______________ / Ю.С.Сачук /");
                document.InsertParagraph("							подпись             расшифровка подписи").Script(Script.superscript).FontSize(10);

                // сохраняем документ
                document.Save();
            }
            catch (Exception e)
            {
                MessageBox.Show($"Error: {e}", "Error", MessageBoxButton.OK);
                return(false);
            }

            return(true);
        }
        private bool CreateContract_Attch1()
        {
            try
            {
                string file = $"Приложение 1.docx";

                // создаём документ
                DocX document = DocX.Create(dir + file);

                document.SetDefaultFont(new Font("Times New Roman"), fontSize: 12); // Устанавливаем стандартный для документа шрифт и размер шрифта
                document.MarginLeft   = 42.5f;
                document.MarginTop    = 34.1f;
                document.MarginRight  = 34.1f;
                document.MarginBottom = 34.1f;

                document.InsertParagraph("Приложение 1").Alignment = Alignment.right;
                document.InsertParagraph($"к договору № {contract_num.Text} от {date.Text} г.").Alignment = Alignment.right;

                // создаём таблицу с N строками и 3 столбцами
                Table table = document.AddTable(selected_dir.Count + 2, 3);
                // располагаем таблицу по центру
                table.Alignment = Alignment.center;
                table.AutoFit   = AutoFit.Contents;

                #region Стандартное заполнение
                table.Rows[0].Cells[0].Paragraphs[0].Append("№ п/п").Alignment = Alignment.center;
                table.Rows[0].Cells[1].Paragraphs[0].Append("Направление /специальность").Alignment = Alignment.center;
                table.Rows[0].Cells[2].Paragraphs[0].Append("Курс").Alignment = Alignment.center;

                table.Rows[1].Cells[0].Paragraphs[0].Append("1").Alignment = Alignment.center;
                table.Rows[1].Cells[1].Paragraphs[0].Append("2").Alignment = Alignment.center;
                table.Rows[1].Cells[2].Paragraphs[0].Append("3").Alignment = Alignment.center;
                #endregion

                for (int i = 0; i < selected_dir.Count; i++)
                {
                    Classes.Direction direction = Helper.ODirections.Where(k => k.code.Equals(selected_dir[i])).ElementAt(0);
                    table.Rows[i + 2].Cells[0].Paragraphs[0].Append((i + 1).ToString()).Alignment = Alignment.center;
                    table.Rows[i + 2].Cells[1].Paragraphs[0].Append(direction.code + " " + direction.name).Alignment = Alignment.both;
                    string courses = "";
                    foreach (string course in selected_course[i])
                    {
                        courses += Convert.ToInt32(course.Split()[0]) + ", ";
                    }

                    table.Rows[i + 2].Cells[2].Paragraphs[0].Append(courses.TrimEnd(new char[] { ',', ' ' })).Alignment = Alignment.center;
                }

                document.InsertParagraph().InsertTableAfterSelf(table);

                document.InsertParagraph();
                document.InsertParagraph("Согласовано:");
                document.InsertParagraph();
                Paragraph paragraph1 = document.InsertParagraph("ФГБОУ ВО «СибАДИ»				");
                paragraph1.Append($"__{contract_org.Text}__").UnderlineStyle(UnderlineStyle.singleLine);
                Paragraph paragraph2 = document.InsertParagraph("Ректор		А.П. Жигадло");
                paragraph2.Append("				наименование предприятия, учреждения, организации").Script(Script.superscript).FontSize(10);
                document.InsertParagraph("							____________________________________");
                document.InsertParagraph("							подпись			расшифровка подписи").Script(Script.superscript).FontSize(10);
                document.InsertParagraph("МП							МП");
                document.InsertParagraph("Имеет право подписи").Italic();
                document.InsertParagraph("за руководителя(ректора)").Italic();
                document.InsertParagraph("Проректор по учебной работе");
                document.InsertParagraph("(доверенность № 61 от 29.10.2018)");
                document.InsertParagraph("____________________ С.В. Мельник");

                // сохраняем документ
                document.Save();
            }
            catch (Exception e)
            {
                MessageBox.Show($"Error: {e}", "Error", MessageBoxButton.OK);
                return(false);
            }

            return(true);
        }
        private bool CreateContract()
        {
            try
            {
                string file = $"Договор.docx";
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                // создаём документ
                DocX document = DocX.Create(dir + file);

                document.SetDefaultFont(new Font("Times New Roman"), fontSize: 12); // Устанавливаем стандартный для документа шрифт и размер шрифта
                document.MarginLeft   = 42.5f;
                document.MarginTop    = 34.1f;
                document.MarginRight  = 34.1f;
                document.MarginBottom = 34.1f;

                document.InsertParagraph($"Договор № {contract_num.Text}").Bold().Alignment = Alignment.center;
                document.InsertParagraph("о совместной деятельности при прохождении практики студентами").Bold().Alignment = Alignment.center;
                document.InsertParagraph($"г. Омск									{date.Text} г.").Alignment = Alignment.center;
                Paragraph paragraph1 = document.InsertParagraph();
                paragraph1.Append("\tФедеральное государственное бюджетное образовательное учреждение высшего образования \"Сибирский государственный автомобильно-дорожный университет(СибАДИ)\", ").Italic().Alignment = Alignment.both;
                paragraph1.Append($"именуемое в дальнейшем «Учреждение», в лице ректора Жигадло Александра Петровича, действующего на основании Устава, с одной стороны и, с другой стороны \"{contract_org.Text}\" ");
                paragraph1.Append($"именуемое в дальнейшем «Организация» в лице {contract_empl.Text} действующего на основании ______________, заключили между собой договор о нижеследующем.");

                #region 1 Предмет договора
                document.InsertParagraph("1\tПредмет договора").Bold().Alignment = Alignment.center;
                document.InsertParagraph("\t1.1 Учреждение направляет обучающихся, а Организация предоставляет им места для прохождения всех типов практик (далее – практика) по направлениям (специальностям), указанным в Приложении 1, на базе Организации в соответствии с программами и заданиями.").Alignment = Alignment.both;
                document.InsertParagraph("\t1.2 Для прохождения практики в Организацию направляются обучающиеся, перечень которых является неотъемлемой частью настоящего договора(Приложение 2).").Alignment = Alignment.both;
                document.InsertParagraph("\t1.3 С момента зачисления обучающихся в качестве практикантов на них распространяются правила охраны труда и правила внутреннего трудового распорядка, действующие в Организации.").Alignment = Alignment.both;
                #endregion

                #region 2 Права и обязанности сторон
                document.InsertParagraph("2\tПрава и обязанности сторон").Bold().Alignment = Alignment.center;
                document.InsertParagraph("\t2.2 Организация обязуется").Alignment          = Alignment.both;
                document.InsertParagraph("\t2.1.2   Предоставить рабочие места обучающимся, назначить руководителей практики, определить наставников.").Alignment = Alignment.both;
                document.InsertParagraph("\t2.1.3	Участвовать в определении процедуры оценки результатов освоения общих и профессиональных компетенций, полученных в период прохождения практики, а также оценке таких результатов.").Alignment = Alignment.both;
                document.InsertParagraph("\t2.1.4   Обеспечить безопасные условия прохождения практики, отвечающие санитарным правилам и требованиям охраны труда.").Alignment = Alignment.both;
                document.InsertParagraph("\t2.1.5   Проводить инструктаж обучающихся по ознакомлению с требованиями охраны труда, техники безопасности, пожарной безопасности, а также правилами внутреннего трудового распорядка.").Alignment = Alignment.both;
                document.InsertParagraph("\t2.1.6   Обеспечить обучающихся необходимыми материалами, которые не составляют коммерческую тайну и могут быть использованы при написании выпускных квалификационных работ / курсовых работ(проектов).").Alignment = Alignment.both;
                document.InsertParagraph("\t2.1.7   Уведомлять Учреждение о нарушении обучающимися графика практики, а также правил внутреннего трудового распорядка.").Alignment = Alignment.both;
                document.InsertParagraph("\t2.1.8   По окончании практики выдать каждому обучающемуся отзыв(характеристику) о его работе.").Alignment = Alignment.both;
                document.InsertParagraph("\t2.1.9   Предоставлять возможность повторного направления обучающегося на практику, если он не прошел практику по уважительным причинам.").Alignment = Alignment.both;
                document.InsertParagraph("\t2.1.10  Не привлекать обучающихся к выполнению тяжелых работ с вредными и опасными условиями труда.").Alignment = Alignment.both;
                document.InsertParagraph("\t2.1.11  Несчастные случаи, происшедшие в Организации со студентами Учреждения во время прохождения практики, расследовать комиссией совместно с представителями Учреждения и учитывать в Организации в соответствии с Положением о расследовании и учете несчастных случаев на производстве.").Alignment = Alignment.both;
                document.InsertParagraph("\t2.1.12  Не менее чем за один месяц до начала практики сообщить в письменном виде об отказе о предоставлении мест проведения практики студентов.").Alignment = Alignment.both;
                document.InsertParagraph("\t2.2 Организация имеет право:").Alignment = Alignment.both;
                document.InsertParagraph("\t2.2.1   Не допускать обучающегося к прохождению практики в случае выявления фактов нарушения им правил внутреннего трудового распорядка, охраны труда, техники безопасности, а также в иных случаях нарушения условий настоящего договора обучающимся или Учреждением.").Alignment = Alignment.both;
                document.InsertParagraph("\t2.3 Учреждение обязуется:").Alignment = Alignment.both;
                document.InsertParagraph("\t2.3.1   Направить в Организацию студентов в сроки, предусмотренные графиком учебного процесса.").Alignment = Alignment.both;
                document.InsertParagraph("\t2.3.2   Определять совместно с Организацией процедуру оценки общих и профессиональных компетенций обучающихся, освоенных ими в ходе прохождения практики.").Alignment = Alignment.both;
                document.InsertParagraph("\t2.3.3   Назначать в качестве руководителей практики от Учреждения квалифицированных сотрудников из числа научно-педагогических работников Учреждения.").Alignment     = Alignment.both;
                document.InsertParagraph("\t2.3.4   Оказывать руководителям практики студентов от Организации методическую помощь в проведении всех видов практики.").Alignment = Alignment.both;
                document.InsertParagraph("\t2.3.5   Принимать участие в работе комиссии Организации по расследованию несчастных случаев с обучающимися.").Alignment             = Alignment.both;
                document.InsertParagraph("\t2.4 Учреждение имеет право:").Alignment = Alignment.both;
                document.InsertParagraph("\t2.4.1   При непредставлении обучающемуся рабочего места и работ, отвечающих требованиям учебных программ специальности(направления), необеспечении условий безопасности труда, а также при использовании труда обучающегося на сторонних или подсобных работах отозвать обучающегося с места практики").Alignment = Alignment.both;
                #endregion

                #region 3 Ответственность
                document.InsertParagraph("3\tОтветственность").Bold().Alignment = Alignment.center;
                document.InsertParagraph("\t3.1 Стороны несут ответственность за неисполнение или ненадлежащее исполнение обязанностей по настоящему договору в соответствии с действующим законодательством Российской Федерации.").Alignment = Alignment.both;
                document.InsertParagraph("\t3.2 Ответственность за вред, который может наступить вследствие разглашения обучающимся конфиденциальной информации Организации, а также за нарушение интеллектуальных, авторских и иных неимущественных прав несет обучающийся.").Alignment = Alignment.both;
                document.InsertParagraph("\t3.3 Неисполнение условий настоящего пункта влечет для Сторон обязанность по возмещению убытков, связанных с неисполнением условий настоящего договора.").Alignment = Alignment.both;
                #endregion

                #region 4 Заключительные положения
                document.InsertParagraph("4\tЗаключительные положения").Bold().Alignment = Alignment.center;
                document.InsertParagraph("\t4.1 Настоящий договор составлен и подписан в двух аутентичных экземплярах - по одному для каждой Стороны.").Alignment = Alignment.both;
                document.InsertParagraph("\t4.2 Договор вступает в силу с момента подписания и действует до 31.12.2024 г.").Alignment = Alignment.both;
                document.InsertParagraph("\t4.3 Если до окончания срока действия настоящего договора ни одна из Сторон не заявит о прекращении действия договора, необходимости внесения в договор изменений и/ или дополнений, о необходимости заключения нового договора на иных условиях, настоящий договор считается продленным(пролонгированным) на _1 г.на прежних условиях.").Alignment = Alignment.both;
                document.InsertParagraph("\t4.4 Во всем остальном, что не предусмотрено настоящим договором, Стороны руководствуются действующим законодательством Российской Федерации.").Alignment = Alignment.both;
                #endregion

                #region 5 Реквизиты и подписи сторон
                document.InsertParagraph("5\tРеквизиты и подписи сторон").Bold().Alignment = Alignment.center;

                document.InsertParagraph("Учреждение: 644080, г.Омск, пр.Мира, 5		Организация:__________________________").Alignment = Alignment.both;
                document.InsertParagraph("ФГБОУ ВО «СибАДИ»				_______________________________________").Alignment                  = Alignment.both;
                document.InsertParagraph("тел.: 72 - 94 - 97					_______________________________________").Alignment                = Alignment.both;
                document.InsertParagraph("Ректор 		А.П.Жигадло			________________ / _____________________ /").Alignment             = Alignment.both;
                document.InsertParagraph("							подпись				расшифровка подписи").Script(Script.superscript).FontSize(10).Alignment = Alignment.both;
                document.InsertParagraph("МП								МП").FontSize(11).Alignment = Alignment.both;
                document.InsertParagraph("Имеет право подписи за руководителя(ректора)").FontSize(10).Alignment = Alignment.both;
                document.InsertParagraph("Проректор по учебной работе").FontSize(10).Alignment       = Alignment.both;
                document.InsertParagraph("(доверенность № 61 от 29.10.2018)").FontSize(10).Alignment = Alignment.both;
                document.InsertParagraph("______________ / С.В.Мельник /").Alignment = Alignment.both;

                document.InsertParagraph("Начальник отдела организации практики").FontSize(10).Alignment    = Alignment.both;
                document.InsertParagraph("и содействия трудоустройству выпускников").FontSize(10).Alignment = Alignment.both;
                document.InsertParagraph("______________ / Ю.С.Сачук /").Alignment = Alignment.both;
                document.InsertParagraph("Заведующий выпускающей кафедрой").FontSize(10).Alignment = Alignment.both;
                document.InsertParagraph("«_Прикладная инфрматика в экономике»").Alignment         = Alignment.both;
                document.InsertParagraph("______________ / Л.И.Остринская /").Alignment            = Alignment.both;
                document.InsertParagraph("подпись         расшифровка подписи").Script(Script.superscript).FontSize(10).Alignment = Alignment.both;
                #endregion

                if (CreateContract_Attch1() == false)
                {
                    return(false);
                }
                if (CreateContract_Attch2() == false)
                {
                    return(false);
                }

                SQLiteAdapter.DeleteRowById("contracts", $"[id]='{sel_items.id}'");
                // Добавляем данные в БД
                SQLiteAdapter.SetValue("contracts", contract_num.Text,
                                       $"{date.Text}",
                                       contract_org.Text,
                                       contract_empl.Text,
                                       form_pract.SelectedItem.ToString(),
                                       type_pract.Text);
                // сохраняем документ
                document.Save();
            }
            catch (Exception e)
            {
                SQLiteAdapter.DeleteRowById("contracts", $"[id]='{contract_num.Text}'");
                SQLiteAdapter.DeleteRowById("attach", $"[id_contract]='{contract_num.Text}'");
                MessageBox.Show($"Error: {e}", "Error", MessageBoxButton.OK);
                return(false);
            }

            return(true);
        }
Пример #11
0
        public ActionResult Contract(int?id)
        {
            if (!User.Identity.IsAuthenticated)
            {
                return(Redirect("/Account/Login"));
            }
            Contract contract = db.Contracts
                                .Include(a => a.Service)
                                .Include(a => a.Administrator)
                                .Include(a => a.Customer)
                                .Include(a => a.Service.Aircraft)
                                .Include(a => a.Service.Aircraft.Base)
                                .First(a => a.Id == id);

            using (MemoryStream ms = new MemoryStream())
            {
                string   ContractID       = contract.Id.ToString();
                string   nameClient       = contract.Customer.Name;
                string   nameStaff        = contract.Administrator.Name;
                string   RegistrationNum  = contract.Service.Aircraft.RegistrationNumber;
                string   Manufacturer     = contract.Service.Aircraft.Manufacturer;
                string   Service          = contract.Service.Name;
                DateTime DateOfSigning    = contract.ContractSignDate;
                DateTime DateOfStart      = contract.ContractStartDate;
                DateTime DateOfCompletion = contract.ContractFinishDate;
                string   sum       = contract.TotalCost.ToString();
                string   cost      = contract.Service.Price.ToString();
                string   PostIndex = contract.Service.Aircraft.Base.PostIndex;
                string   City      = contract.Service.Aircraft.Base.City;
                string   Address   = contract.Service.Aircraft.Base.Adress;

                // создаём документ
                DocX document = DocX.Create(ms);
                document.SetDefaultFont(new Xceed.Document.NET.Font("Times New Roman"), 12);
                document.MarginLeft   = 85;
                document.MarginTop    = 56.7f;
                document.MarginBottom = 56.7f;
                document.MarginRight  = 42.5f;
                // Вставляем параграф и указываем текст
                Paragraph text = document.InsertParagraph();
                document.InsertParagraph($"Клієнтський договір № {ContractID}").Bold().
                Alignment = Alignment.center;
                document.InsertParagraph($"Місто {City}\t\t\t\t\t\t\t\t{DateOfSigning.Date.ToString().Substring(0, 10)} рік");
                // вставляем параграф и добавляем текст
                Paragraph firstParagraph = document.InsertParagraph();
                // выравниваем параграф по правой стороне
                firstParagraph.Alignment = Alignment.both;
                firstParagraph.AppendLine("Авіа-клуб «Student Aero», що являється платником податку на загальних підставах " +
                                          $"в особі {nameClient} (надалі іменується Замовник) з однієї сторони, та Авіа-клуб «Student Aero» " +
                                          $"(надалі іменується Виконавець) в особі {nameStaff}, діючого на підставі  " +
                                          "№20037808 від 01.11.2018, з іншої сторони, заключили даний Договір про нижче наведене:");
                document.InsertParagraph("\n1. Предмет договору.").Bold().Alignment = Alignment.center;
                document.InsertParagraph("1.1. За даним Договором Виконавець за плату та за завданням Замовника " +
                                         "зобов’язується надати комплекс послуг з організації спортивно-розважального заходу, а саме заходу на " +
                                         $"повітряному судні.").Alignment = Alignment.both;
                //document.InsertParagraph("\n2. Права та обов’язки сторін.").Bold().Alignment = Alignment.center;
                document.InsertParagraph("\n2. Права та обов’язки сторін.").Bold().Alignment = Alignment.center;
                document.InsertParagraph("2.1. Для виконання даного Договору Виконавець зобов’язується організувати " +
                                         $"спортивно-розважальні послуги на повітряному судні «{RegistrationNum} {Manufacturer}» {DateOfStart.Date.ToString().Substring(0, 10)} року " +
                                         $"до {DateOfCompletion.Date.ToString().Substring(0, 10)} року " +
                                         $"в місці зустрічі на авіабазі {PostIndex} м. {City}, {Address}").Alignment = Alignment.both;
                document.InsertParagraph("2.2.Для виконання даного Договору Замовник зобов’язується:\n" +
                                         "2.2.1. Під час здійснення прогулянкового польоту не допускати використання особами, " +
                                         "що знаходяться на судні під відповідальність Замовника(своїми клієнтами, співробітниками " +
                                         "та іншими залученими їм особами), судна в цілях, що не відповідають призначенню поїздки та / " +
                                         "або несуть ризик псування або пошкодження судна та / або майна, що на ньому знаходиться;").Alignment = Alignment.both;
                document.InsertParagraph("2.2.2. Виконувати та забезпечити виконання особами, що знаходяться на судні " +
                                         "під відповідальність Замовника, правил пожежної безпеки, охорони праці, норм і правил санітарії, " +
                                         "інших загальнообов’язкових правил та норм поведінки, а також спеціальних (внутрішніх) вимог " +
                                         "безпеки під час перебування на даному судні, так само як і законних, розумних та обґрунтованих " +
                                         "вимог старшого на судні;\n" +
                                         "2.2.3. Про всі інциденти та / або нестандартні ситуації, та / або надзвичайні події, " +
                                         "що загрожують життю та здоров’ю людей і збереженню майна, в тому числі третіх осіб, " +
                                         "негайно інформувати старшого на судні та представника Виконавця, а також приймати посильні " +
                                         "заходи для їх попередження, не піддаючи себе при цьому ризику.\n" +
                                         "2.3. Сторони мають право вимагати одна від одної добросовісного виконання прийнятих зобов’язань.\n").Alignment = Alignment.both;
                document.InsertParagraph("3. Вартість послуг та порядок розрахунків.").Bold().Alignment = Alignment.center;
                document.InsertParagraph("3.1. Загальна вартість послуг, що надаються згідно даного " +
                                         $"договору становить: {sum} грн., в тому числі: {Service} становить {cost} грн.").Alignment = Alignment.both;
                document.InsertParagraph("3.2. Розрахунки між сторонами здійснюються в усній формі.\n").Alignment       = Alignment.both;
                document.InsertParagraph("4. Відповідальність сторін та порядок вирішення суперечок.").Bold().Alignment = Alignment.center;
                document.InsertParagraph("4.1. За порушення зобов’язань, що витікають з умов даного Договору, " +
                                         "сторони несуть відповідальність, передбачену чинним законодавством України. При цьому винна " +
                                         "Сторона зобов’язана відшкодувати іншій Стороні завдані цим збитки.\n" +
                                         "4.2. Усі суперечності та спори, що виникли з даного Договору чи в зв’язку з ним, " +
                                         "вирішуються шляхом проведення переговорів представниками сторін. У випадку неможливості " +
                                         "досягнення згоди суперечка передається на розгляд до суду у відповідності з правилами " +
                                         "підвідомчості і підсудності, встановленими чинним законодавством України. Дотримання " +
                                         "досудового(претензійного) порядку врегулювання спорів являється для Сторін обов’язковим.\n" +
                                         "4.3. Замовник несе майнову відповідальність за шкоду, завдану ним або іншими особами на судні " +
                                         "під відповідальність Замовника, майну Виконавця, або третіх осіб.\n" +
                                         "4.4. У випадку порушення Замовником п. 3.2 Договору та зриву(відміни) в зв’язку з цим " +
                                         "спортивно-розважального заходу на повітряному судні, вартість бронювання спортивно-розважального заходу на " +
                                         "повітряному судні згідно п.2.1 не повертається. Можливість подальшого виконання Договору " +
                                         "обговорюється Сторонами шляхом укладання Додаткового погодження до Договору.\n").Alignment = Alignment.both;
                document.InsertParagraph("5. Термін дії, обставини форс-мажор та інші умови Договору.").Bold().Alignment             = Alignment.center;
                document.InsertParagraph("5.1. Даний договір набуває чинності з моменту початку спортивно-розважального заходу та діє до " +
                                         "моменту його завершення.\n" +
                                         "5.2. Одностороння зміна умов або відмова від Договору не допускається.\n" +
                                         "5.3. Сторони звільняються від відповідальності за порушення Договору у випадку дії обставин " +
                                         "непереборної сили(форс - мажор), які трапилися не по їх волі та перешкоджають виконанню " +
                                         "Договору. Такими обставинами є: війна та військові дії, повстання, страйки, локаути, масові " +
                                         "заворушення, ембарго, обмеження подачі електроенергії та енергоносіїв, епідемії, пожежі, " +
                                         "вибухи, природні катастрофи, дорожні пригоди.\n" +
                                         "5.4. Даний Договір складений і укладений при повному розумінні Сторонами його умов " +
                                         "українською мовою на двох сторінках у двох примірниках рівної юридичної сили по одному для " +
                                         "кожної із Сторін.\n\n\n").Alignment = Alignment.both;
                document.InsertParagraph("______________/__________________      ______________/__________________").Alignment = Alignment.both;
                document.InsertParagraph("М.П.                        М.П. ").Alignment = Alignment.both;
                document.InsertParagraph($"\n\n\n\n\nДата друку: {DateTime.Today.ToString().Substring(0, 10)}").Alignment = Alignment.right;
                document.Save();

                Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                Response.AddHeader("content-disposition",
                                   "attachment;filename=Contract №" + ContractID + ".docx");
                Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
            }

            return(null);

            /*if (!User.Identity.IsAuthenticated) return Redirect("/Account/Login");
             * if (id == null)
             * {
             *  return HttpNotFound();
             * }
             * Contract contract = db.Contracts
             *  .Include(a => a.Service)
             *  .Include(a => a.Administrator)
             *  .Include(a => a.Customer)
             *  .Include(a => a.Service.Aircraft)
             *  .Include(a => a.Service.Aircraft.Base)
             *  .First(a => a.Id == id);
             * string ttf = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIAL.TTF");
             * var baseFont = BaseFont.CreateFont(ttf, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
             * var font = new iTextSharp.text.Font(baseFont, iTextSharp.text.Font.DEFAULTSIZE, iTextSharp.text.Font.NORMAL);
             * using (MemoryStream ms = new MemoryStream())
             * {
             *  Document document = new Document(PageSize.A4, 25, 25, 30, 30);
             *
             *  PdfWriter writer = PdfWriter.GetInstance(document, ms);
             *  document.Open();
             *
             *  document.Add(new Paragraph("Акт наданих послуг", font));
             *  document.Add(new Paragraph("до договору від від " + contract.ContractSignDate + " №" + contract.Id, font));
             *  document.Add(new Paragraph("м. " + contract.Service.Aircraft.Base.City + "                    " + contract.ContractSignDate, font));
             *  document.Add(new Paragraph("Сторона, що надає послуги, ООО\"Студентавиклуб\" в особі адміністратора " + contract.Administrator.Name + ", який діє на підставі статусу, та сторона, що отримує послуги, фізичне лицо " + contract.Customer.Name + ", склали цей Акт про те, що послуги з найменуванням \"" + contract.Service.Name + "\" одиниці авіатехніки класу \"" + contract.Service.Aircraft.Class + "\", моделі " + contract.Service.Aircraft.Model + ", реєстраційний номер " + contract.Service.Aircraft.RegistrationNumber + " для часного використання надані в повному обсязі відповідно до Договору.", font));
             *  document.Add(new Paragraph("Загальна вартість послуг, наданих у період із " + contract.ContractStartDate + " по " + contract.ContractFinishDate + ", становить " + contract.TotalCost + " грн.", font));
             *  document.Add(new Paragraph("Сторони претензій одна до одної не мають.", font));
             *  document.Add(new Paragraph("Цей Акт складено у двох примірниках, що мають однакову силу, по одному для кожної зі Сторін.", font));
             *  document.Add(new Paragraph("Сторона, що надає послуги:____________________________                                                Сторона, що отримує послуги:__________________________", font));
             *  document.Add(new Paragraph("Дата:" + contract.ContractSignDate, font));
             *
             *  document.Close();
             *  writer.Close();
             *  Response.ContentType = "pdf/application";
             *  Response.AddHeader("content-disposition",
             *  "attachment;filename=Contract" + id + ".pdf");
             *  Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
             * }
             * return null;*/
        }
Пример #12
0
 public void OpenBlank(Exam exam, Ticket ticket, bool markAnswers)
 {
     CloseWord();
     using (DocX docXdocument = DocX.Create(path.ToString()))
     {
         int i, j;
         docXdocument.AddFooters();
         docXdocument.SetDefaultFont(new Xceed.Document.NET.Font("Times New Roman"), 14);
         Xceed.Document.NET.Paragraph headerParagraph = docXdocument.InsertParagraph();
         Xceed.Document.NET.Paragraph paragraph       = docXdocument.InsertParagraph();
         headerParagraph.Append($"Виконання завдань")
         .Bold()
         .FontSize(16);
         paragraph = docXdocument.InsertParagraph();
         paragraph.Append($"Здобувач освіти")
         .Bold()
         .Append("\t\t\t\t\t\t\t")
         .UnderlineStyle(UnderlineStyle.singleLine)
         .Append("білет №")
         .Bold()
         .Append("\t\t")
         .UnderlineStyle(UnderlineStyle.singleLine);
         paragraph = docXdocument.InsertParagraph();
         paragraph.Append($"{Environment.NewLine}I частина")
         .Bold()
         .Alignment = Alignment.center;
         paragraph  = docXdocument.InsertParagraph();
         paragraph.Append($"\tОзнайомтесь з тестовим завданням. Дайте відповіді на тестові завдання в таблиці" +
                          $"(поряд із номером запитання зазначте номер правильної відповіді){Environment.NewLine}")
         .Alignment = Alignment.left;
         List <OneAnswerQuestion[]> questionLists = new List <OneAnswerQuestion[]>();
         for (i = 0; i < exam.Themes.Count; i++)
         {
             OneAnswerQuestion[] questions = exam.Themes[i].GetQuestions(ticket).Cast <OneAnswerQuestion>().ToArray();
             Array.Sort(questions,
                        (Question a, Question b) =>
             {
                 if (a.QuestionNumber > b.QuestionNumber)
                 {
                     return(1);
                 }
                 else if (a.QuestionNumber < b.QuestionNumber)
                 {
                     return(-1);
                 }
                 return(0);
             });
             questionLists.Add(questions);
         }
         int max = questionLists.Max(a => a.Length);
         Xceed.Document.NET.Table table = docXdocument.AddTable(max + 1, questionLists.Count * 2);
         table.SetBorder(TableBorderType.Bottom, new Xceed.Document.NET.Border(BorderStyle.Tcbs_double, BorderSize.two, 0, Color.Black));
         table.SetBorder(TableBorderType.Top, new Xceed.Document.NET.Border(BorderStyle.Tcbs_double, BorderSize.two, 0, Color.Black));
         table.SetBorder(TableBorderType.Left, new Xceed.Document.NET.Border(BorderStyle.Tcbs_double, BorderSize.two, 0, Color.Black));
         table.SetBorder(TableBorderType.Right, new Xceed.Document.NET.Border(BorderStyle.Tcbs_double, BorderSize.two, 0, Color.Black));
         List <float> percentages = new List <float>();
         float        pa          = 30 / (table.ColumnCount / 2);
         float        pb          = 70 / (table.ColumnCount / 2);
         for (i = 0; i < table.ColumnCount / 2; i += 2)
         {
             table.Rows[0].MergeCells(i, i + 1);
             percentages.Add(pa);
             percentages.Add(pb);
             i--;
         }
         table.SetWidthsPercentage(percentages.ToArray(), docXdocument.PageWidth - docXdocument.PageWidth / 5);
         for (i = 0; i < exam.Themes.Count; i++)
         {
             table.Rows[0].Cells[i].InsertParagraph()
             .Append(exam.Themes[i].ThemeName)
             .Alignment = Alignment.center;
         }
         for (i = 0; i < table.ColumnCount / 2; i++)
         {
             for (j = 0; j < questionLists[i].Length; j++)
             {
                 table.Rows[1 + j].Cells[i * 2].InsertParagraph()
                 .Append($"{questionLists[i][j].QuestionNumber + exam.FirstQuestionNumber}");
                 if (markAnswers)
                 {
                     int index = questionLists[i][j].QuestionContent.Answers.IndexOf(questionLists[i][j].Answer.Content);
                     table.Rows[1 + j].Cells[i * 2 + 1].InsertParagraph()
                     .Append(index >= 0 && index < questionLists[i][j].QuestionContent.Letters.Length ? questionLists[i][j].QuestionContent.Letters[index].ToString() : "*");
                 }
             }
         }
         docXdocument.InsertTable(table);
         paragraph = docXdocument.InsertParagraph();
         paragraph.Append($"{Environment.NewLine}{Environment.NewLine}Балл: ")
         .Bold()
         .Alignment = Alignment.right;
         if (!markAnswers)
         {
             paragraph.Append("\t\t")
             .UnderlineStyle(UnderlineStyle.singleLine)
             .Alignment = Alignment.right;
         }
         else
         {
             paragraph.Append($"{ticket.MaxPoints:F2}")
             .UnderlineStyle(UnderlineStyle.singleLine)
             .Alignment = Alignment.right;
         }
         docXdocument.Footers.Odd.InsertParagraph()
         .Append("Створено за допомогою SimplEx Program")
         .FontSize(10)
         .UnderlineStyle(UnderlineStyle.singleLine)
         .Alignment = Xceed.Document.NET.Alignment.right;
         docXdocument.Save();
     }
     OpenWord();
 }