Example #1
0
        public static void AddImage(System.Drawing.Image theImage, string headingText, string pptHeader)
        {
            string    cleanedHeaderText = CleanInvalidXmlChars(headingText).Replace(" ", "");
            Paragraph para = _doc.Paragraphs.FirstOrDefault(x => CleanInvalidXmlChars(x.Text).Replace(" ", "").Contains(cleanedHeaderText));

            //Paragraph para = _doc.Paragraphs.FirstOrDefault(x => x.Text.Contains(headingText));
            if (para == null || string.IsNullOrWhiteSpace(para.Text))
            {
                cleanedHeaderText = CleanInvalidXmlChars(pptHeader).Replace(" ", "");
                para = _doc.Paragraphs.FirstOrDefault(x => CleanInvalidXmlChars(x.Text).Replace(" ", "").Contains(pptHeader));

                if (para == null || string.IsNullOrWhiteSpace(para.Text))
                {
                    return;
                }
            }


            using (MemoryStream ms = new MemoryStream())
            {
                try
                {
                    theImage.Save(ms, ImageFormat.Png);    //theImage.Save(ms, theImage.RawFormat);  // Save your picture in a memory stream.
                }
                catch
                {
                    try
                    {
                        theImage.Save(ms, theImage.RawFormat);
                    }
                    catch
                    {
                        try
                        {
                            theImage.Save(ms, ImageFormat.MemoryBmp);
                        }
                        catch
                        {
                            try
                            {
                                theImage.Save(ms, ImageFormat.Jpeg);
                            }
                            catch
                            {
                                try
                                {
                                    theImage.Save(ms, ImageFormat.Bmp);
                                }
                                catch
                                {
                                    try
                                    {
                                        theImage.Save(ms, ImageFormat.Gif);
                                    }
                                    catch (Exception ex)
                                    {
                                        throw ex;
                                    }
                                }
                            }
                        }
                    }
                }

                ms.Seek(0, SeekOrigin.Begin);

                var image = _doc.AddImage(ms);
                var pic   = image.CreatePicture();

                //Calculate Horizontal and Vertical scale
                float Hscale = ((float)96 / theImage.HorizontalResolution);
                float Vscale = ((float)96 / theImage.VerticalResolution);

                //Apply scale to height & width
                pic.Height = (int)(theImage.Height / 2 * Hscale);
                pic.Width  = (int)(theImage.Width / 2 * Vscale);


                //pic.SetPictureShape(BasicShapes.cube);
                var picPara = para.AppendLine();
                picPara.AppendPicture(pic);
                //para.InsertParagraphAfterSelf(picPara);
                //AddBlankLine();
                //var picPara = AddBlankLine();
                // picPara.InsertPicture(pic, 0);//.Pictures.Insert(0, pic);
            }
        }
Example #2
0
        /// <summary>
        /// Insert Word Results for each step --> Support Method
        /// </summary>
        /// <param name="StepName">Name of the step</param>
        /// <param name="Stepdescription">Description of the step</param>
        /// <param name="Stepstatus">Status of the step</param>
        /// <param name="img">Step image</param>
        public static void InsertWordResults(string StepName, Status Stepstatus)
        {
            try
            {
                Paragraph title1 = resultdocument.InsertParagraph().Append("Step Name: " + StepName).FontSize(12).Font("Calibri").Color(System.Drawing.Color.FromArgb(0, 0, 0));

                Paragraph title2 = null;
                Paragraph title3 = null;

                switch (Stepstatus)
                {
                case Status.Pass:
                    title2 = resultdocument.InsertParagraph().Append("Step Status: Passed").FontSize(12).Font("Calibri").Color(System.Drawing.Color.FromArgb(52, 168, 83));
                    break;

                case Status.Warning:
                    title2 = resultdocument.InsertParagraph().Append("Step Status: Warning").FontSize(12).Font("Calibri").Color(System.Drawing.Color.FromArgb(251, 188, 5));
                    break;

                case Status.Fail:
                    title2 = resultdocument.InsertParagraph().Append("Step Status: Failed").FontSize(12).Font("Calibri").Color(System.Drawing.Color.FromArgb(234, 67, 53));
                    title3 = resultdocument.InsertParagraph().Append("Error Message: " + Reports.errorMessage).FontSize(12).Font("Calibri").Color(System.Drawing.Color.FromArgb(234, 67, 53));
                    break;

                case Status.Information:
                    title2 = resultdocument.InsertParagraph().Append("Step Status: Information").FontSize(12).Font("Calibri").Color(System.Drawing.Color.FromArgb(0, 0, 225));
                    break;

                case Status.Error:
                    title2 = resultdocument.InsertParagraph().Append("Step Status: Error").FontSize(12).Font("Calibri").Color(System.Drawing.Color.FromArgb(234, 67, 53));
                    break;

                case Status.Skip:
                    title2 = resultdocument.InsertParagraph().Append("Step Status: Skip").FontSize(12).Font("Calibri").Color(System.Drawing.Color.FromArgb(102, 225, 178));
                    break;
                }

                title1.Alignment = Alignment.left;
                Paragraph step = resultdocument.InsertParagraph();
                step.AppendLine();
                if (!string.IsNullOrEmpty(Reports.runtimescnshtpath))
                {
                    string WordImg = Reports.getCurrentTestRunPath + Reports.runtimescnshtpath.Replace("..", "");
                    Image  image   = resultdocument.AddImage(WordImg);

                    Picture picture = image.CreatePicture();
                    picture.Width  = 600;
                    picture.Height = 330;
                    step.AppendPicture(picture);
                }
                if (temp > 1)
                {
                    for (int i = 0; i <= 4; i++)
                    {
                        step.AppendLine();
                        resultdocument.Save();
                    }
                    temp = 1;
                }
                else
                {
                    step.AppendLine();
                    resultdocument.Save();
                    temp = temp + 1;
                }
            }
            catch (Exception e)
            {
                Reports.SetupErrorLog(e);
            }
        }
        /// <summary>
        /// Writes given inputs into a document.
        /// </summary>
        /// <param name="input">Inputs</param>
        /// <param name="document">Word document</param>
        /// <param name="tractID">Selected tractID</param>
        private void WriteInputs(ReportingAssesmentInputParams input, DocX document)
        {
            string paragraph = input.SelectedTractCombination;

            document.InsertParagraph(paragraph).FontSize(16).Bold().Alignment = Alignment.center;
            if (File.Exists(input.TractImageFile))
            {
                var p = document.InsertParagraph("");
                p.Alignment = Alignment.center;
                var image   = document.AddImage(input.TractImageFile);
                var picture = image.CreatePicture();
                // Check if the image is too big.
                if (picture.Height > 670 || picture.Width > 600)
                {
                    // Shrinks the image so that it retains right proportions.
                    while (picture.Height > 670 || picture.Width > 600)
                    {
                        picture.Height = picture.Height - 10;
                        picture.Width  = picture.Width - 7;
                    }
                }
                p.AppendPicture(picture);
                p.SpacingBefore(50);
                p.SpacingAfter(10);
            }
            Paragraph severalParagraphs = document.InsertParagraph("Figure 1. ").Bold();

            severalParagraphs.Append("Location of tract " + input.SelectedTractCombination + ".");
            document.InsertParagraph().InsertPageBreakAfterSelf();
            //paragraph = input.DepositType + " ASSESMENT FOR TRACT " + "\'" + input.SelectedTract + "\' " + input.Country + "\r\n";
            //document.InsertParagraph(paragraph).FontSize(16).Bold();
            paragraph = input.AssesmentTitle + "\r\n";
            document.InsertParagraph(paragraph).FontSize(16).Bold();
            paragraph = input.Authors + "\r\n";
            document.InsertParagraph(paragraph).FontSize(11);
            paragraph = "Deposit type: " + input.DepositType;
            document.InsertParagraph(paragraph).FontSize(11);
            paragraph = "Descriptive model: " + input.DescModelName;
            document.InsertParagraph(paragraph).FontSize(11);
            paragraph = "Grade-tonnage model: " + input.GTModelName + "\r\n";

            document.InsertParagraph(paragraph).FontSize(11);
            paragraph = "List of permissive tracts:";//tracts included in the assessment:";
            document.InsertParagraph(paragraph).FontSize(11);
            string tractFile = Path.Combine(input.Env.RootPath, "TractDelineation", "Tracts", input.SelectedTractCombination, "TractsAggregated.csv");

            if (File.Exists(tractFile))
            {
                string   tractText = File.ReadAllText(tractFile);
                string[] tractList = tractText.Split(',');
                foreach (var tract in tractList)
                {
                    paragraph = tract;
                    document.InsertParagraph(paragraph).FontSize(11);
                }
            }
            paragraph = "\r\n\r\n";
            document.InsertParagraph(paragraph).FontSize(11);
            paragraph = "Assessment date: " + input.AsDate;
            document.InsertParagraph(paragraph).FontSize(11);
            paragraph = "Assessment depth: " + input.AsDepth;
            document.InsertParagraph(paragraph).FontSize(11);
            paragraph = "Assessment team leader: " + input.AsLeader;
            document.InsertParagraph(paragraph).FontSize(11);
            paragraph = "Assessment team members: " + input.AsTeamMembers + "\r\n";

            document.InsertParagraph(paragraph);
            paragraph = "Estimated number of undiscovered deposits" + "\r\n";
            document.InsertParagraph(paragraph).FontSize(14).Bold();
        }
Example #4
0
        private void InsertPicture(Paragraph paragraphToInsert, ObservableCollection <Picture> pictures)
        {
            Table picTable = paragraphToInsert.InsertTableAfterSelf(1, 2);

            picTable.AutoFit   = AutoFit.Window;
            picTable.Alignment = Alignment.left;

            foreach (var p in pictures)
            {
                p.CreatePicture();
            }

            var i = 0;

            while (i < pictures.Count)
            {
                Xceed.Words.NET.Image   img = _templateDocx.AddImage(pictures[i].FullPath);
                Xceed.Words.NET.Picture p   = img.CreatePicture();

                //非手機圖
                if (!IsCellPhoneScreenshot(pictures[i]))
                {
                    var row = picTable.InsertRow();
                    row.MergeCells(0, 1);

                    var row2 = picTable.InsertRow();
                    row2.MergeCells(0, 1);

                    //按照比例縮小圖片,如圖片不足600寬,則保留原大小
                    ResizePicture(pictures[i], 600, out var width, out var height);
                    p.Width  = width;
                    p.Height = height;

                    //新增table放圖片
                    row.Cells[0].Paragraphs.First().Append(pictures[i].Caption).Font(Font);
                    row2.Cells[0].Paragraphs.First().InsertPicture(p);

                    if (i == pictures.Count - 1)
                    {
                        break;
                    }

                    i++;
                }

                //第一張手機圖
                else
                {
                    //最後一張圖
                    if (i == pictures.Count - 1)
                    {
                        var row = picTable.InsertRow();
                        row.MergeCells(0, 1);

                        var row2 = picTable.InsertRow();
                        row2.MergeCells(0, 1);

                        //按照比例縮小圖片,如圖片不足200寬,則保留原大小
                        ResizePicture(pictures[i], 200, out var width, out var height);
                        p.Width  = width;
                        p.Height = height;

                        //新增table放圖片
                        row.Cells[0].Paragraphs.First().Append(pictures[i].Caption).Font(Font);
                        row2.Cells[0].Paragraphs.First().InsertPicture(p);

                        break;
                    }
                    //下一張不是手機圖
                    if (!IsCellPhoneScreenshot(pictures[i + 1]))
                    {
                        var row = picTable.InsertRow();
                        row.MergeCells(0, 1);

                        var row2 = picTable.InsertRow();
                        row2.MergeCells(0, 1);

                        //按照比例縮小圖片,如圖片不足200寬,則保留原大小
                        ResizePicture(pictures[i], 200, out var width, out var height);
                        p.Width  = width;
                        p.Height = height;

                        //新增table放圖片
                        row2.Cells[0].Paragraphs.First().InsertPicture(p);
                        row.Cells[0].Paragraphs.First().Append(pictures[i].Caption).Font(Font);

                        i++;
                    }

                    //下一張也是手機圖
                    else
                    {
                        Xceed.Words.NET.Image   img2 = _templateDocx.AddImage(pictures[i + 1].FullPath);
                        Xceed.Words.NET.Picture p2   = img2.CreatePicture();

                        var row  = picTable.InsertRow();
                        var row2 = picTable.InsertRow();


                        //按照比例縮小圖片,如圖片不足200寬,則保留原大小
                        ResizePicture(pictures[i], 200, out var width, out var height);
                        p.Width  = width;
                        p.Height = height;

                        ResizePicture(pictures[i + 1], 200, out var width2, out var height2);
                        p2.Width  = width2;
                        p2.Height = height2;

                        //新增table放圖片
                        row.Cells[0].Paragraphs.First().Append(pictures[i].Caption).Font(Font);
                        row2.Cells[0].Paragraphs.First().InsertPicture(p);

                        row.Cells[1].Paragraphs.First().Append(pictures[i + 1].Caption).Font(Font);
                        row2.Cells[1].Paragraphs.First().InsertPicture(p2);

                        i += 2;
                    }
                }
            }
            picTable.RemoveRow(0);
            picTable.InsertParagraphAfterSelf("\r\n");

            foreach (var p in pictures)
            {
                p.ReleasePictureResource();
            }
        }
        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 }));
        }
Example #6
0
        /// <summary>
        /// Create a file and add a picture, a table, an hyperlink, paragraphs, a bulleted list and a numbered list.
        /// </summary>
        public static void CreateRecipe()
        {
            Console.WriteLine("\tCreateRecipe()");

            // Create a new document.
            using (DocX document = DocX.Create(MiscellaneousSample.MiscellaneousSampleOutputDirectory + @"CreateRecipe.docx"))
            {
                // Create a rotated picture from existing image.
                var image   = document.AddImage(MiscellaneousSample.MiscellaneousSampleResourcesDirectory + @"cupcake.png");
                var picture = image.CreatePicture();
                picture.Rotation = 20;

                // Create an hyperlink.
                var hyperlink = document.AddHyperlink("Food.com", new Uri("http://www.food.com/recipe/simple-vanilla-cupcakes-178370"));

                // Create a bulleted list for the ingredients.
                var bulletsList = document.AddList("2 cups of flour", 0, ListItemType.Bulleted);
                document.AddListItem(bulletsList, "3⁄4 cup of sugar");
                document.AddListItem(bulletsList, "1⁄2 cup of butter");
                document.AddListItem(bulletsList, "2 eggs");
                document.AddListItem(bulletsList, "1 cup of milk");
                document.AddListItem(bulletsList, "2 teaspoons of baking powder");
                document.AddListItem(bulletsList, "1⁄2 teaspoon of salt");
                document.AddListItem(bulletsList, "1 teaspoon of vanilla essence");

                // Create a table for text and the picture.
                var table = document.AddTable(1, 2);
                table.Design  = TableDesign.LightListAccent3;
                table.AutoFit = AutoFit.Window;
                table.Rows[0].Cells[0].Paragraphs[0].AppendLine().AppendLine().Append("Simple Vanilla Cupcakes Recipe").FontSize(20).Font(new Font("Comic Sans MS"));
                table.Rows[0].Cells[1].Paragraphs[0].AppendPicture(picture);

                // Create a numbered list for the directions.
                var recipeList = document.AddList("Preheat oven to 375F and fill muffin cups with papers.", 0, ListItemType.Numbered, 1);
                document.AddListItem(recipeList, "Mix butter and sugar until light and fluffy.");
                document.AddListItem(recipeList, "Beat in the eggs, one at a time.", 1);
                document.AddListItem(recipeList, "Add the flour, baking powder and salt, alternate with milk and beat well.");
                document.AddListItem(recipeList, "Add in vanilla.", 1);
                document.AddListItem(recipeList, "Divide in the pans and bake for 18 minutes.");
                document.AddListItem(recipeList, "Let cool 5 minutes an eat.", 1);

                // Insert the data in page.
                document.InsertTable(table);
                var paragraph = document.InsertParagraph();
                paragraph.AppendLine();
                paragraph.AppendLine();
                paragraph.AppendLine("Ingredients").FontSize(15).Bold().Color(Color.BlueViolet);
                document.InsertList(bulletsList);
                var paragraph2 = document.InsertParagraph();
                paragraph2.AppendLine();
                paragraph2.AppendLine("Directions").FontSize(15).Bold().Color(Color.BlueViolet);
                document.InsertList(recipeList);
                var paragraph3 = document.InsertParagraph();
                paragraph3.AppendLine();
                paragraph3.AppendLine("Reference: ").AppendHyperlink(hyperlink).Color(Color.Blue).UnderlineColor(Color.Blue).Append(".");

                // Save this document to disk.
                document.Save();
                Console.WriteLine("\tCreated: CreateRecipe.docx\n");
            }
        }
Example #7
0
        public void WriteMainParagraphs()
        {
            _document.MarginTop = 25;
            repository          = new PatientRepository(dB);
            Hospital hospital = repository.Hospital.FirstOrDefault();
            Image    image;
            Picture  picture;
            Table    headerTable = _document.InsertTable(2, 3);
            var      path        = _pathToBinFolder + @"\Icon.png";

            headerTable.MergeCellsInColumn(1, 0, 1);
            if (File.Exists(path.Substring(6)))
            {
                image   = _document.AddImage(path.Substring(6));
                picture = image.CreatePicture();
                headerTable.Rows[0].Cells[1].Paragraphs[0].InsertPicture(picture);
            }
            headerTable.SetColumnWidth(0, 3300);
            headerTable.SetColumnWidth(1, 3300);
            headerTable.SetColumnWidth(2, 3300);
            headerTable.Rows[0].Cells[0].Paragraphs[0].Append("Тел: ").Bold().FontSize(11).SpacingAfter(2).Append(hospital?.Phone).FontSize(paragraphSize);
            headerTable.Rows[1].Cells[0].Paragraphs[0].Append("Адрес: ").Bold().FontSize(11).SpacingAfter(2).Append(hospital?.Address).FontSize(paragraphSize);
            headerTable.Rows[0].Cells[0].Paragraphs[0].Alignment = Alignment.center;
            headerTable.Rows[1].Cells[0].Paragraphs[0].Alignment = Alignment.center;

            headerTable.Rows[0].Cells[2].Paragraphs[0].Append("Tel: ").Bold().FontSize(11).SpacingAfter(2).Append(hospital?.Phone).FontSize(paragraphSize);
            headerTable.Rows[1].Cells[2].Paragraphs[0].Append("Manzil: ").Bold().FontSize(11).SpacingAfter(2).Append(hospital?.AddressUz).FontSize(paragraphSize);
            headerTable.Rows[0].Cells[2].Paragraphs[0].Alignment = Alignment.center;
            headerTable.Rows[1].Cells[2].Paragraphs[0].Alignment = Alignment.center;

            ClearBorder(headerTable);
            _document.InsertParagraph().FontSize(9);
            Table  mainTable = _document.InsertTable(6, 2);
            string jender    = _patient.Patient.Jender == "Ж" ? "Женский" : "Мужской";

            mainTable.SetColumnWidth(0, 4000);
            mainTable.SetColumnWidth(1, 5900);
            mainTable.Rows[0].Cells[0].Paragraphs[0].Append("Ф.И.О пациента").Bold().FontSize(paragraphSize);
            mainTable.Rows[0].Cells[1].Paragraphs[0].Append(_patient.Patient.FIO?.ToUpper() + " " + _patient.Patient.CardNumber).Bold().FontSize(paragraphSize).UnderlineStyle(UnderlineStyle.singleLine);

            mainTable.Rows[1].Cells[0].Paragraphs[0].Append("Дата рождения").Bold().FontSize(paragraphSize);
            mainTable.Rows[1].Cells[1].Paragraphs[0].Append(_patient.Patient.BirthDay).FontSize(paragraphSize);

            mainTable.Rows[2].Cells[0].Paragraphs[0].Append("Пол").Bold().FontSize(paragraphSize);
            mainTable.Rows[2].Cells[1].Paragraphs[0].Append(jender).FontSize(paragraphSize);


            mainTable.Rows[3].Cells[0].Paragraphs[0].Append("Ф.И.О врача").Bold().FontSize(paragraphSize);
            mainTable.Rows[3].Cells[1].Paragraphs[0].Append(_patient.Patient.DoctorName).FontSize(paragraphSize);

            mainTable.Rows[4].Cells[0].Paragraphs[0].Append("Дата обследования").Bold().FontSize(paragraphSize);
            mainTable.Rows[4].Cells[1].Paragraphs[0].Append(_patient.Patient.ResearchDateTime.Value.ToString()).FontSize(paragraphSize);

            mainTable.Rows[5].Cells[0].Paragraphs[0].Append("Аппарат").Bold().FontSize(paragraphSize);
            mainTable.Rows[5].Cells[1].Paragraphs[0].Append(_patient.Patient.SelectedApparat).FontSize(paragraphSize);
            if (_patient.Patient.ChildAgeCode != 0)
            {
                mainTable.RemoveRow(2);
            }


            _document.InsertParagraph().FontSize(9);
            var p = _document.InsertParagraph("Эхокардиография").Bold().UnderlineStyle(UnderlineStyle.singleLine).FontSize(15).SpacingAfter(20);

            p.Alignment = Alignment.center;
            Table table = _document.InsertTable(2, 2);

            table.SetColumnWidth(0, 4950); table.SetColumnWidth(1, 4950);
            table.Rows[0].Cells[0].Paragraphs[0].Append($"ЭКГ ритм: {_patient.ECG.Rhythm} {_patient.ECG.FirstTextBox} {_patient.ECG.SecondTextBox} в мин").FontSize(cellParagraphSize).SpacingAfter(2);
            table.Rows[1].Cells[0].Paragraphs[0].Append($"Рост: {_patient.Patient.Height} см вес: {_patient.Patient.Weigth} кг").FontSize(cellParagraphSize).SpacingAfter(2);
            table.Rows[1].Cells[1].Paragraphs[0].Append($"качество визуализации: {_patient.Patient.SelectedQualityVizuality}").FontSize(cellParagraphSize).SpacingAfter(2);
            table.Rows[0].Cells[1].Paragraphs[0].Alignment = Alignment.right;
            table.Rows[1].Cells[1].Paragraphs[0].Alignment = Alignment.right;
            ClearBorder(table);

            _document.InsertParagraph().FontSize(2);
            WriteTable();
            AddImage();
            _document.InsertParagraph().FontSize(9);
            p = _document.InsertParagraph($"ЗАКЛЮЧЕНИЕ:").FontSize(cellParagraphSize).SpacingAfter(6).Bold();
            p = _document.InsertParagraph(_patient.Patient.Conclusion?.ToUpper()).FontSize(cellParagraphSize).SpacingAfter(1).Bold();
            _document.InsertParagraph().FontSize(9);

            p = _document.InsertParagraph($"РЕКОМЕНДАЦИИ:").FontSize(cellParagraphSize).SpacingAfter(6).Bold();
            p = _document.InsertParagraph(_patient.Patient.Recomendation).FontSize(cellParagraphSize).SpacingAfter(1);
            _document.InsertParagraph().FontSize(9);
            p = _document.InsertParagraph($"Подпись_____________________________/{_patient.Patient.DoctorName}").FontSize(cellParagraphSize).SpacingBefore(5);
        }
Example #8
0
        static void Main()
        {
            using (StreamReader sr = new StreamReader("Content/text.txt", Encoding.UTF8))
            {
                using (DocX doc = DocX.Create("Output.doc"))
                {
                    Paragraph p = doc.InsertParagraph(sr.ReadLine(), false);
                    p.Alignment = Alignment.center;
                    p.FontSize(32);
                    p.Bold();
                    Image   img = doc.AddImage("Content/rpg-game.png");
                    Picture pic = img.CreatePicture(300, 600);
                    p.AppendPicture(pic);
                    doc.InsertParagraph(sr.ReadLine());
                    Paragraph  p3     = doc.InsertParagraph(sr.ReadLine());
                    Formatting format = new Formatting {
                        Bold = true
                    };
                    p3.ReplaceText("role playing game", "role playing game", false, RegexOptions.None, format);
                    format.UnderlineStyle = UnderlineStyle.singleLine;
                    p3.ReplaceText("grand prize!", "grand prize!", false, RegexOptions.None, format);
                    doc.InsertParagraph(sr.ReadLine());

                    List list = doc.AddList(sr.ReadLine(), 0, ListItemType.Bulleted);
                    doc.AddListItem(list, sr.ReadLine());
                    doc.AddListItem(list, sr.ReadLine());
                    doc.AddListItem(list, sr.ReadLine());
                    list.Items[0].IndentationBefore = 1.5f;
                    list.Items[1].IndentationBefore = 1.5f;
                    list.Items[2].IndentationBefore = 1.5f;
                    doc.InsertList(list);
                    doc.InsertParagraph("");

                    string[] tableHeaders = sr.ReadLine().Split();

                    Table table = doc.AddTable(4, 3);
                    table.Alignment = Alignment.center;
                    table.Design    = TableDesign.TableGrid;
                    table.Rows[0].Cells[0].FillColor = Color.CornflowerBlue;
                    table.Rows[0].Cells[0].Paragraphs.First().Append(tableHeaders[0]).Bold().Alignment = Alignment.center;
                    foreach (var cell in table.Rows[0].Cells)
                    {
                        cell.Width        = doc.PageWidth / 3;
                        cell.MarginBottom = 0;
                        cell.MarginLeft   = 0;
                        cell.MarginRight  = 0;
                        cell.MarginTop    = 0;
                    }
                    table.Rows[0].Cells[1].FillColor = Color.CornflowerBlue;
                    table.Rows[0].Cells[1].Paragraphs.First().Append(tableHeaders[1]).Bold().Alignment = Alignment.center;
                    table.Rows[0].Cells[2].FillColor = Color.CornflowerBlue;
                    table.Rows[0].Cells[2].Paragraphs.First().Append(tableHeaders[2]).Bold().Alignment = Alignment.center;
                    string[] tableContents = sr.ReadLine().Split(new char [] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries)
                                             .Concat(sr.ReadLine().Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries))
                                             .Concat(sr.ReadLine().Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries)).ToArray();
                    int index = 0;
                    for (int i = 1; i < table.RowCount; i++)
                    {
                        for (int j = 0; j < table.ColumnCount; j++)
                        {
                            table.Rows[i].Cells[j].Paragraphs[0].Append(tableContents[index]).Alignment = Alignment.center;
                            index++;
                        }
                    }
                    doc.InsertTable(table);
                    doc.InsertParagraph(sr.ReadLine());

                    Paragraph p4 = doc.InsertParagraph(sr.ReadLine()).Bold().FontSize(12).Color(Color.DarkBlue);
                    p4.ReplaceText("SPECTACULAR", "SPECTACULAR", false, RegexOptions.None, new Formatting {
                        Bold = true, FontColor = Color.DarkBlue, Size = 12
                    });
                    p4.AppendLine(sr.ReadLine().ToUpper())
                    .Bold()
                    .FontSize(24)
                    .UnderlineStyle(UnderlineStyle.singleLine)
                    .Color(Color.DarkBlue)
                    .UnderlineColor(Color.DarkBlue);
                    p4.Alignment = Alignment.center;

                    doc.Save();
                }
            }
        }
Example #9
0
        //creates ticket and returns its path
        public string createTicket(string firstName, string lastName, string company, string format,
                                   string eventName, string date, int monthNumber, string location1Row, string location2Row, string barcode,
                                   System.Drawing.Color barcodeColor, string savingName, string firmImagePath,
                                   string eventImagePath, string sponsorsImagePath, string savingPath)
        {
            string encodedBarcode = StringEncoder.ReturnEncryptedString(barcode);

            System.Drawing.Image barcodeImage = barcodeGenerator.generateQrBarcodeZXing(encodedBarcode, barcodeColor);

            string localSavingPath = @"docs\";

            if (savingPath.Replace(" ", "").Length > 0)
            {
                localSavingPath = savingPath + @"\";
            }

            using (DocX document = DocX.Create(localSavingPath + savingName + ".docx"))
            {
                document.InsertParagraph();
                document.InsertParagraph();
                System.Drawing.Color borderColor = System.Drawing.ColorTranslator.FromHtml("#00A86B");
                // Set document margins
                document.MarginBottom = 0.7F;
                document.MarginTop    = 0.7F;
                document.MarginRight  = 35F;
                document.MarginLeft   = 35F;

                document.InsertParagraph();
                //add logo image
                Picture eventpic    = null;
                Picture sponsorspic = null;
                if (eventImagePath.Length > 0)
                {
                    Image image = document.AddImage(eventImagePath);
                    eventpic = image.CreatePicture();
                }
                if (sponsorsImagePath.Length > 0)
                {
                    Image image = document.AddImage(sponsorsImagePath);
                    sponsorspic = image.CreatePicture();
                }
                if (eventImagePath.Length > 0 && sponsorsImagePath.Length > 0)
                {
                    Table   table            = document.AddTable(1, 2);
                    float[] widthsPercentage = { 40F, 60F };
                    table.SetWidthsPercentage(widthsPercentage, document.PageWidth - 20F);
                    table.Design = TableDesign.TableGrid;
                    Border emptyBorder = new Border(BorderStyle.Tcbs_none, BorderSize.one, 0, System.Drawing.Color.Transparent);
                    table.SetBorder(TableBorderType.Top, emptyBorder);
                    table.SetBorder(TableBorderType.Right, emptyBorder);
                    table.SetBorder(TableBorderType.Left, emptyBorder);
                    table.SetBorder(TableBorderType.Bottom, emptyBorder);
                    Border notEmptyBorder = new Border(BorderStyle.Tcbs_single, BorderSize.one, 1, borderColor);

                    table.SetBorder(TableBorderType.InsideV, notEmptyBorder);
                    if (eventpic != null)
                    {
                        table.Rows[0].Cells[0].VerticalAlignment = VerticalAlignment.Center;

                        table.Rows[0].Cells[0].Paragraphs[0].AppendPicture(resizePicture(eventpic, 300, 200));
                    }
                    if (sponsorspic != null)
                    {
                        table.Rows[0].Cells[1].VerticalAlignment = VerticalAlignment.Center;
                        table.Rows[0].Cells[1].MarginLeft        = 20F;
                        table.Rows[0].Cells[1].Paragraphs[0].AppendPicture(resizePicture(sponsorspic, 600, 200));
                    }
                    table.SetBorder(TableBorderType.Bottom, emptyBorder);
                    //table.AutoFit = AutoFit.Contents;
                    document.InsertTable(table);
                    table.SetBorder(TableBorderType.Bottom, emptyBorder);
                }
                else if (eventImagePath.Length > 0)
                {
                    addImageToDocument(document, 150, 500, eventImagePath, Alignment.center);
                }
                else if (sponsorsImagePath.Length > 0)
                {
                    addImageToDocument(document, 150, 500, sponsorsImagePath, Alignment.center);
                }
                //addImageToDocument(document, 145, 473, LogoFinalImage, Alignment.center);

                float pageWidth = document.PageWidth * 18;
                //add line through all page

                document.InsertParagraph();
                addLineToDocument(document, Xceed.Document.NET.BorderStyle.Tcbs_dashed,
                                  pageWidth, borderColor);

                document.InsertParagraph();

                System.Drawing.Color headerColor    = System.Drawing.ColorTranslator.FromHtml("#9E9E9E");
                System.Drawing.Color paragraphColor = System.Drawing.ColorTranslator.FromHtml("#404040");
                System.Drawing.Color linkColor      = System.Drawing.ColorTranslator.FromHtml("#E36C0A");
                //Add text to document
                addTextToDocument(document, "Name", Alignment.left, "Calibri", 14, headerColor);
                addTextToDocument(document, firstName + " " + lastName, Alignment.left, "Calibri", 28, paragraphColor);
                document.InsertParagraph();
                addTextToDocument(document, "Company", Alignment.left, "Calibri", 14, headerColor);
                addTextToDocument(document, company, Alignment.left, "Calibri", 16, paragraphColor);
                document.InsertParagraph();
                addTextToDocument(document, "Format", Alignment.left, "Calibri", 14, headerColor);
                addTextToDocument(document, format, Alignment.left, "Calibri", 16, paragraphColor);
                document.InsertParagraph();
                addTextToDocument(document, "Event", Alignment.left, "Calibri", 14, headerColor);
                addTextToDocument(document, eventName, Alignment.left, "Calibri", 16, paragraphColor);
                document.InsertParagraph();
                string dateLocation = "Date\t\t\t\t\t\t\t\t\tLocation";
                string tabs         = "\t\t\t\t\t";
                if (monthNumber >= 11 || monthNumber == 9)
                {
                    tabs = "\t\t\t\t";
                }
                string datePlace    = date + tabs + location1Row;
                string TimeLocation = "\t\t\t\t\t\t\t\t\t" + location2Row;



                //string calendarMap = "Add to calendar\t\t\t\t\t\t\t\t\t\t\tView map";



                addTextToDocument(document, dateLocation, Alignment.left, "Calibri", 14, headerColor);
                addTextToDocument(document, datePlace, Alignment.left, "Calibri", 16, paragraphColor);
                addTextToDocument(document, TimeLocation, Alignment.left, "Calibri", 16, paragraphColor);
                document.InsertParagraph();



                addImageToDocument(document, 250, 250, barcodeImage, Alignment.center);

                //addTextToDocument(document, calendarMap, Alignment.left, "Calibri", 11, linkColor);
                document.InsertParagraph();
                addLineToDocument(document, Xceed.Document.NET.BorderStyle.Tcbs_dashed,
                                  pageWidth, borderColor);

                document.InsertParagraph();
                addTextToDocument(document, "ORGANIZER", Alignment.left, "Calibri", 14, headerColor);

                string companyImagePath = Directory.GetParent(workingDirectory).Parent.FullName + @"\UI\Images\" + "mergedImage" + ".png";
                if (firmImagePath.Replace(" ", "").Length < 1)
                {
                    addTwoImagesToText("\t\t\t\t\t\t", companyImagePath, iliniumImage, document, Alignment.right, "Calibri",
                                       14, System.Drawing.Color.Black);
                }
                else
                {
                    addTwoImagesToText("\t\t\t\t\t\t", companyImagePath, firmImagePath, document, Alignment.right, "Calibri",
                                       14, System.Drawing.Color.Black);
                }
                // Save this document.
                document.Save();
            }


            string targetPath = Directory.GetParent(workingDirectory).Parent.FullName + @"\bin\Debug\docs\";

            if (savingPath.Replace(" ", "").Length > 0)
            {
                targetPath = savingPath + @"\";
            }
            string targetFile = targetPath + savingName + ".pdf";

            convertWordToPdf(targetPath + savingName + ".docx", targetFile);

            return(targetFile);
        }
Example #10
0
        private static Table AlizhouTableToTable(DocX word, AlizhouTable alizhouTable)
        {
            var table = word.AddTable(alizhouTable.RowCount, alizhouTable.ColumnCount);

            table.Alignment = Alignment.center;
            table.SetBorder(TableBorderType.InsideH, new Border {
            });
            table.SetBorder(TableBorderType.Top, new Border {
            });
            table.SetBorder(TableBorderType.Bottom, new Border {
            });
            table.SetBorder(TableBorderType.Left, new Border {
            });
            table.SetBorder(TableBorderType.Right, new Border {
            });
            table.SetBorder(TableBorderType.InsideV, new Border {
            });
            for (int i = 0; i < alizhouTable.Rows.Count; i++)
            {
                if (alizhouTable.Rows[i].Height > 0)
                {
                    table.Rows[i].Height = alizhouTable.Rows[i].Height;//设置行高
                }
                //处理每行单元格
                for (int j = 0; j < alizhouTable.Rows[i].Cells.Count; j++)
                {
                    var alizhouTableCell = alizhouTable.Rows[i].Cells[j];
                    //设置单元格宽
                    if (table.Rows[i].Cells[j].Width > 0)
                    {
                        table.Rows[i].Cells[j].Width = alizhouTableCell.Width;
                    }
                    if (alizhouTableCell.FillColor != Color.Empty)
                    {
                        table.Rows[i].Cells[j].FillColor = alizhouTableCell.FillColor;
                    }
                    table.Rows[i].Cells[j].VerticalAlignment = alizhouTableCell.VerticalAlignment;

                    table.Rows[i].Cells[j].RemoveParagraphAt(0);//移除默认段落
                    foreach (var item in alizhouTableCell.Paragraphs)
                    {
                        var p = table.Rows[i].Cells[j].InsertParagraph();
                        if (!string.IsNullOrEmpty(item.Run.Text))
                        {
                            p.Append(item.Run.Text);
                        }
                        if (item.Run.IsBold)
                        {
                            p.Bold();
                        }
                        p.FontSize(item.Run.FontSize);
                        p.Font(item.Run.FontFamily);
                        p.Color(item.Run.Color);
                        p.Alignment = item.Alignment;
                        if (item.Run.Pictures.Count > 0)
                        {
                            item.Run.Pictures.ForEach(t =>
                            {
                                Stream stream = t.PictureData ?? File.OpenRead(t.PictureUrl);
                                p.AppendPicture(word.AddImage(stream).CreatePicture(t.Width, t.Height));
                            });
                        }
                    }
                }
            }


            //处理合并单元格


            foreach (var item in alizhouTable.MergeCellsInColumns)
            {
                table.MergeCellsInColumn(item.Item1, item.Item2, item.Item3);
            }
            foreach (var item in alizhouTable.MergeCellsInRows)
            {
                table.Rows[item.Item1].MergeCells(item.Item2, item.Item3);
                if (table.Rows[item.Item1].Cells[item.Item2].Paragraphs[0].Text == "备注")
                {
                }
                //合并之后只保留一个段落
                while (table.Rows[item.Item1].Cells[item.Item2].Paragraphs.Count > 1)
                {
                    table.Rows[item.Item1].Cells[item.Item2].RemoveParagraphAt(1);
                }
            }

            return(table);
        }
Example #11
0
        public static void SaveAllData(PictureBox pictureBox1, int complexity)
        {
            //Сохранение картинки
            System.Drawing.Rectangle r = pictureBox1.RectangleToScreen(pictureBox1.ClientRectangle);
            Bitmap   b = new Bitmap(r.Width, r.Height);
            Graphics g = Graphics.FromImage(b);

            g.CopyFromScreen(r.Location, new System.Drawing.Point(0, 0), r.Size);
            b.Save(path + "Image.jpg");


            //Сохранение в WORD
            string pathDocument = path + "DragonCurveInfo.docx";
            string pathImage    = path + "Image.jpg";
            DocX   document     = DocX.Create(pathDocument);

            // вставляем параграф и передаём текст
            document.InsertParagraph("Complexity: " + complexity).
            // устанавливаем шрифт
            Font("Calibri").
            // устанавливаем размер шрифта
            FontSize(15).
            // устанавливаем цвет
            Color(Color.Black).
            // делаем текст жирным
            Bold().
            // устанавливаем интервал между символами
            Spacing(5).
            // выравниваем текст по центру
            Alignment = Alignment.left;
            Painter painter = new Painter();

            document.InsertParagraph("X1: " + painter.x1.ToString() +
                                     "\nX2: " + painter.x2.ToString() +
                                     "\nY1: " + painter.y1.ToString() +
                                     "\nY2: " + painter.y2.ToString()).
            Font("Calibri").
            FontSize(15).
            Color(Color.Black).
            Bold().
            Spacing(5).
            Alignment = Alignment.left;

            Xceed.Words.NET.Image image = document.AddImage(pathImage);
            // создание параграфа
            Paragraph paragraph = document.InsertParagraph();

            // вставка изображения в параграф
            paragraph.AppendPicture(image.CreatePicture());
            // выравнивание параграфа по центру
            paragraph.Alignment = Alignment.center;
            // сохраняем документ
            document.Save();

            //Сохранение в EXCEL
            string pathExcel = path + "DragonCurveInfo.xls";

            // Создаём экземпляр нашего приложения
            Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();

            // Создаём экземпляр рабочий книги Excel
            Workbook workBook;
            // Создаём экземпляр листа Excel
            Worksheet workSheet;

            workBook  = excelApp.Workbooks.Add();
            workSheet = (Worksheet)workBook.Worksheets.get_Item(1);

            workSheet.Cells[1, 1] = "Complexity";
            workSheet.Cells[1, 2] = "X1";
            workSheet.Cells[1, 3] = "X2";
            workSheet.Cells[1, 4] = "Y1";
            workSheet.Cells[1, 5] = "Y2";
            workSheet.Cells[2, 1] = complexity.ToString();
            workSheet.Cells[2, 2] = painter.x1.ToString();
            workSheet.Cells[2, 3] = painter.x2.ToString();
            workSheet.Cells[2, 4] = painter.y1.ToString();
            workSheet.Cells[2, 5] = painter.y2.ToString();
            workSheet.Shapes.AddPicture(path + "Image.jpg",
                                        Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 0, 30, 350, 250);
            //excelApp.Visible = true;
            //excelApp.UserControl = true;

            //excelApp.DefaultSaveFormat = Excel.XlFileFormat.xlExcel9795;
            excelApp.DefaultFilePath = pathExcel;
            excelApp.DisplayAlerts   = false;
            workBook.SaveAs(pathExcel, XlFileFormat.xlWorkbookNormal,
                            Type.Missing,
                            Type.Missing,
                            Type.Missing,
                            Type.Missing,
                            XlSaveAsAccessMode.xlExclusive,
                            Type.Missing,
                            Type.Missing,
                            Type.Missing,
                            Type.Missing,
                            Type.Missing);
            excelApp.Quit();
        }
Example #12
0
        public static void CreateSampleDocument()
        {
            using (DocX document = DocX.Create("../../MyDocXDocument.docx"))
            {
                Paragraph headLine     = document.InsertParagraph();
                string    headLineText = "SoftUni OOP Game Contest";
                headLine.AppendLine(headLineText).Bold().FontSize(32);
                headLine.Alignment = Alignment.center;

                Image     imageGame        = document.AddImage("../../rpg-game.png");
                Paragraph pictureParagraph = document.InsertParagraph("", false);
                Picture   game             = imageGame.CreatePicture(250, 600);
                pictureParagraph.InsertPicture(game);

                Paragraph text = document.InsertParagraph();
                text.AppendLine();
                text.Append("SoftUni is organizing a contest for the best ");
                text.Append("role playing game").Bold();
                text.Append(" from the OOP teamwork\n projects. The winning teams will receive a ");
                text.Append("grand prize").Bold().UnderlineStyle(UnderlineStyle.singleLine);
                text.Append("!\nThe game should be:");

                List bullets = document.AddList(null, 0, ListItemType.Bulleted);
                document.AddListItem(bullets, "Properly structured and follow all good OOP practices");
                document.AddListItem(bullets, "Awesome");
                document.AddListItem(bullets, "..Very Awesome");
                document.InsertList(bullets);
                document.InsertParagraph("\n");

                Table table = document.AddTable(4, 3);
                table.Alignment = Alignment.center;
                table.Rows[0].Cells[0].Paragraphs.First().Append("Team").Bold();
                table.Rows[0].Cells[0].Paragraphs.First().Alignment = Alignment.center;
                table.Rows[0].Cells[1].Paragraphs.First().Append("Game").Bold();
                table.Rows[0].Cells[1].Paragraphs.First().Alignment = Alignment.center;
                table.Rows[0].Cells[2].Paragraphs.First().Append("Points").Bold();
                table.Rows[0].Cells[2].Paragraphs.First().Alignment = Alignment.center;

                for (int i = 1; i < 4; i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        table.Rows[i].Cells[j].Paragraphs.First().Append("-");
                        table.Rows[i].Cells[j].Paragraphs.First().Alignment = Alignment.center;
                    }
                }

                table.Rows[0].Cells.ForEach(c => c.Width = 300);
                table.Rows[1].Cells.ForEach(c => c.Width = 300);
                table.Rows[2].Cells.ForEach(c => c.Width = 300);
                document.InsertTable(table);

                Paragraph finalParagraph = document.InsertParagraph();
                finalParagraph.AppendLine();
                finalParagraph.Append("The top 3 teams will receive a ");
                finalParagraph.Append("SPECTACULAR").Bold().FontSize(16);
                finalParagraph.Append(" prize:\n");
                finalParagraph.Append("A HANDSHAKE FROM NAKOV").Bold().FontSize(24).UnderlineStyle(UnderlineStyle.singleLine);
                finalParagraph.Alignment = Alignment.center;
                document.Save();
            }
        }
Example #13
0
        public static DocX CreateDocA(DocX template, ECEViewModel model, string source, bool cprvalue)
        {
            bool   addcor  = false;
            string Fadcorr = "";
            bool   special = false;
            string Fsnum   = "[NUMBER]";
            string sym     = getSym(model);

            if (!String.IsNullOrEmpty(model.Prep))
            {
                sym = sym.Replace("#", model.Prep.ToString());
            }
            if (cprvalue == true)
            {
                sym = sym + "/CRP." + model.cprnum.ToString();
            }
            if (!String.IsNullOrEmpty(model.Add) && model.cAdd == true && model.cCor == false)
            {
                sym     = sym + "/Add." + model.Add.ToString();
                Fadcorr = "Addendum";
                addcor  = true;
            }
            if (!String.IsNullOrEmpty(model.Cor) && model.cCor == true && model.cAdd == false)
            {
                sym     = sym + "/Corr." + model.Cor.ToString();
                Fadcorr = "Corrigendum";
                addcor  = true;
            }
            if (!String.IsNullOrEmpty(model.Cor) && !String.IsNullOrEmpty(model.Add) && model.cCor == true && model.cAdd == true)
            {
                sym     = sym + "/Add." + model.Add.ToString() + "/Corr." + model.Cor.ToString();
                Fadcorr = "Addendum Corrigendum";
                addcor  = true;
            }
            if (String.IsNullOrEmpty(model.Cor) && String.IsNullOrEmpty(model.Add))
            {
                addcor = false;
            }
            if (String.IsNullOrEmpty(model.CaseYear))
            {
                sym = sym.Replace("&", DateTime.Now.Year.ToString());
            }
            if (!String.IsNullOrEmpty(model.CaseYear))
            {
                sym = sym.Replace("&", model.CaseYear.ToString());
            }
            model.tsym = sym;
            string[] SymStr = sym.Split('/');
            string[] sym1   = SymStr.Skip(1).ToArray();
            string   Fsym   = String.Join("/", sym1);

            if (Fsym.Contains("/S/"))
            {
                special = true;
                Fsnum   = "special";
            }
            //Create Date for Header
            string Fdate = model.date.ToString();

            string[] d = Fdate.Split(' ');
            Fdate = d[0];
            Fdate = formatdate(Fdate, model);


            //Create Distribution for Header
            string Fdist = getDist(model);

            //Create Virsions for Header
            string Fvirs = "";

            //if (model.version1 != null)
            //{
            //    int deleteStart = 0;
            //    int deleteEnd = 0;

            //    //Get the array of the paragraphs containing the start and end catches
            //    for (int i = 0; i < template.Paragraphs.Count; i++)
            //    {
            //        if (template.Paragraphs[i].Text.Contains("Original"))
            //            deleteStart = i;
            //        if (template.Paragraphs[i].Text.Contains("olang"))
            //            deleteEnd = i;
            //    }

            //    if (deleteStart > 0 && deleteEnd > 0)
            //    {
            //        //delete from the paraIndex as the arrays will shift when a paragraph is deleted
            //        int paraIndex = deleteStart;
            //        for (int i = deleteStart; i <= deleteEnd; i++)
            //        {
            //            template.RemoveParagraphAt(paraIndex);
            //        }
            //    }
            //}

            //Fvirs = getVerisons(model);

            string Folang = "";

            Folang = Olanguage(model.lang_ID);

            string Fatitle = "[Title]";

            if (!String.IsNullOrEmpty(model.AgendaItem))
            {
                Fatitle = model.AgendaItem.ToString();
            }
            string Fsdate = "[Start-End Dates ]";

            if (model.Sdate != null & model.Edate != null)
            {
                string   sdate = model.Sdate.ToString();
                string[] sd    = sdate.Split(' ');
                sdate = sd[0];
                sdate = formatdate(sdate, model);

                string   edate = model.Edate.ToString();
                string[] ed    = edate.Split(' ');
                edate = ed[0];
                edate = formatdate(edate, model);


                Fsdate = SessionDate(sdate, edate, model);
            }
            string Fldate = "[Start Date]";

            if (model.Sdate != null & model.Edate != null)
            {
                string   ldate = model.Sdate.ToString();
                string[] ld    = ldate.Split(' ');
                ldate = ld[0];
                string dldate = System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat.GetDayName(DateTime.Parse(ldate).DayOfWeek);
                ldate = formatdate(ldate, model);
                //Regex rx = new Regex(@"^\d+\p{Zs}", RegexOptions.Compiled);
                //ldate = rx.Replace(ldate, dldate+" ");
                ldate  = dldate + " " + ldate;
                Fldate = ldate;
            }

            string Fanum = "[NUMBER]";

            if (!String.IsNullOrEmpty(model.AgendaNum))
            {
                Fanum = model.AgendaNum.ToString();
            }

            if (special == false)
            {
                if (!String.IsNullOrEmpty(model.SNum))
                {
                    Fsnum = Sessionnum(model);
                }
            }



            if (model.qrcode == true)
            {
                string lang = language(model.lang_ID);
                lang = lang.Substring(0, 1);


                string url = "http://undocs.org/m2/QRCode.ashx?DS=" + Fsym + "&Size=2&Lang=" + lang;
                using (var client = new WebClient())
                {
                    //var content = client.DownloadData("https://api.qrserver.com/v1/create-qr-code/?size=66x66&data=http://undocs.org/fr/A/HRC/70");
                    //var content = client.DownloadData("http://undocs.org/m2/QRCode.ashx?DS=A/HRC/70&Size=2&Lang=F");
                    var content = client.DownloadData(url);

                    using (var str = new MemoryStream(content))
                    {
                        if (lang == "A")
                        {
                            Image     image = template.AddImage(str);
                            NVPicture p     = image.CreatePicture();
                            NVFooter  f     = template.Footers.first;
                            NVTable   t     = f.Tables[0];
                            //t.Rows[0].Cells[1].Paragraphs.First().AppendPicture(pR);
                            t.Rows[0].Cells[0].Paragraphs.First().AppendPicture(p);
                        }
                        else
                        {
                            NVImage   image = template.AddImage(str);
                            NVPicture p     = image.CreatePicture();
                            NVFooter  f     = template.Footers.first;
                            NVTable   t     = f.Tables[0];
                            //t.Rows[0].Cells[1].Paragraphs.First().AppendPicture(pR);
                            t.Rows[0].Cells[1].Paragraphs.First().AppendPicture(p);
                        }
                    }
                }
            }
            string Fcategory = "";

            Fcategory = getCat(model.Cat);
            string FSubcategory = "";

            if (model.SCat != "Not Applicable" || model.SCat != "Special Session")
            {
                FSubcategory = model.SCat.ToString();
            }
            if (model.SCat == "Not Applicable" || model.SCat == "Special Session")
            {
                int deleteStart = 0;
                int deleteEnd   = 0;

                //Get the array of the paragraphs containing the start and end catches
                for (int i = 0; i < template.Paragraphs.Count; i++)
                {
                    if (template.Paragraphs[i].Text.Contains("subcategory"))
                    {
                        deleteStart = i;
                    }
                    if (template.Paragraphs[i].Text.Contains("subcategory"))
                    {
                        deleteEnd = i;
                    }
                }

                if (deleteStart > 0 && deleteEnd > 0)
                {
                    //delete from the paraIndex as the arrays will shift when a paragraph is deleted
                    int paraIndex = deleteStart;
                    for (int i = deleteStart; i <= deleteEnd; i++)
                    {
                        template.RemoveParagraphAt(paraIndex);
                    }
                }
            }
            if (addcor == false)
            {
                int deleteStart = 0;
                int deleteEnd   = 0;

                //Get the array of the paragraphs containing the start and end catches
                for (int i = 0; i < template.Paragraphs.Count; i++)
                {
                    if (template.Paragraphs[i].Text.Contains("adcorr"))
                    {
                        deleteStart = i;
                    }
                    if (template.Paragraphs[i].Text.Contains("adcorr"))
                    {
                        deleteEnd = i;
                    }
                }

                if (deleteStart > 0 && deleteEnd > 0)
                {
                    //delete from the paraIndex as the arrays will shift when a paragraph is deleted
                    int paraIndex = deleteStart;
                    for (int i = deleteStart; i <= deleteEnd; i++)
                    {
                        template.RemoveParagraphAt(paraIndex);
                    }
                }
            }
            string Fsplace = "[Session City]";

            if (!String.IsNullOrEmpty(model.splace))
            {
                Fsplace = model.splace.ToString();
            }
            string Floca = "[Session Location]";

            if (!String.IsNullOrEmpty(model.loca))
            {
                Floca = model.loca.ToString() + ", " + Fsplace;
            }

            DateTime x = DateTime.Now;

            string[] info1 = info(model);

            template.AddCustomProperty(new CustomProperty("sym1", Fsym));
            template.AddCustomProperty(new CustomProperty("symh", sym));
            template.AddCustomProperty(new CustomProperty("dist", Fdist));
            template.AddCustomProperty(new CustomProperty("date", Fdate));
            template.AddCustomProperty(new CustomProperty("sdate", Fsdate));
            template.AddCustomProperty(new CustomProperty("virs", Fvirs));
            template.AddCustomProperty(new CustomProperty("snum", Fsnum));
            template.AddCustomProperty(new CustomProperty("anum", Fanum));
            template.AddCustomProperty(new CustomProperty("adcorr", Fadcorr));
            template.AddCustomProperty(new CustomProperty("gdoc", ""));
            template.AddCustomProperty(new CustomProperty("gdocf", ""));
            template.AddCustomProperty(new CustomProperty("tlang", ""));
            template.AddCustomProperty(new CustomProperty("atitle", Fatitle));
            template.AddCustomProperty(new CustomProperty("ldate", Fldate));
            template.AddCustomProperty(new CustomProperty("loca", Floca));
            template.AddCustomProperty(new CustomProperty("categ", Fcategory));
            template.AddCustomProperty(new CustomProperty("subcategory", FSubcategory));
            template.AddCustomProperty(new CustomProperty("splace", Fsplace));
            template.AddCustomProperty(new CustomProperty("olang", Folang));
            template.AddCustomProperty(new CustomProperty("Date-Generated", x));
            template.AddCustomProperty(new CustomProperty("Org", "ECE"));
            template.AddCustomProperty(new CustomProperty("Entity", info1[0]));
            template.AddCustomProperty(new CustomProperty("doctype", info1[1]));
            template.AddCustomProperty(new CustomProperty("category", info1[2]));
            template.AddCustomProperty(new CustomProperty("bar", ""));

            for (int i = 0; i < template.Paragraphs.Count; i++)
            {
                if (template.Paragraphs[i].Text.Contains(Fsnum))
                {
                    string Fsnum1 = char.ToUpper(Fsnum[0]) + Fsnum.Substring(1);
                    template.Paragraphs[i].ReplaceText(Fsnum, Fsnum1);
                    break;
                }
            }
            if (addcor == true && cprvalue == false)
            {
                int deleteStart = 0;
                int deleteEnd   = 0;

                //Get the array of the paragraphs containing the start and end catches
                for (int i = 0; i < template.Paragraphs.Count; i++)
                {
                    if (template.Paragraphs[i].Text.Contains("*"))
                    {
                        deleteStart = i;
                    }

                    if (template.Paragraphs[i].Text.Contains(Fadcorr))
                    {
                        deleteEnd = i;
                    }
                }

                if (deleteStart > 0 && deleteEnd > 0)
                {
                    //delete from the paraIndex as the arrays will shift when a paragraph is deleted
                    int paraIndex = deleteEnd - deleteStart;
                    paraIndex = deleteStart + paraIndex - 1;

                    template.RemoveParagraphAt(paraIndex);
                }
                //List <string> replace = template.FindUniqueByPattern("*", RegexOptions.None);
                //foreach (string s in replace)
                //{
                //    if (!s.Equals("")) template.ReplaceText((s, "");
                //}

                template.ReplaceText("*", "");

                List <string> repl = template.FindUniqueByPattern(",\\s", RegexOptions.None);
                foreach (string rep in repl)
                {
                    if (!String.IsNullOrEmpty(rep))
                    {
                        template.ReplaceText(rep, "");
                    }
                }



                //bool flag = false;
                //List<List<string>> list1 = new List<List<string>>();
                //List<string> list2 = new List<string>();
                //foreach (Novacode.Paragraph item in template.Paragraphs)
                //{
                //    //use this if you need whole text of a paragraph
                //    string paraText = item.Text;
                //    var result = paraText.Split(' ');
                //    int count = 0;
                //    list2 = new List<string>();
                //    //use this if you need word by word
                //    foreach (var data in result)
                //    {
                //        string word = data.ToString();

                //        if (word.Contains(Fsnum)) flag = true;
                //        if (word.Contains("session"))
                //        {
                //            flag = false;
                //            // list2.Add(word);
                //        }
                //        if (flag)
                //            list2.Add(word);
                //        count++;
                //    }
                //    //    list2.RemoveAt(0);

                //    list1.Add(list2);

                //}
                ////   list1[0].Replace(list1[0], "*");
                //for (int i = 0; i < list1.Count(); i++)
                //{

                //    string temp = "";
                //    for (int y = 0; y < list1[i].Count(); y++)
                //    {
                //        if (y == 0)
                //        {
                //            temp = list1[i][y];
                //            continue;
                //        }
                //        temp += " " + list1[i][y];
                //        //   temp = temp.Remove(temp.IndexOf(',')-1, temp.Length);
                //    }
                //    int ind = temp.IndexOf("*");

                //    // temp = temp.Substring(ind, temp.Length - ind);
                //    if (!temp.Equals("")) template.ReplaceText("Done", "");
                //}
            }
            //using (WordprocessingDocument

            // document = WordprocessingDocument.Open(source, true))

            //{
            //    var bookMarks = FindBookmarks(document.MainDocumentPart.Document);
            //}
            // Return the template now that it has been modified to hold all of our custom data.
            return(template);
        }
Example #14
0
        private static Table AlizhouTableToTable(DocX word, AlizhouTable alizhouTable)
        {
            var table = word.AddTable(alizhouTable.RowCount, alizhouTable.ColumnCount);

            table.Alignment = Alignment.center;
            table.SetBorder(TableBorderType.InsideH, new Border {
            });
            table.SetBorder(TableBorderType.Top, new Border {
            });
            table.SetBorder(TableBorderType.Bottom, new Border {
            });
            table.SetBorder(TableBorderType.Left, new Border {
            });
            table.SetBorder(TableBorderType.Right, new Border {
            });
            table.SetBorder(TableBorderType.InsideV, new Border {
            });
            for (int i = 0; i < alizhouTable.Rows.Count; i++)
            {
                table.Rows[i].Height = alizhouTable.Rows[i].Height;//设置行高
                //处理每行单元格
                for (int j = 0; j < alizhouTable.Rows[i].Cells.Count; j++)
                {
                    var alizhouTableCell = alizhouTable.Rows[i].Cells[j];
                    //设置单元格宽
                    table.Rows[i].Cells[j].Width = alizhouTableCell.Width;
                    if (alizhouTableCell.FillColor != Color.Empty)
                    {
                        table.Rows[i].Cells[j].FillColor = alizhouTableCell.FillColor;
                    }
                    foreach (var item in alizhouTableCell.Paragraphs)
                    {
                        if (item.Run.Pictures.Count > 0)
                        {
                            Paragraph paragraph = table.Rows[i].Cells[j].InsertParagraph();
                            paragraph.Alignment = item.Alignment;
                            item.Run.Pictures.ForEach(t =>
                            {
                                Stream stream = t.PictureData != null ? t.PictureData : File.OpenRead(t.PictureUrl);
                                paragraph.InsertPicture(word.AddImage(stream).CreatePicture(t.Width, t.Height));
                            });
                        }
                        else
                        {
                            //Formatting formatting = new Formatting
                            //{
                            //    Bold = item.Run.IsBold,
                            //    FontColor = item.Run.Color,
                            //    FontFamily = new Font(item.Run.FontFamily),
                            //    Size = item.Run.FontSize
                            //};

                            table.Rows[i].Cells[j].Paragraphs[0].Append(item.Run.Text);
                            if (item.Run.IsBold)
                            {
                                table.Rows[i].Cells[j].Paragraphs[0].Bold();
                            }
                            table.Rows[i].Cells[j].Paragraphs[0].FontSize(item.Run.FontSize);
                            table.Rows[i].Cells[j].Paragraphs[0].Font(item.Run.FontFamily);
                            table.Rows[i].Cells[j].Paragraphs[0].Color(item.Run.Color);
                            table.Rows[i].Cells[j].Paragraphs[0].Alignment = item.Alignment;
                        }
                    }
                }
            }
            return(table);
        }
Example #15
0
        /// <summary>
        /// Create a table, insert rows, image and replace text.
        /// </summary>
        public static void InsertRowAndImageTable()
        {
            Console.WriteLine("\tInsertRowAndImageTable()");

            // Create a document.
            using (DocX document = DocX.Create(TableSample.TableSampleOutputDirectory + @"InsertRowAndImageTable.docx"))
            {
                // Add a title
                document.InsertParagraph("Inserting table").FontSize(15d).SpacingAfter(50d).Alignment = Alignment.center;

                // Add a Table into the document and sets its values.
                var t = document.AddTable(5, 2);
                t.Design    = TableDesign.ColorfulListAccent1;
                t.Alignment = Alignment.center;
                t.Rows[0].Cells[0].Paragraphs[0].Append("Mike");
                t.Rows[0].Cells[1].Paragraphs[0].Append("65");
                t.Rows[1].Cells[0].Paragraphs[0].Append("Kevin");
                t.Rows[1].Cells[1].Paragraphs[0].Append("62");
                t.Rows[2].Cells[0].Paragraphs[0].Append("Carl");
                t.Rows[2].Cells[1].Paragraphs[0].Append("60");
                t.Rows[3].Cells[0].Paragraphs[0].Append("Michael");
                t.Rows[3].Cells[1].Paragraphs[0].Append("59");
                t.Rows[4].Cells[0].Paragraphs[0].Append("Shawn");
                t.Rows[4].Cells[1].Paragraphs[0].Append("57");

                // Add a row at the end of the table and sets its values.
                var r = t.InsertRow();
                r.Cells[0].Paragraphs[0].Append("Mario");
                r.Cells[1].Paragraphs[0].Append("54");

                // Add a row at the end of the table which is a copy of another row, and sets its values.
                var newPlayer = t.InsertRow(t.Rows[2]);
                newPlayer.ReplaceText("Carl", "Max");
                newPlayer.ReplaceText("60", "50");

                // Add an image into the document.
                var image = document.AddImage(TableSample.TableSampleResourcesDirectory + @"logo_xceed.png");
                // Create a picture from image.
                var picture = image.CreatePicture(25, 100);

                // Calculate totals points from second column in table.
                var totalPts = 0;
                foreach (var row in t.Rows)
                {
                    totalPts += int.Parse(row.Cells[1].Paragraphs[0].Text);
                }

                // Add a row at the end of the table and sets its values.
                var totalRow = t.InsertRow();
                totalRow.Cells[0].Paragraphs[0].Append("Total for ").AppendPicture(picture);
                totalRow.Cells[1].Paragraphs[0].Append(totalPts.ToString());
                totalRow.Cells[1].VerticalAlignment = VerticalAlignment.Center;

                // Insert a new Paragraph into the document.
                var p = document.InsertParagraph("Xceed Top Players Points:");
                p.SpacingAfter(40d);

                // Insert the Table after the Paragraph.
                p.InsertTableAfterSelf(t);

                document.Save();
                Console.WriteLine("\tCreated: InsertRowAndImageTable.docx\n");
            }
        }
Example #16
0
        private void CreateDoc(ValueRange vr)
        {
            weight = 0;
            bool secondPage      = false;
            int  amountContPage1 = 0;
            int  amounrContPage2 = 0;

            for (int i = 0; i < vr.Values.Count; i++)
            {
                weight += double.Parse(vr.Values[i][5].ToString(), CultureInfo.CreateSpecificCulture("uk-UA"));
            }
            string strWeight = weight.ToString("#,#.##", CultureInfo.CreateSpecificCulture("uk-UA"));

            if (vr.Values.Count > 22)
            {
                secondPage      = true;
                amountContPage1 = 22;
                amounrContPage2 = vr.Values.Count - 22;
            }
            else
            {
                amountContPage1 = vr.Values.Count;
            }
            Directory.CreateDirectory(@"" + Properties.Settings.Default["SavingPath"].ToString() + "\\" + linesComboBox.Text + "\\" + vesselsComboBox.Text);
            DocX document = DocX.Create(@"" + Properties.Settings.Default["SavingPath"].ToString() + "\\" + linesComboBox.Text + "\\" + vesselsComboBox.Text + "\\" + senderComboBox.Text + " - Прч. " + errendNumber.Text + " - " + vr.Values.Count.ToString() + " конт. - " + countryСomboBox.Text + ".docx");

            Xceed.Words.NET.Image img;
            if (arena.Checked == true)
            {
                img = document.AddImage(@"logo1.png");
            }
            else
            {
                img = document.AddImage(@"UGLv1.jpg");
            }
            Picture p = img.CreatePicture();

            p.Height = (int)(138 / 3.2);
            p.Width  = (int)(2207 / 3.2);
            document.AddHeaders();
            Header header = document.Headers.Odd;

            header.InsertParagraph(" ", false).InsertPicture(p).FontSize(1);
            document.MarginHeader = 0;
            document.MarginFooter = 0;
            document.MarginTop    = 20;
            document.MarginLeft   = 70;
            document.MarginRight  = 25;

            document.AddFooters();
            Footer footer  = document.Footers.Odd;
            Table  tFooter = footer.InsertTable(2, 4);

            tFooter.Rows[1].Height = 50;
            tFooter.Rows[0].Cells[0].Paragraphs.First().IndentationBefore = -2f;
            tFooter.Rows[0].Cells[0].MarginLeft  = 50;
            tFooter.Rows[0].Cells[3].MarginRight = 10;
            tFooter.Rows[0].Cells[0].Width       = 160;
            tFooter.Rows[0].Cells[1].Width       = 150;
            tFooter.Rows[0].Cells[2].Width       = 150;
            tFooter.Rows[0].Cells[3].Width       = 160;
            tFooter.Rows[0].Cells[0].Paragraphs.First().Append("Экспедитор").Alignment     = Alignment.center;
            tFooter.Rows[0].Cells[1].Paragraphs.First().Append("Судовой агент").Alignment  = Alignment.center;
            tFooter.Rows[0].Cells[2].Paragraphs.First().Append("Линейный агент").Alignment = Alignment.center;
            tFooter.Rows[0].Cells[3].Paragraphs.First().Append("Таможня").Alignment        = Alignment.center;
            tFooter.Rows[1].Cells[0].Paragraphs.First().Append("Экспедитор\n").Alignment   = Alignment.left;
            tFooter.Rows[1].Cells[0].Paragraphs[0].Append("Глоба В. Л.\n").Alignment       = Alignment.left;
            tFooter.Rows[1].Cells[0].Paragraphs[0].Append("Тел.050-341-89-12").Alignment   = Alignment.left;
            tFooter.Rows[1].Cells[0].VerticalAlignment = VerticalAlignment.Bottom;
            foreach (var item in tFooter.Paragraphs)
            {
                item.Font("Times New Roman").FontSize(10).Bold();
            }
            document.MarginFooter = 15;

            Paragraph p1 = document.InsertParagraph();

            p1.Append(proforma[0]);
            if (arena.Checked == true)
            {
                p1.Append(proforma[1]).UnderlineStyle(UnderlineStyle.singleLine)
                .Append(Environment.NewLine).Append(proforma[2]);
            }
            else
            {
                p1.Append(proforma[29]).UnderlineStyle(UnderlineStyle.singleLine)
                .Append(Environment.NewLine).Append(proforma[30]);
            }
            Paragraph p2 = document.InsertParagraph();

            p2.Append(proforma[3] + " ").Append("«" + linesComboBox.Text + "»").UnderlineStyle(UnderlineStyle.singleLine).SpacingAfter(8).Alignment = Alignment.right;

            Paragraph p3   = document.InsertParagraph();
            DateTime  date = DateTime.Now;

            p3.Append(proforma[4] + " " + errendNumber.Text + " от «" + date.Day.ToString("d2") + "» " + months[date.Month - 1] + " " + date.Year + " г." + Environment.NewLine + proforma[5])
            .Append(proforma[6]).UnderlineStyle(UnderlineStyle.singleLine).Append(proforma[7]).SpacingAfter(8).Alignment = Alignment.center;

            Paragraph p4 = document.InsertParagraph();

            p4.Append(proforma[8] + " ").Append(senderNameTextBox.Text.ToUpper() + Environment.NewLine).UnderlineStyle(UnderlineStyle.singleLine)
            .Append(senderAddressTextBox.Text.ToUpper() + Environment.NewLine).UnderlineStyle(UnderlineStyle.singleLine)
            .Append("Код: " + senderCodTextBox.Text).UnderlineStyle(UnderlineStyle.singleLine)
            .SpacingAfter(8);

            Paragraph p5 = document.InsertParagraph();

            p5.Append(proforma[9] + " ").Append(receiverComboBox.Text.ToUpper() + Environment.NewLine).UnderlineStyle(UnderlineStyle.singleLine)
            .Append(receiverAddressTextBox.Text.ToUpper()).UnderlineStyle(UnderlineStyle.singleLine);

            Table t1 = document.AddTable(5, 2);

            Xceed.Words.NET.Border b = new Xceed.Words.NET.Border(Xceed.Words.NET.BorderStyle.Tcbs_none, BorderSize.five, 0, System.Drawing.Color.White);
            t1.SetBorder(TableBorderType.InsideH, b);
            t1.SetBorder(TableBorderType.InsideV, b);
            t1.SetBorder(TableBorderType.Bottom, b);
            t1.SetBorder(TableBorderType.Top, b);
            t1.SetBorder(TableBorderType.Left, b);
            t1.SetBorder(TableBorderType.Right, b);

            t1.Rows[0].Cells[0].Width       = 285;
            t1.Rows[0].Cells[1].MarginRight = 230;
            t1.Rows[1].Cells[0].Paragraphs.First().Append(proforma[10] + " ").Append("«" + vesselsComboBox.Text.ToUpper() + "»").UnderlineStyle(UnderlineStyle.singleLine).SpacingAfter(8);
            t1.Rows[1].Cells[1].Paragraphs.First().Append(proforma[11] + " ").Append(voyageComboBox.Text.ToUpper()).UnderlineStyle(UnderlineStyle.singleLine).Append("  " + proforma[12] + " ").Append(seTextBox.Text.ToUpper()).UnderlineStyle(UnderlineStyle.singleLine).Append("  " + proforma[13] + " ").Append(flagTextBox.Text.ToUpper()).UnderlineStyle(UnderlineStyle.singleLine).SpacingAfter(8);
            t1.Rows[2].Cells[0].Paragraphs.First().Append(proforma[14] + " ").Append(proforma[15]).UnderlineStyle(UnderlineStyle.singleLine).SpacingAfter(8);
            t1.Rows[2].Cells[1].Paragraphs.First().Append(proforma[16] + " ").Append(podComboBox.Text.ToUpper()).UnderlineStyle(UnderlineStyle.singleLine).SpacingAfter(8);
            t1.Rows[3].Cells[0].Paragraphs.First().Append(proforma[17] + " ").Append(potComboBox.Text.ToUpper()).UnderlineStyle(UnderlineStyle.singleLine).SpacingAfter(8);
            t1.Rows[4].Cells[0].Paragraphs.First().Append(proforma[18] + " ").Append(cargoNameСomboBox.Text.ToUpper()).UnderlineStyle(UnderlineStyle.singleLine).SpacingAfter(8);
            t1.Rows[4].Cells[1].Paragraphs.First().Append(proforma[19] + " ").Append(cargoCodComboBox.Text).UnderlineStyle(UnderlineStyle.singleLine);
            document.InsertTable(t1);

            Paragraph p6 = document.InsertParagraph();

            p6.Append(proforma[20] + " ").Append(bookingTextBox.Text.ToUpper()).UnderlineStyle(UnderlineStyle.singleLine);

            Table t2 = document.AddTable(amountContPage1 + 1, 8);

            t2.Rows[0].Cells[0].MarginLeft = 40;
            t2.Rows[0].Cells[0].Paragraphs.First().Append("Номер контейнера").Alignment = Alignment.center;
            t2.Rows[0].Cells[0].Paragraphs.First().IndentationBefore                    = -1f;
            t2.Rows[0].Cells[1].Paragraphs.First().Append("Тип").Alignment              = Alignment.center;
            t2.Rows[0].Cells[2].Paragraphs.First().Append("Кол-во Мест").Alignment      = Alignment.center;
            t2.Rows[0].Cells[3].Paragraphs.First().Append("Вес груза нетто").Alignment  = Alignment.center;
            t2.Rows[0].Cells[4].Paragraphs.First().Append("Вес груза брутто").Alignment = Alignment.center;
            t2.Rows[0].Cells[5].Paragraphs.First().Append("VGM перепро-веренный вес к-ра брутто**").Alignment = Alignment.center;
            t2.Rows[0].Cells[6].Paragraphs.First().Append("Пломбы").Alignment = Alignment.center;
            t2.Rows[0].Cells[6].Width       = 350;
            t2.Rows[0].Cells[7].MarginRight = 10;
            t2.Rows[0].Cells[7].Paragraphs.First().Append("ГТД").Alignment = Alignment.center;
            for (int i = 0; i < amountContPage1; i++)
            {
                t2.Rows[i + 1].Cells[0].Paragraphs.First().Append(vr.Values[i][0].ToString()).Alignment = Alignment.center;
                t2.Rows[i + 1].Cells[1].Paragraphs.First().Append(contSizeComboBox.Text + contTypeComboBox.Text).Alignment = Alignment.center;
                t2.Rows[i + 1].Cells[2].Paragraphs.First().Append(vr.Values[i][13].ToString().ToUpper() == "НАВАЛ" || vr.Values[i][13].ToString().ToUpper() == "" ? "НАВАЛ" : vr.Values[i][13].ToString()).Alignment = Alignment.center;
                t2.Rows[i + 1].Cells[3].Paragraphs.First().Append(vr.Values[i][4].ToString()).Alignment = Alignment.center;
                t2.Rows[i + 1].Cells[4].Paragraphs.First().Append(vr.Values[i][5].ToString()).Alignment = Alignment.center;
                t2.Rows[i + 1].Cells[5].Paragraphs.First().Append(vr.Values[i][6].ToString()).Alignment = Alignment.center;

                if (vr.Values[i].Count == 20)
                {
                    t2.Rows[i + 1].Cells[6].Paragraphs.First().Append(vr.Values[i][19].ToString()).Alignment = Alignment.center;
                }
                else
                {
                    t2.Rows[i + 1].Cells[6].Paragraphs.First().Append("").Alignment = Alignment.center;
                }
                t2.Rows[i + 1].Cells[7].Paragraphs.First().Append(vr.Values[i][2].ToString()).Alignment = Alignment.center;
                if (vr.Values[i][2].ToString() == "")
                {
                    t2.Rows[0].Cells[7].Width = 500;
                }
                else
                {
                    t2.Rows[0].Cells[7].Width = 0;
                }
            }
            foreach (var item in t2.Rows[0].Cells)
            {
                item.VerticalAlignment = VerticalAlignment.Center;
            }
            document.InsertTable(t2);

            Paragraph p7 = document.InsertParagraph();

            p7.Append(proforma[21] + Environment.NewLine + proforma[22]).SpacingAfter(8).Alignment = Alignment.center;

            Paragraph p8 = document.InsertParagraph();

            p8.Append(proforma[23] + " " + vr.Values.Count + "x" + contSizeComboBox.Text + "` контейнер(ов). ").Append("ВЕС " + '\u2013' + " " + strWeight + " кг." + Environment.NewLine).UnderlineStyle(UnderlineStyle.singleLine)
            .Append(proforma[24]).Append(proforma[25]).UnderlineStyle(UnderlineStyle.singleLine).SetLineSpacing(LineSpacingType.Line, 1.7f);

            Paragraph p9 = document.InsertParagraph();

            p9.Append(proforma[26] + " ").Append("ПРР: " + lineInfTextBox.Text.ToUpper() + ", ГРН" + Environment.NewLine).UnderlineStyle(UnderlineStyle.singleLine)
            .Append("                            ");
            if (arena.Checked == true)
            {
                p9.Append(proforma[27]).UnderlineStyle(UnderlineStyle.singleLine);
            }
            else
            {
                p9.Append(proforma[31]).UnderlineStyle(UnderlineStyle.singleLine);
            }

            foreach (var item in document.Paragraphs)
            {
                item.Font("Times New Roman").FontSize(10).Bold();
            }
            document.Paragraphs[2].FontSize(11);

            if (secondPage)
            {
                p9.InsertPageBreakAfterSelf();
                Paragraph p10 = document.InsertParagraph();
                p10.Append(proforma[28] + " " + errendNumber.Text + " от «" + date.Day.ToString("d2") + "» " + months[date.Month - 1] + " " + date.Year + " г." + Environment.NewLine + proforma[5])
                .Append(proforma[6]).UnderlineStyle(UnderlineStyle.singleLine).Append(proforma[7]).SpacingAfter(8).Alignment = Alignment.center;

                Table t3 = document.AddTable(amounrContPage2 + 1, 8);
                t3.Rows[0].Cells[0].MarginLeft = 40;
                t3.Rows[0].Cells[0].Paragraphs.First().Append("Номер контейнера").FontSize(10).Alignment = Alignment.center;
                t3.Rows[0].Cells[0].Paragraphs.First().IndentationBefore = -1f;
                t3.Rows[0].Cells[1].Paragraphs.First().Append("Тип").FontSize(10).Alignment              = Alignment.center;
                t3.Rows[0].Cells[2].Paragraphs.First().Append("Кол-во Мест").FontSize(10).Alignment      = Alignment.center;
                t3.Rows[0].Cells[3].Paragraphs.First().Append("Вес груза нетто").FontSize(10).Alignment  = Alignment.center;
                t3.Rows[0].Cells[4].Paragraphs.First().Append("Вес груза брутто").FontSize(10).Alignment = Alignment.center;
                t3.Rows[0].Cells[5].Paragraphs.First().Append("VGM перепро-веренный вес к-ра брутто**").FontSize(10).Alignment = Alignment.center;
                t3.Rows[0].Cells[6].Paragraphs.First().Append("Пломбы").FontSize(10).Alignment = Alignment.center;
                t3.Rows[0].Cells[6].Width       = 350;
                t3.Rows[0].Cells[7].MarginRight = 10;
                t3.Rows[0].Cells[7].Paragraphs.First().Append("ГТД").FontSize(10).Alignment = Alignment.center;
                for (int i = 0; i < amounrContPage2; i++)
                {
                    t3.Rows[i + 1].Cells[0].Paragraphs.First().Append(vr.Values[i + 22][0].ToString()).FontSize(10).Alignment = Alignment.center;
                    t3.Rows[i + 1].Cells[1].Paragraphs.First().Append(contSizeComboBox.Text + contTypeComboBox.Text).FontSize(10).Alignment = Alignment.center;
                    t3.Rows[i + 1].Cells[2].Paragraphs.First().Append(vr.Values[i + 22][13].ToString().ToUpper() == "НАВАЛ" || vr.Values[i + 22][13].ToString().ToUpper() == "" ? "НАВАЛ" : vr.Values[i + 22][13].ToString()).FontSize(10).Alignment = Alignment.center;
                    t3.Rows[i + 1].Cells[3].Paragraphs.First().Append(vr.Values[i + 22][4].ToString()).FontSize(10).Alignment = Alignment.center;
                    t3.Rows[i + 1].Cells[4].Paragraphs.First().Append(vr.Values[i + 22][5].ToString()).FontSize(10).Alignment = Alignment.center;
                    t3.Rows[i + 1].Cells[5].Paragraphs.First().Append(vr.Values[i + 22][6].ToString()).FontSize(10).Alignment = Alignment.center;
                    if (vr.Values[i].Count == 20)
                    {
                        t3.Rows[i + 1].Cells[6].Paragraphs.First().Append(vr.Values[i + 22][19].ToString()).FontSize(10).Alignment = Alignment.center;
                    }
                    else
                    {
                        t3.Rows[i + 1].Cells[6].Paragraphs.First().Append("").FontSize(10).Alignment = Alignment.center;
                    }
                    t3.Rows[i + 1].Cells[7].Paragraphs.First().Append(vr.Values[i + 22][2].ToString()).FontSize(10).Alignment = Alignment.center;
                    if (vr.Values[i + 22][2].ToString() == "")
                    {
                        t3.Rows[0].Cells[7].Width = 500;
                    }
                    else
                    {
                        t3.Rows[0].Cells[7].Width = 0;
                    }
                }
                foreach (var item in t3.Rows[0].Cells)
                {
                    item.VerticalAlignment = VerticalAlignment.Center;
                }
                document.InsertTable(t3);

                Paragraph p11 = document.InsertParagraph();
                p11.Append(proforma[21] + Environment.NewLine + proforma[22]).SpacingAfter(8).FontSize(10).Alignment = Alignment.center;

                Paragraph p12 = document.InsertParagraph();
                p12.Append(proforma[23] + " " + vr.Values.Count + "x" + contSizeComboBox.Text + "` контейнер(ов)." + " ").FontSize(10).Append("ВЕС " + '\u2013' + " " + strWeight + " кг." + Environment.NewLine).UnderlineStyle(UnderlineStyle.singleLine).FontSize(10)
                .Append(proforma[24]).FontSize(10).Append(proforma[25]).FontSize(10).UnderlineStyle(UnderlineStyle.singleLine).SetLineSpacing(LineSpacingType.Line, 1.7f);

                Paragraph p13 = document.InsertParagraph();
                p13.Append(proforma[26] + " ").FontSize(10).Append("ПРР: " + lineInfTextBox.Text + ", ГРН" + Environment.NewLine).FontSize(10).UnderlineStyle(UnderlineStyle.singleLine)
                .Append("                            ").FontSize(10);

                if (arena.Checked == true)
                {
                    p9.Append(proforma[27]).FontSize(10).UnderlineStyle(UnderlineStyle.singleLine);
                }
                else
                {
                    p9.Append(proforma[31]).FontSize(10).UnderlineStyle(UnderlineStyle.singleLine);
                }

                foreach (var item in document.Paragraphs)
                {
                    item.Font("Times New Roman").Bold();
                }
                secondPage = false;
            }
            try
            {
                document.Save();
                Process.Start(@"" + Properties.Settings.Default["SavingPath"].ToString() + "\\" + linesComboBox.Text + "\\" + vesselsComboBox.Text + "\\" + senderComboBox.Text + " - Прч. " + errendNumber.Text + " - " + vr.Values.Count.ToString() + " конт. - " + countryСomboBox.Text + ".docx");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Example #17
0
        /// <summary>
        /// Create a document and add headers/footers with tables and pictures, paragraphs and charts.
        /// </summary>
        public static void CompanyReport()
        {
            Console.WriteLine("\tCompanyReport()");

            // Create a new document.
            using (DocX document = DocX.Create(MiscellaneousSample.MiscellaneousSampleOutputDirectory + @"CompanyReport.docx"))
            {
                // Add headers and footers.
                document.AddHeaders();
                document.AddFooters();

                // Define the pages header's picture in a Table. Odd and even pages will have the same headers.
                var oddHeader        = document.Headers.Odd;
                var headerFirstTable = oddHeader.InsertTable(1, 2);
                headerFirstTable.Design  = TableDesign.ColorfulGrid;
                headerFirstTable.AutoFit = AutoFit.Window;
                var upperLeftParagraph = oddHeader.Tables[0].Rows[0].Cells[0].Paragraphs[0];
                var logo = document.AddImage(MiscellaneousSample.MiscellaneousSampleResourcesDirectory + @"Phone.png");
                upperLeftParagraph.AppendPicture(logo.CreatePicture(30, 100));
                upperLeftParagraph.Alignment = Alignment.left;

                // Define the pages header's text in a Table. Odd and even pages will have the same footers.
                var upperRightParagraph = oddHeader.Tables[0].Rows[0].Cells[1].Paragraphs[0];
                upperRightParagraph.Append("Toms Telecom Annual report").Color(Color.White);
                upperRightParagraph.SpacingBefore(5d);
                upperRightParagraph.Alignment = Alignment.right;

                // Define the pages footer's picture in a Table.
                var oddFooter        = document.Footers.Odd;
                var footerFirstTable = oddFooter.InsertTable(1, 2);
                footerFirstTable.Design  = TableDesign.ColorfulGrid;
                footerFirstTable.AutoFit = AutoFit.Window;
                var lowerRightParagraph = oddFooter.Tables[0].Rows[0].Cells[1].Paragraphs[0];
                lowerRightParagraph.AppendPicture(logo.CreatePicture(30, 100));
                lowerRightParagraph.Alignment = Alignment.right;

                // Define the pages footer's text in a Table
                var lowerLeftParagraph = oddFooter.Tables[0].Rows[0].Cells[0].Paragraphs[0];
                lowerLeftParagraph.Append("Toms Telecom 2016").Color(Color.White);
                lowerLeftParagraph.SpacingBefore(5d);

                // Define Data in first page : a Paragraph.
                var paragraph = document.InsertParagraph();
                paragraph.AppendLine("Toms Telecom Annual report\n2016").Bold().FontSize(35).SpacingBefore(150d);
                paragraph.Alignment = Alignment.center;
                paragraph.InsertPageBreakAfterSelf();

                // Define Data in second page : a Bar Chart.
                document.InsertParagraph("").SpacingAfter(150d);
                var barChart    = new BarChart();
                var sales       = CompanyData.CreateSales();
                var salesSeries = new Series("Sales Per Month");
                salesSeries.Color = Color.GreenYellow;
                salesSeries.Bind(sales, "Month", "Sales");
                barChart.AddSeries(salesSeries);
                document.InsertChart(barChart);
                document.InsertParagraph("Sales were 11% greater in 2016 compared to 2015, with the usual drop during spring time.").SpacingBefore(35d).InsertPageBreakAfterSelf();

                // Define Data in third page : a Line Chart.
                document.InsertParagraph("").SpacingAfter(150d);
                var lineChart  = new LineChart();
                var calls      = CompanyData.CreateCallNumber();
                var callSeries = new Series("Call Number Per Month");
                callSeries.Bind(calls, "Month", "Calls");
                lineChart.AddSeries(callSeries);
                document.InsertChart(lineChart);
                document.InsertParagraph("The number of calls received was much lower in 2016 compared to 2015, by 31%. Winter is still the busiest time of year.").SpacingBefore(35d);

                // Save this document to disk.
                document.Save();
                Console.WriteLine("\tCreated: CompanyReport.docx\n");
            }
        }
Example #18
0
        public static DocX CreateDocA(DocX template, UnogViewModel model)
        {
            string sym = model.Sym.ToString();

            string[] SymStr    = sym.Split('/');
            string[] sym1      = SymStr.Skip(1).ToArray();
            string   Fsym      = String.Join("/", sym1);
            int      reppos    = 0;
            int      repposcom = 0;
            int      countpos  = 0;


            //Create Date for Header
            string Fdate = model.date.ToString();

            string[] d = Fdate.Split(' ');
            Fdate = d[0];
            Fdate = formatdate(Fdate, model);
            //Create Distrbution for Header
            string Fdist = getDist(model);
            //document Language "Section"
            string Ftlang = "";

            Ftlang = Tlanguage(model.lang_ID);
            //ORiginal Language
            string Folang = "";

            Folang = Olanguage1(model.Olang_ID);
            string FAuthor = "";

            //Typist
            if (!String.IsNullOrEmpty(model.Author))
            {
                FAuthor = model.Author.ToString();
            }
            //Agenda Title
            string Fatitle = "";

            if (!String.IsNullOrEmpty(model.AgendaItem))
            {
                Fatitle = model.AgendaItem.ToString();
            }
            //Session Title
            string Fstitle = "";

            if (!String.IsNullOrEmpty(model.STitle))
            {
                Fstitle = model.STitle.ToString();
            }
            //Session Dates
            string Fsdate = "";

            if (model.Sdate != null & model.Edate != null)
            {
                string   sdate = model.Sdate.ToString();
                string[] sd    = sdate.Split(' ');
                sdate = sd[0];
                sdate = formatdate(sdate, model);

                string   edate = model.Edate.ToString();
                string[] ed    = edate.Split(' ');
                edate = ed[0];
                edate = formatdate(edate, model);


                Fsdate = SessionDate(sdate, edate, model);
            }

            //Agenda Number
            string Fanum = "";

            if (!String.IsNullOrEmpty(model.AgendaNum))
            {
                Fanum = model.AgendaNum.ToString();
            }
            //Session Numer
            string Fsnum = "";

            if (!String.IsNullOrEmpty(model.SNum))
            {
                Fsnum = Sessionnum(model);
            }

            ///
            //Report num and count

            string structure = model.structure.ToString();

            string[] str = structure.Split('/');
            for (int i = 0; i < str.Length; i++)
            {
                if (str[i] == "#")
                {
                    reppos = i;
                }
                if (str[i] == "ISO")
                {
                    countpos = i;
                }
                if (str[i] == "R.#")
                {
                    repposcom = i;
                }
            }

            string Fprep = "";

            if (reppos != 0 && countpos != 0)
            {
                Fprep = Reportnumber(model, SymStr[reppos], model.lang_ID, SymStr[countpos]);
            }
            if (repposcom != 0 && countpos != 0)
            {
                string x     = SymStr[repposcom];
                int    start = x.IndexOf('.');
                string prep  = x.Substring(start, x.Count() - 1);

                Fprep = Reportnumber(model, prep, model.lang_ID, SymStr[countpos]);
            }

            string fCount = "";

            if (countpos != 0)
            {
                fCount = getCount(SymStr[countpos], model);
            }


            //QR code and Bar code

            string lang = getlanguageQR(model.lang_ID);



            string url = "http://undocs.org/m2/QRCode.ashx?DS=" + Fsym + "&Size=2&Lang=" + lang;

            using (var client = new WebClient())
            {
                //var content = client.DownloadData("https://api.qrserver.com/v1/create-qr-code/?size=66x66&data=http://undocs.org/fr/A/HRC/70");
                //var content = client.DownloadData("http://undocs.org/m2/QRCode.ashx?DS=A/HRC/70&Size=2&Lang=F");
                var content = client.DownloadData(url);

                using (var str1 = new MemoryStream(content))
                {
                    Image   image = template.AddImage(str1);
                    Picture p     = image.CreatePicture();
                    Footer  f     = template.Footers.first;
                    Table   t     = f.Tables[0];
                    //t.Rows[0].Cells[1].Paragraphs.First().AppendPicture(pR);
                    t.Rows[0].Cells[1].Paragraphs.First().AppendPicture(p);
                }
            }

            //create barcode
            string Fbar = "";

            Fbar = model.Gdoc.ToString();
            Fbar = "*" + Fbar + "*";

            //creat gdoc
            string gdoc = model.Gdoc.ToString();

            gdoc = gdoc.Insert(2, "-");

            //creat gdoc footer
            string Fgdocf = gdoc;


            DateTime xxx = DateTime.Now;

            template.AddCustomProperty(new CustomProperty("sym1", Fsym));
            template.AddCustomProperty(new CustomProperty("symh", sym));
            template.AddCustomProperty(new CustomProperty("dist", Fdist));
            template.AddCustomProperty(new CustomProperty("date", Fdate));
            template.AddCustomProperty(new CustomProperty("sdate", Fsdate));
            template.AddCustomProperty(new CustomProperty("virs", ""));
            template.AddCustomProperty(new CustomProperty("snum", Fsnum));
            template.AddCustomProperty(new CustomProperty("anum", Fanum));
            template.AddCustomProperty(new CustomProperty("count", fCount));
            template.AddCustomProperty(new CustomProperty("gdoc", gdoc));
            template.AddCustomProperty(new CustomProperty("gdocf", Fgdocf));
            template.AddCustomProperty(new CustomProperty("tlang", Ftlang));
            template.AddCustomProperty(new CustomProperty("atitle", Fatitle));
            template.AddCustomProperty(new CustomProperty("stitle", Fstitle));
            template.AddCustomProperty(new CustomProperty("prep", Fprep));
            template.AddCustomProperty(new CustomProperty("olang", Folang));
            template.AddCustomProperty(new CustomProperty("Author", FAuthor));
            template.AddCustomProperty(new CustomProperty("bar", Fbar));
            template.AddCustomProperty(new CustomProperty("Date-Generated", xxx));
            // template.AddCoreProperty("dc:title", sym);



            return(template);
        }
Example #19
0
        protected void Unnamed_Click(object sender, EventArgs e)
        {
            const int    yeH = 266;
            const int    yeW = 472;
            const double eventPhotoScalePercentage = 0.7;   // /100

            using (var _db = new Kronika106.Models.Kronika106DBContext())
            {
                contentList = (from EventComments comment in _db.Forum
                               //(comment.EventId.ToLower() == trueEvetId && ((forumType == ForumType.Event && comment.IsEvent) || (forumType == ForumType.EventPhotoGallery && comment.IsPhoto && comment.ThumbPath.Contains(photoName))))
                               orderby comment.ID ascending
                               select new PageContent {
                    ID = comment.ID, CreatedUTC = comment.CreatedUTC, EventId = comment.EventId, RootID = comment.RootID, ThumbPath = comment.ThumbPath, ScoutNickName = comment.ApplicationUser.ScoutNickName, NickName = comment.ApplicationUser.NickName, Comment = comment.Comment, IsVideo = comment.IsVideo, IsEvent = comment.IsEvent, IsPhoto = comment.IsPhoto, UserID = comment.ApplicationUser.Id, UserName = comment.ApplicationUser.UserName                                    /*, VideoPosition= comment.VideoPosition */
                }).ToList();
            }
            if (contentList == null || contentList.Count == 0)
            {
                return;
            }

            string now = DateTime.Now.ToString("yyyyMMddHHmmss");

            string pthAppData   = Server.MapPath("..\\App_Data");
            string pthAllPhotos = Server.MapPath("..\\AllPhotos");

            DirectoryInfo dAllPhotosInfo = new DirectoryInfo(pthAllPhotos);
            List <string> lstDocFiles    = new List <string>();

            foreach (var dYear in dAllPhotosInfo.GetDirectories())
            {
                //rok
                //DateTime.Now.ToString("yyyyMMddHHmmss")
                string fileName     = $"kronika106_{dYear.Name}_{now}.docx";
                string fileFullPath = System.IO.Path.Combine(pthAppData, fileName);
                doc = DocX.Create(fileFullPath);
                doc.InsertSection();
                doc.InsertParagraph(dYear.Name, false, formatYear).Heading(HeadingType.Heading1).SpacingAfter(25d).Alignment = Alignment.center;
                var yImage      = doc.AddImage(Path.Combine(dYear.FullName, GlobalConstants.fnRokFotka));
                var pYImageYear = doc.InsertParagraph();
                pYImageYear.AppendPicture(yImage.CreatePicture(yeH, yeW)).SpacingAfter(20d).Alignment = Alignment.center;


                var yPopisPath = Path.Combine(dYear.FullName, GlobalConstants.fnRokPopis);
                if (System.IO.File.Exists(yPopisPath))
                {
                    doc.InsertParagraph(System.IO.File.ReadAllText(yPopisPath), false, formatText).SpacingAfter(20d).Alignment = Alignment.both;
                }
                doc.InsertSectionPageBreak();

                //toto rozdelit na zanostatny paragraf pre obrazok a pre text
                foreach (var dAkcia in dYear.GetDirectories())
                {
                    doc.InsertParagraph(dAkcia.Name, false, formatAkcia).Heading(HeadingType.Heading2).SpacingAfter(15d).Alignment = Alignment.center;
                    string eventImagePath = Path.Combine(dAkcia.FullName, GlobalConstants.fnAkciaFotka);
                    if (File.Exists(eventImagePath))
                    {
                        var pImageEvent = doc.InsertParagraph();
                        var yImageEvent = doc.AddImage(eventImagePath);
                        pImageEvent.AppendPicture(yImageEvent.CreatePicture(yeH, yeW)).SpacingAfter(15d).Alignment = Alignment.center;
                    }

                    string eventDescriptionPath = Path.Combine(dAkcia.FullName, GlobalConstants.fnAkciaPopis);
                    if (File.Exists(eventDescriptionPath))
                    {
                        doc.InsertParagraph(File.ReadAllText(eventDescriptionPath), false, formatText).SpacingAfter(15d).Alignment = Alignment.both;
                    }

                    string dbEventId = dAkcia.FullName.Replace(pthAllPhotos, "").TrimStart('\\').Replace("\\", "/");
                    commentTree(dbEventId, null, ref doc, ForumType.Event);

                    //precitat fotky:
                    foreach (var ePhoto in dAkcia.GetFiles("*.jpg"))
                    {
                        //vynechame uvodny obrazok
                        if (ePhoto.Name.Equals(GlobalConstants.fnAkciaFotka))
                        {
                            continue;
                        }
                        var pPhotoEvent = doc.InsertParagraph();
                        var yPhotoEvent = doc.AddImage(ePhoto.FullName);
                        var pct         = yPhotoEvent.CreatePicture();
                        pct.Width  = (int)Math.Round(pct.Width * eventPhotoScalePercentage, 0);
                        pct.Height = (int)Math.Round(pct.Height * eventPhotoScalePercentage, 0);

                        pPhotoEvent.AppendPicture(pct).SpacingAfter(5d).SpacingBefore(8d).Alignment = Alignment.center;

                        //tu najst podla nazvu akcie a fotky komnetare  a doplmnit -usera

                        commentTree(dbEventId, ePhoto.Name, ref doc, ForumType.EventPhotoGallery);
                    }
                    doc.InsertSectionPageBreak();
                }
                doc.Save();
                lstDocFiles.Add(fileFullPath);
            }
            string zipFileName = Path.Combine(pthAppData, $"Kronika2Word_{now}.zip");

            createZipFile(zipFileName, lstDocFiles);

            //mama zip zmazeme
            foreach (var file in lstDocFiles)
            {
                System.IO.File.Delete(file);
            }

            //upload na klienta
            FileInfo fInfo = new FileInfo(zipFileName);

            Response.Clear();
            Response.ClearHeaders();
            Response.ClearContent();
            Response.AddHeader("Content-Disposition", "attachment; filename=" + fInfo.Name);
            Response.AddHeader("Content-Length", fInfo.Length.ToString());
            Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            Response.Flush();
            Response.TransmitFile(fInfo.FullName);
            Response.End();

            foreach (var file in lstDocFiles)
            {
                System.IO.File.Delete(file);
            }
        }
Example #20
0
        /// <summary>
        /// 產生制式化文件
        /// </summary>
        public static void CreateDocX_FormulatedDocument(FileInfo fi)
        {
            // 參數。應該自外帶入。此處為測試,寫在裡面。
            var info = new
            {
                postDate   = "2015/12/07",
                custName   = "歐陽重天",
                custAddr1  = "11265台北市北投區",
                custAddr2  = "沒這條路三段66號2樓之1",
                caseNo     = "201205-990137",
                disputeAmt = 7530,
                flag1      = false,
                flag2      = true,
                flag3      = false,
                flag4      = true,
                otherDesc  = "沒錢可付只好洗碗"
            };

            using (DocX doc = DocX.Create(fi.FullName))
            {
                //Add custom properties to document.
                doc.AddCustomProperty(new CustomProperty("CompanyName", "亞洲志遠科技"));
                doc.AddCustomProperty(new CustomProperty("Product", "DocX練習"));
                doc.AddCustomProperty(new CustomProperty("Address", "新北市中正路755號7樓"));
                doc.AddCustomProperty(new CustomProperty("Date", DateTime.Now));

                // resource
                Font fontC = new Font("標楷體");
                Font fontE = new Font("Tahoma");
                Font fontN = new Font("Verdana");
                Font fontG = new Font("微軟正黑體");

                // banner
                Image   image = doc.AddImage("Image2.png");
                Picture pic   = image.CreatePicture();
                doc.InsertParagraph()
                .AppendPicture(pic)
                .Alignment = Alignment.right;

                // prefix header
                doc.InsertParagraph()
                .Append(info.postDate).Font(fontE)
                .AppendLine()
                .AppendLine(info.custName).Font(fontC)
                .AppendLine()
                .AppendLine(info.custAddr1).Font(fontC)
                .AppendLine(info.custAddr2).Font(fontC)
                .AppendLine()
                .AppendLine();

                // title
                doc.InsertParagraph("爭議款結案通知書")
                .Font(fontC)
                .FontSize(20d)
                .SpacingAfter(10d)
                .Alignment = Alignment.center;

                // paragraph 1
                Paragraph p1 = doc.InsertParagraph();
                p1.Append("案件編號:").Append(info.caseNo).Font(fontN)
                .AppendLine("爭議金額:").Append(string.Format("NTD${0:N0}元", info.disputeAmt)).Font(fontN)
                .AppendLine();

                // paragraph 2
                Paragraph p2 = doc.InsertParagraph();
                p2.IndentationFirstLine = 1.0f; // 第一行縮排1公分
                p2.Append("台端於日前致電本行要求處理之爭議款項,已因下列原因結案,特發此函通知。")
                .AppendLine();

                // item 1
                Paragraph p2a = doc.InsertParagraph();
                p2a.IndentationBefore    = 1.0f; // 凸排一公分
                p2a.IndentationFirstLine = -1.0f;
                p2a.Append(info.flag1 ? "■" : "□")
                .Append(" 1.\t商店同意退回上述爭議款款項,因本行於您提出爭議時即以「帳務調整爭議款」之科目先行調整您的信用卡帳務,現爭議款確定無須支付,本行將逕做結案處理。")
                .SpacingAfter(10d);

                // item 2
                Paragraph p2b = doc.InsertParagraph();
                p2b.IndentationBefore    = 1.0f; // 凸排一公分
                p2b.IndentationFirstLine = -1.0f;
                p2b.Append(info.flag2 ? "■" : "□")
                .Append(" 2.\t商店主動退回上述爭議款款項,此筆退款將出現於您近期帳單中,敬請查核。")
                .AppendLine()
                .SpacingAfter(10d);

                // item 3
                Paragraph p2c = doc.InsertParagraph();
                p2c.IndentationBefore    = 1.0f; // 凸排一公分
                p2c.IndentationFirstLine = -1.0f;
                p2c.Append(info.flag3 ? "■" : "□")
                .Append(" 3.\t商店同意退回上述爭議款款項,本行已於近期帳單中以「帳務調整爭議款」科目退款給您。")
                .SpacingAfter(10d);

                // item 4
                Paragraph p2d = doc.InsertParagraph();
                p2d.IndentationBefore    = 1.0f; // 凸排一公分
                p2d.IndentationFirstLine = -1.0f;
                p2d.Append(info.flag4 ? "■" : "□")
                .Append(" 4.\t其他:")
                .Append(info.otherDesc + new string(' ', 30 - info.otherDesc.Length) + ".").UnderlineStyle(UnderlineStyle.singleLine)
                .SpacingAfter(10d);

                // tail
                doc.InsertParagraph().AppendLine("謹祝  商祺")
                .Font(fontG);
                doc.InsertParagraph().AppendLine("千陽號銀行信用卡爭議帳款小組 敬上")
                .Font(fontG)
                .Alignment = Alignment.right;

                // Save this document.
                doc.Save();
            }
        }
Example #21
0
        private void btnGenForm_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(cmbSubj.Text) || string.IsNullOrEmpty(txtLock.Text) || string.IsNullOrEmpty(txtIssued.Text) || string.IsNullOrEmpty(txtDate.Text) || string.IsNullOrEmpty(txtProf.Text) || string.IsNullOrEmpty(txtSched.Text) || string.IsNullOrEmpty(txtStud1.Text) || string.IsNullOrEmpty(txtName1.Text))
            {
                MessageBox.Show("Fill in the missing fields");
            }
            else
            {
                string           sMessageBoxText = "Are all fields accounted form?";
                string           sCaption        = "Generate issuance form";
                MessageBoxButton btnMessageBox   = MessageBoxButton.YesNoCancel;
                MessageBoxImage  icnMessageBox   = MessageBoxImage.Warning;

                MessageBoxResult dr = MessageBox.Show(sMessageBoxText, sCaption, btnMessageBox, icnMessageBox);
                switch (dr)
                {
                case MessageBoxResult.Yes:
                    bool success = false;
                    foreach (var item in items)     //VALIDATION CHECKING
                    {
                        if (string.IsNullOrEmpty(item.manuf))
                        {
                            MessageBox.Show("One or more manufacturing fields are empty, please fill all out.");
                            return;
                        }
                        SqlCeConnection conn = DBUtils.GetDBConnection();
                        conn.Open();
                        int maxQty = 0;

                        using (SqlCeCommand cmd = new SqlCeCommand("SELECT qty from ApparatusInventory where name = @name and manuf = @manuf and (size IS null or size = @size)", conn))
                        {
                            cmd.Parameters.AddWithValue("@size", item.size);
                            cmd.Parameters.AddWithValue("@manuf", item.manuf);
                            cmd.Parameters.AddWithValue("@name", item.inventName);
                            using (DbDataReader reader = cmd.ExecuteResultSet(ResultSetOptions.Scrollable))
                            {
                                if (reader.HasRows)
                                {
                                    while (reader.Read())
                                    {
                                        int qtyIndex = reader.GetOrdinal("qty");
                                        maxQty = Convert.ToInt32(reader.GetValue(qtyIndex));
                                    }
                                }
                            }

                            if (item.qty > maxQty)
                            {
                                var found = items.FirstOrDefault(x => (x.inventName == item.inventName) && (x.manuf == item.manuf) && ((x.size == item.size) || (x.size == null)));
                                if (found != null)
                                {
                                    MessageBox.Show("Item " + item.inventName + " size: " + item.size + " manufacturer: " + item.manuf + " has low stocks, quantity has been set to the quantity of available stocks");
                                    found.qty = maxQty;
                                    return;
                                }
                            }
                        }
                    }
                    studInfo.Add(new StudentInfo
                    {
                        studName = txtName1.Text,
                        studNo   = txtStud1.Text
                    });
                    if (string.IsNullOrEmpty(txtStud2.Text) && txtName2.Text.Length > 0)
                    {
                        MessageBox.Show("Please fill up the missing student field!");
                        txtStud2.Focus();
                        return;
                    }
                    else if (string.IsNullOrEmpty(txtName2.Text) && txtStud2.Text.Length > 0)
                    {
                        MessageBox.Show("Please fill up the missing student field!");
                        txtName2.Focus();
                        return;
                    }
                    else if (txtName2.Text.Length > 0 && txtStud2.Text.Length > 0)
                    {
                        studInfo.Add(new StudentInfo
                        {
                            studName = txtName2.Text,
                            studNo   = txtStud2.Text
                        });
                    }

                    if (string.IsNullOrEmpty(txtStud3.Text) && txtName3.Text.Length > 0)
                    {
                        MessageBox.Show("Please fill up the missing student field!");
                        txtStud3.Focus();
                        return;
                    }
                    else if (string.IsNullOrEmpty(txtName3.Text) && txtStud3.Text.Length > 0)
                    {
                        MessageBox.Show("Please fill up the missing student field!");
                        txtName3.Focus();
                        return;
                    }
                    else if (txtName3.Text.Length > 0 && txtStud3.Text.Length > 0)
                    {
                        studInfo.Add(new StudentInfo
                        {
                            studName = txtName3.Text,
                            studNo   = txtStud3.Text
                        });
                    }

                    if (string.IsNullOrEmpty(txtStud4.Text) && txtName4.Text.Length > 0)
                    {
                        MessageBox.Show("Please fill up the missing student field!");
                        txtStud4.Focus();
                        return;
                    }
                    else if (string.IsNullOrEmpty(txtName4.Text) && txtStud4.Text.Length > 0)
                    {
                        MessageBox.Show("Please fill up the missing student field!");
                        txtName4.Focus();
                        return;
                    }
                    else if (txtName4.Text.Length > 0 && txtStud4.Text.Length > 0)
                    {
                        studInfo.Add(new StudentInfo
                        {
                            studName = txtName4.Text,
                            studNo   = txtStud4.Text
                        });
                    }

                    string user     = Environment.UserName;
                    string date     = txtDate.Text.Replace("/", "-");
                    string filename = @"C:\Users\" + user + @"\Desktop\[" + date + "][" + txtLock.Text + "][" + cmbSubj.Text + "][" + txtSect.Text + "].docx";
                    filename = filename.Replace(" ", "-");

                    using (DocX document = DocX.Create(filename))
                    {
                        document.MarginBottom = InchesToPoints(.5f);
                        document.MarginTop    = InchesToPoints(.5f);
                        document.MarginRight  = InchesToPoints(.5f);
                        string underline = "";

                        var image   = document.AddImage(@"resources/adulogo-blue.png");
                        var picture = image.CreatePicture(50, 200);

                        var p0 = document.InsertParagraph();
                        p0.AppendPicture(picture);

                        document.InsertParagraph();
                        var p1 = document.InsertParagraph("ISSUANCE FORM").Bold().FontSize(10)
                                 .Alignment = Alignment.right;

                        var p2 = document.InsertParagraph("PHARMACY LABORATORY").Bold().FontSize(8)
                                 .UnderlineColor(System.Drawing.Color.Black).SpacingAfter(15).Alignment = Alignment.right;


                        var t0 = document.AddTable(2, 1);
                        t0.Design    = TableDesign.None;
                        t0.Alignment = Alignment.right;

                        underline = returnCount(12, txtLock.Text);

                        t0.Rows[0].Cells[0].Paragraphs[0].Bold().Append("________").Bold().UnderlineStyle(UnderlineStyle.thick).Alignment = Alignment.center;
                        t0.Rows[0].Cells[0].Paragraphs[0].Bold().Append(txtLock.Text + underline).Bold().UnderlineStyle(UnderlineStyle.thick).Alignment = Alignment.center;     //LOCKER NO
                        underline = "";
                        t0.Rows[1].Cells[0].Paragraphs[0].Append("LOCKER NUMBER").Bold().Alignment = Alignment.center;

                        document.InsertTable(t0);

                        document.InsertParagraph();

                        var t1 = document.AddTable(2, 3);
                        t1.Design  = TableDesign.None;
                        t1.AutoFit = AutoFit.Window;

                        foreach (Row row in t1.Rows)
                        {
                            row.Cells[0].Width = 200;
                            row.Cells[1].Width = 200;
                            row.Cells[2].Width = 200;
                        }

                        t1.Rows[1].Cells[0].Paragraphs[0].Append("PROFESSOR").Bold().Alignment = Alignment.center;
                        t1.Rows[0].Cells[0].Paragraphs[0].Append("___").FontSize(10).Bold().UnderlineStyle(UnderlineStyle.thick).Alignment = Alignment.center;
                        t1.Rows[1].Cells[1].Paragraphs[0].Append("SCHEDULE").FontSize(10).Bold().Alignment = Alignment.center;
                        t1.Rows[0].Cells[1].Paragraphs[0].Append("_____").Bold().UnderlineStyle(UnderlineStyle.thick).Alignment = Alignment.center;
                        t1.Rows[1].Cells[2].Paragraphs[0].Append("SUBJECT AND SECTION").Bold().Alignment = Alignment.center;
                        t1.Rows[0].Cells[2].Paragraphs[0].Append("__").FontSize(10).Bold().UnderlineStyle(UnderlineStyle.thick).Alignment = Alignment.center;

                        underline = returnCount(24, txtProf.Text);

                        t1.Rows[0].Cells[0].Paragraphs[0].Append(txtProf.Text + underline).FontSize(10).Bold().UnderlineStyle(UnderlineStyle.thick).FontSize(9).Alignment = Alignment.center;     //PROFESSOR
                        underline = "";

                        underline = returnCount(20, txtSched.Text);

                        t1.Rows[0].Cells[1].Paragraphs[0].Append(txtSched.Text + underline).FontSize(10).Bold().UnderlineStyle(UnderlineStyle.thick).Alignment = Alignment.center;     //SCHEDULE
                        underline = "";

                        underline = returnCount(25, txtSubject.Text + " " + txtSect.Text);

                        t1.Rows[0].Cells[2].Paragraphs[0].Append(txtSubject.Text + " " + txtSect.Text + underline).FontSize(9).Bold().UnderlineStyle(UnderlineStyle.thick).Alignment = Alignment.center;     //SUBJECT
                        underline = "";
                        document.InsertTable(t1);

                        document.InsertParagraph();     //newline

                        var t2 = document.AddTable(26, 6);
                        t2.Design  = TableDesign.TableGrid;
                        t2.AutoFit = AutoFit.Window;

                        foreach (Row row in t2.Rows)
                        {
                            row.Cells[0].Width = 30;
                            row.Cells[1].Width = 120;
                            row.Cells[2].Width = 200;
                            row.Cells[3].Width = 40;
                            row.Cells[4].Width = 80;
                            row.Cells[5].Width = 50;
                        }

                        t2.Rows[0].Cells[0].Paragraphs[0].Append("QTY").Bold().Alignment = Alignment.center;
                        t2.Rows[0].Cells[0].VerticalAlignment = Xceed.Words.NET.VerticalAlignment.Bottom;
                        t2.Rows[0].Cells[1].Paragraphs[0].Append("APPARATUS").Bold().Alignment = Alignment.center;
                        t2.Rows[0].Cells[1].VerticalAlignment = Xceed.Words.NET.VerticalAlignment.Bottom;
                        t2.Rows[0].Cells[2].Paragraphs[0].Append("SIZE / BRAND / REMARKS").Bold().Alignment = Alignment.center;
                        t2.Rows[0].Cells[2].VerticalAlignment = Xceed.Words.NET.VerticalAlignment.Bottom;
                        t2.Rows[0].Cells[3].Paragraphs[0].Append("RTN").Bold().Alignment       = Alignment.center;
                        t2.Rows[0].Cells[3].Paragraphs[0].AppendLine("CHK").Bold().Alignment   = Alignment.center;
                        t2.Rows[0].Cells[4].Paragraphs[0].Append("BREAKAGES").Bold().Alignment = Alignment.center;
                        t2.Rows[0].Cells[4].VerticalAlignment = Xceed.Words.NET.VerticalAlignment.Bottom;
                        t2.Rows[0].Cells[5].Paragraphs[0].Append("AMOUNT").Bold().Alignment     = Alignment.center;
                        t2.Rows[0].Cells[5].Paragraphs[0].AppendLine("CHARGE").Bold().Alignment = Alignment.center;

                        //INSERTION OF ITEMS REQUESTED TO DATABASE AND WORD FILE
                        SqlCeConnection conn = DBUtils.GetDBConnection();
                        conn.Open();

                        int rowx = 1;
                        foreach (var items in items)
                        {
                            if (string.IsNullOrEmpty(items.manuf))
                            {
                                MessageBox.Show("One or more manufacturing fields are empty, please fill all out.");
                                return;
                            }
                            else
                            {
                                string prodCode = "";
                                using (SqlCeCommand cmd = new SqlCeCommand("SELECT prodCode from ApparatusInventory where name = @name and manuf = @manuf and (size IS null or size = @size)", conn))
                                {
                                    cmd.Parameters.AddWithValue("@name", items.inventName);
                                    cmd.Parameters.AddWithValue("@manuf", items.manuf);
                                    cmd.Parameters.AddWithValue("@size", items.size);
                                    using (DbDataReader reader = cmd.ExecuteResultSet(ResultSetOptions.Scrollable))
                                    {
                                        if (reader.HasRows)
                                        {
                                            while (reader.Read())
                                            {
                                                int prodCodeIndex = reader.GetOrdinal("prodCode");
                                                prodCode = Convert.ToString(reader.GetValue(prodCodeIndex));
                                            }
                                        }
                                    }
                                }
                                //////////////////////////////////////////////////////////////////////////////////////////////
                                t2.Rows[rowx].Cells[0].Paragraphs[0].Append(Convert.ToString(items.qty)).Bold().Alignment  = Alignment.center;    // QTY
                                t2.Rows[rowx].Cells[1].Paragraphs[0].Append(items.inventName).FontSize(8).Bold().Alignment = Alignment.center;    //INVENT NAME
                                if (!string.IsNullOrEmpty(items.size))
                                {
                                    t2.Rows[rowx].Cells[2].Paragraphs[0].Append(items.size + "/" + items.manuf + "/").Bold().Alignment = Alignment.center;     //APPENDING SIZE MANUF AND REMARKS
                                }
                                else
                                {
                                    t2.Rows[rowx].Cells[2].Paragraphs[0].Append(items.manuf + "/").Bold().Alignment = Alignment.center;    //APPENDING MANUF AND REMARKS
                                }

                                rowx++;
                                foreach (var student in studInfo)
                                {
                                    using (SqlCeCommand cmd = new SqlCeCommand("INSERT into IssuanceList (lockNo, prof, sched, subject, section, issuedDate, issuedBy, fullName, studentNo, prodCode, qty, breakage) VALUES (@lockNo, @prof, @sched, @subject, @section, @issuedDate, @issuedBy, @fullName, @studentNo, @prodCode, @qty, 0)", conn))
                                    {
                                        cmd.Parameters.AddWithValue("@lockNo", txtLock.Text);
                                        cmd.Parameters.AddWithValue("@prof", txtProf.Text);
                                        cmd.Parameters.AddWithValue("@sched", txtSched.Text);
                                        cmd.Parameters.AddWithValue("@subject", txtSubject.Text);
                                        cmd.Parameters.AddWithValue("@section", txtSect.Text);
                                        cmd.Parameters.AddWithValue("@issuedDate", txtDate.Text);
                                        cmd.Parameters.AddWithValue("@issuedBy", txtIssued.Text);
                                        cmd.Parameters.AddWithValue("@fullName", student.studName);
                                        cmd.Parameters.AddWithValue("@studentNo", student.studNo);
                                        cmd.Parameters.AddWithValue("@prodCode", prodCode);
                                        cmd.Parameters.AddWithValue("@qty", items.qty);
                                        try
                                        {
                                            int count = cmd.ExecuteNonQuery();
                                            if (count > 0)
                                            {
                                                success = true;
                                            }
                                        }
                                        catch (SqlCeException ex)
                                        {
                                            MessageBox.Show("Error! Log has been updated with the error.");
                                            Log = LogManager.GetLogger("*");
                                            Log.Error(ex, "Query Error");
                                        }
                                    }
                                }
                                using (SqlCeCommand cmd = new SqlCeCommand("UPDATE ApparatusInventory set qty = qty - @qty where prodCode = @prodCode", conn))
                                {
                                    cmd.Parameters.AddWithValue("@qty", items.qty);
                                    cmd.Parameters.AddWithValue("@prodCode", prodCode);
                                    try
                                    {
                                        cmd.ExecuteNonQuery();
                                    }
                                    catch (SqlCeException ex)
                                    {
                                        MessageBox.Show("Error! Log has been updated with the error.");
                                        Log = LogManager.GetLogger("*");
                                        Log.Error(ex, "Query Error");
                                    }
                                }
                            }
                        }
                        document.InsertTable(t2);


                        document.InsertParagraph();     //newline

                        var t3 = document.AddTable(2, 2);
                        t3.Design  = TableDesign.None;
                        t3.AutoFit = AutoFit.Window;

                        t3.Rows[0].Cells[0].Paragraphs[0].Append("ISSUED ON :         ").FontSize(9).Bold();
                        t3.Rows[1].Cells[0].Paragraphs[0].Append("ISSUED BY :          ").FontSize(9).Bold().Alignment = Alignment.left;
                        t3.Rows[0].Cells[1].Paragraphs[0].Append("RETURNED ON :_________________________").FontSize(9).Bold().Alignment   = Alignment.right;
                        t3.Rows[1].Cells[1].Paragraphs[0].Append("RECEIVED BY   :_________________________").FontSize(9).Bold().Alignment = Alignment.right;

                        underline = returnCount(19, txtDate.Text);

                        t3.Rows[0].Cells[0].Paragraphs[0].Append("__" + txtDate.Text + underline).FontSize(9).Bold().UnderlineStyle(UnderlineStyle.thick).Alignment = Alignment.left;     // ISSUED DATE
                        underline = "";

                        underline = returnCount(19, txtIssued.Text);

                        t3.Rows[1].Cells[0].Paragraphs[0].Append("__" + txtIssued.Text + underline).UnderlineStyle(UnderlineStyle.thick).FontSize(9).Bold().Alignment = Alignment.left;     // ISSUED BY
                        underline = "";

                        document.InsertTable(t3);


                        document.InsertParagraph();
                        var p5 = document.InsertParagraph(@"                I/We, the undersigned, acknowledge to have received the apparatus above clean, dry and in good condition. Said articles are to be returned upon the termination of the semester clean, dry and in good condition.").FontSize(10).Bold().Alignment = Alignment.both;

                        document.InsertParagraph();

                        var p6 = document.InsertParagraph("FILL THE BLANKS PROPERLY AND IN PRINT").Bold().UnderlineStyle(UnderlineStyle.singleLine);

                        document.InsertParagraph();

                        var t4 = document.AddTable(5, 4);
                        t4.Design  = TableDesign.None;
                        t4.AutoFit = AutoFit.Window;

                        foreach (Row row in t4.Rows)
                        {
                            row.Cells[0].Width = 180;
                            row.Cells[1].Width = 120;
                            row.Cells[2].Width = 80;
                            row.Cells[3].Width = 80;
                        }

                        t4.Rows[0].Cells[0].Paragraphs[0].Append("   SURNAME         FIRST NAME        M.I.").FontSize(9).Bold();
                        t4.Rows[0].Cells[1].Paragraphs[0].Append("STUDENT NUMBER").FontSize(9).Bold().Alignment = Alignment.center;
                        t4.Rows[0].Cells[2].Paragraphs[0].Append("COURSE").FontSize(9).Bold().Alignment         = Alignment.center;
                        t4.Rows[0].Cells[3].Paragraphs[0].Append("SIGNATURE").FontSize(9).Bold().Alignment      = Alignment.center;

                        t4.Rows[1].Cells[0].Paragraphs[0].Append("1. ").Bold().FontSize(9);
                        t4.Rows[2].Cells[0].Paragraphs[0].Append("2. ").Bold().FontSize(9);
                        t4.Rows[3].Cells[0].Paragraphs[0].Append("3. ").Bold().FontSize(9);
                        t4.Rows[4].Cells[0].Paragraphs[0].Append("4. ").Bold().FontSize(9);

                        underline = returnCount(36, txtName1.Text);

                        t4.Rows[1].Cells[0].Paragraphs[0].Append("_" + txtName1.Text + underline).UnderlineStyle(UnderlineStyle.thick).Bold().FontSize(9);     //STUDENT NAME
                        underline = "";

                        underline = returnCount(36, txtName2.Text);

                        t4.Rows[2].Cells[0].Paragraphs[0].Append("_" + txtName2.Text + underline).UnderlineStyle(UnderlineStyle.thick).Bold().FontSize(9);     //STUDENT NAME
                        underline = "";

                        underline = returnCount(36, txtName3.Text);

                        t4.Rows[3].Cells[0].Paragraphs[0].Append("_" + txtName3.Text + underline).UnderlineStyle(UnderlineStyle.thick).Bold().FontSize(9);     //STUDENT NAME
                        underline = "";

                        underline = returnCount(36, txtName4.Text);

                        t4.Rows[4].Cells[0].Paragraphs[0].Append("_" + txtName4.Text + underline).UnderlineStyle(UnderlineStyle.thick).Bold().FontSize(9);     //STUDENT NAME
                        underline = "";

                        t4.Rows[1].Cells[1].Paragraphs[0].Append("____").UnderlineStyle(UnderlineStyle.thick).FontSize(9);
                        t4.Rows[2].Cells[1].Paragraphs[0].Append("____").UnderlineStyle(UnderlineStyle.thick).FontSize(9);
                        t4.Rows[3].Cells[1].Paragraphs[0].Append("____").UnderlineStyle(UnderlineStyle.thick).FontSize(9);
                        t4.Rows[4].Cells[1].Paragraphs[0].Append("____").UnderlineStyle(UnderlineStyle.thick).FontSize(9);

                        underline = returnCount(16, txtStud1.Text);

                        t4.Rows[1].Cells[1].Paragraphs[0].Append(txtStud1.Text + underline).UnderlineStyle(UnderlineStyle.thick).Bold().FontSize(9);     //STUDENT NO
                        underline = "";

                        underline = returnCount(16, txtStud2.Text);
                        t4.Rows[2].Cells[1].Paragraphs[0].Append(txtStud2.Text + underline).UnderlineStyle(UnderlineStyle.thick).Bold().FontSize(9);     //STUDENT NO
                        underline = "";

                        underline = returnCount(16, txtStud3.Text);
                        t4.Rows[3].Cells[1].Paragraphs[0].Append(txtStud3.Text + underline).UnderlineStyle(UnderlineStyle.thick).Bold().FontSize(9);     //STUDENT NO
                        underline = "";

                        underline = returnCount(16, txtStud4.Text);
                        t4.Rows[4].Cells[1].Paragraphs[0].Append(txtStud4.Text + underline).UnderlineStyle(UnderlineStyle.thick).Bold().FontSize(9);     //STUDENT NO

                        t4.Rows[1].Cells[2].Paragraphs[0].Append("_________________").UnderlineStyle(UnderlineStyle.thick).FontSize(9);
                        t4.Rows[2].Cells[2].Paragraphs[0].Append("_________________").UnderlineStyle(UnderlineStyle.thick).FontSize(9);
                        t4.Rows[3].Cells[2].Paragraphs[0].Append("_________________").UnderlineStyle(UnderlineStyle.thick).FontSize(9);
                        t4.Rows[4].Cells[2].Paragraphs[0].Append("_________________").UnderlineStyle(UnderlineStyle.thick).FontSize(9);

                        t4.Rows[1].Cells[3].Paragraphs[0].Append("_________________").UnderlineStyle(UnderlineStyle.thick).FontSize(9);
                        t4.Rows[2].Cells[3].Paragraphs[0].Append("_________________").UnderlineStyle(UnderlineStyle.thick).FontSize(9);
                        t4.Rows[3].Cells[3].Paragraphs[0].Append("_________________").UnderlineStyle(UnderlineStyle.thick).FontSize(9);
                        t4.Rows[4].Cells[3].Paragraphs[0].Append("_________________").UnderlineStyle(UnderlineStyle.thick).FontSize(9);
                        document.InsertTable(t4);

                        document.InsertParagraph();

                        var p7 = document.InsertParagraph("PHARMACY LABORATORY'S COPY").FontSize(9).Bold().Alignment = Alignment.center;


                        document.Save();
                        Process.Start("WINWORD.EXE", filename);
                    }
                    if (success)
                    {
                        Log = LogManager.GetLogger("generateIssuanceForm");
                        string newLine = System.Environment.NewLine;
                        Log.Info("A Issuance form has been generated with the following details: " + newLine +
                                 "Date Requested: " + txtDate.Text + newLine +
                                 "Subject: " + cmbSubj.Text + newLine +
                                 "Section: " + txtSect.Text + newLine +
                                 "Schedule: " + txtSched.Text + newLine +
                                 "Professor: " + txtProf.Text + newLine +
                                 "Locker No.: " + txtLock.Text + newLine +
                                 "Issued by: " + txtIssued.Text
                                 );
                        emptyFields();
                    }
                    break;

                case MessageBoxResult.No:
                    break;
                }
            }
        }
Example #22
0
        public static void CreateDocX_SimpleTable(FileInfo fi)
        {
            // Create a document.
            using (DocX document = DocX.Create(fi.FullName))
            {
                // Add a title
                document.InsertParagraph("Inserting table")
                .FontSize(20d)
                .Bold()
                .SpacingAfter(10d)
                .Alignment = Alignment.center;

                document.InsertParagraph()
                .Append("可在現有段落中插入Table。加入image等等。");

                // Add a Table into the document and sets its values.
                var t = document.AddTable(5, 2);
                t.Design    = TableDesign.ColorfulListAccent1;
                t.Alignment = Alignment.center;
                t.Rows[0].Cells[0].Paragraphs[0].Append("Mike");
                t.Rows[0].Cells[1].Paragraphs[0].Append("65");
                t.Rows[1].Cells[0].Paragraphs[0].Append("Kevin");
                t.Rows[1].Cells[1].Paragraphs[0].Append("62");
                t.Rows[2].Cells[0].Paragraphs[0].Append("Carl");
                t.Rows[2].Cells[1].Paragraphs[0].Append("60");
                t.Rows[3].Cells[0].Paragraphs[0].Append("Michael");
                t.Rows[3].Cells[1].Paragraphs[0].Append("59");
                t.Rows[4].Cells[0].Paragraphs[0].Append("Shawn");
                t.Rows[4].Cells[1].Paragraphs[0].Append("57");

                // Add a row at the end of the table and sets its values.
                var r = t.InsertRow();
                r.Cells[0].Paragraphs[0].Append("Mario");
                r.Cells[1].Paragraphs[0].Append("54");

                // Add a row at the end of the table which is a copy of another row, and sets its values.
                var newPlayer = t.InsertRow(t.Rows[2]);
                newPlayer.ReplaceText("Carl", "Max");
                newPlayer.ReplaceText("60", "50");

                // Add an image into the document.
                var image   = document.AddImage(@"Image2.png");
                var picture = image.CreatePicture(25, 100);

                // Calculate totals points from second column in table.
                var totalPts = 0;
                foreach (var row in t.Rows)
                {
                    totalPts += int.Parse(row.Cells[1].Paragraphs[0].Text);
                }

                // Add a row at the end of the table and sets its values.
                var totalRow = t.InsertRow();
                totalRow.Cells[0].Paragraphs[0].Append("Total for ").AppendPicture(picture);
                totalRow.Cells[1].Paragraphs[0].Append(totalPts.ToString());
                totalRow.Cells[1].VerticalAlignment = VerticalAlignment.Center;

                // Insert a new Paragraph into the document.
                var p = document.InsertParagraph("Xceed Top Players Points:");
                //p.SpacingAfter(40d);

                // Insert the Table after the Paragraph.
                p.InsertTableAfterSelf(t);

                //
                document.Save();
            }
        }
Example #23
0
        public byte[] OutputWordTest()
        {
            string templateFilePath = Path.Combine(HostingEnvironment.MapPath("~/ExcelTemplate"), "test0001.docx");
            DocX   document         = DocX.Load(templateFilePath);
            var    myImageFullPath  = @"C:\temp\FHM0I715F010202-163404.jpg";
            Image  image            = document.AddImage(myImageFullPath);

            // Create a picture (A custom view of an Image).
            Picture picture = image.CreatePicture();

            Table t = document.Tables[0];

            t.Rows[0].Cells[1].Paragraphs.First().Append("單據BB");
            t.Rows[0].Cells[3].Paragraphs.First().Append("計時制");
            t.Rows[1].Cells[1].Paragraphs.First().Append("停車單");
            t.Rows[1].Cells[3].Paragraphs.First().Append("NM-0998");
            t.Rows[2].Cells[1].Paragraphs.First().Append("自用小型車");
            t.Rows[2].Cells[3].Paragraphs.First().Append("0.5");
            t.Rows[3].Cells[1].Paragraphs.First().Append("未紀錄");
            t.Rows[3].Cells[3].Paragraphs.First().Append("中和區安和路");
            t.Rows[4].Cells[1].Paragraphs.First().Append("");
            t.Rows[4].Cells[3].Paragraphs.First().Append("");
            t.Rows[5].Cells[1].Paragraphs.First().Append("");
            t.Rows[5].Cells[3].Paragraphs.First().Append("");
            t.Rows[6].Cells[1].Paragraphs.First().Append("");
            t.Rows[6].Cells[3].Paragraphs.First().Append("");
            t.Rows[7].Cells[1].Paragraphs.First().Append("");
            t.Rows[7].Cells[3].Paragraphs.First().Append("");

            // Insert a new Paragraph into the document.
            Paragraph p1 = document.InsertParagraph();

            p1.AppendPicture(picture);

            //string filePath = @"C:\temp\word";

            ////建folder
            //if (!Directory.Exists(filePath))
            //    Directory.CreateDirectory(filePath);

            ////新完整檔名
            //string newFileName = "word.docx";
            ////檔案路徑 + 新完整檔名
            //string fullFilePath = Path.Combine(filePath, newFileName);

            //FileStream file = new FileStream(fullFilePath, FileMode.Create);//產生檔案
            //document.SaveAs(file);
            //file.Close();
            //GC.Collect();
            //return fullFilePath;

            MemoryStream stream = new MemoryStream();

            document.SaveAs(stream);
            byte[] fileBytes = stream.ToArray();
            stream.Close();
            stream.Dispose();
            GC.Collect();
            return(fileBytes);

            #region 使用url下載圖片
            //string ImageServer = WebConfigurationManager.AppSettings["ImageServerSite"];
            //string myImageFullPath = ImageServer + item.ParkMonth + "/" + item.ParkDate + "/" + item.FileName;
            //System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(myImageFullPath);
            //webRequest.AllowWriteStreamBuffering = true;
            //webRequest.Timeout = 30000;
            //System.Net.WebResponse webResponse;
            //try
            //{
            //    webResponse = webRequest.GetResponse();
            //}
            //catch (Exception ex)
            //{
            //    logger.Error($"單據明細docx檔下載發生例外:{item.FileName}{ex.Message}");
            //    continue;
            //}
            //Stream stream = webResponse.GetResponseStream();
            //System.Drawing.Image image2 = System.Drawing.Image.FromStream(stream);
            //webResponse.Close();

            //MemoryStream ms = new MemoryStream();
            //image2.Save(ms, image2.RawFormat);
            //Image image = document.AddImage(ms);

            //Picture picture = image.CreatePicture(200, 200);
            //p1.AppendPicture(picture);
            #endregion
        }
Example #24
0
        internal static string CreateDocX_SimpleTable3(Stream stream, List <TestResultInfo> testResultList)
        {
            try
            {
                // Create a document.
                Font defaultFont  = new Font("新細明體"); // 新細明體 微軟正黑體
                var  defaultColor = System.Drawing.Color.FromArgb(0, 112, 192);
                using (DocX document = DocX.Create(stream))
                {
                    // Add a title
                    document.InsertParagraph("上傳附件檔")
                    .Font(defaultFont)
                    .FontSize(20d)
                    .Color(defaultColor)
                    .SpacingBefore(8d)
                    .SpacingAfter(8d)
                    .Bold()
                    .Alignment = Alignment.center;

                    // Add an image into the document.
                    var      imageFolder = new DirectoryInfo(@"C:\GitHubRepos\DocXLab\DocXLab"); // < ------參數化
                    FileInfo imageFi     = new FileInfo(Path.Combine(imageFolder.FullName, "Test_Result.png"));
                    var      image       = document.AddImage(imageFi.FullName);
                    var      picture     = image.CreatePicture(109, 242);

                    // Add a Table into the document and sets its values.
                    var t = document.AddTable(testResultList.Count + 1, 3);
                    t.Design    = TableDesign.TableGrid;
                    t.Alignment = Alignment.center;
                    t.SetWidthsPercentage(new float[] { 33, 33, 34 }, 600);

                    // fill caption
                    t.Rows[0].Cells[0].Paragraphs[0].Append("序號")
                    .Font(defaultFont).Color(defaultColor).FontSize(16d).SpacingBefore(8d).SpacingAfter(8d);
                    t.Rows[0].Cells[1].Paragraphs[0].Append("姓名")
                    .Font(defaultFont).Color(defaultColor).FontSize(16d).SpacingBefore(8d).SpacingAfter(8d);
                    t.Rows[0].Cells[2].Paragraphs[0].Append("篩檢圖片")
                    .Font(defaultFont).Color(defaultColor).FontSize(16d).SpacingBefore(8d).SpacingAfter(8d);

                    // fill content
                    int rowIndex = 1;
                    foreach (var item in testResultList)
                    {
                        t.Rows[rowIndex].Cells[0].Paragraphs[0].Append($"{item.ItemSn}")
                        .Font(defaultFont).Color(defaultColor).FontSize(16d).SpacingBefore(8d).SpacingAfter(8d);
                        t.Rows[rowIndex].Cells[1].Paragraphs[0].Append(item.Name)
                        .Font(defaultFont).Color(defaultColor).FontSize(16d).SpacingBefore(8d).SpacingAfter(8d);
                        t.Rows[rowIndex].Cells[2].Paragraphs[0].AppendPicture(picture)
                        .Font(defaultFont).Color(defaultColor).FontSize(16d).SpacingBefore(8d).SpacingAfter(8d);

                        // next row
                        ++rowIndex;
                    }

                    document.InsertParagraph()
                    .InsertTableAfterSelf(t);

                    //
                    document.Save();
                    return("SUCCESS");
                }
            }
            catch (Exception ex)
            {
                return($"FAIL! {ex.Message}");
            }
        }
Example #25
0
        /// <summary>
        /// Initialize Word Report --> Support Method
        /// </summary>
        public static void InitSetupWord()
        {
            try
            {
                string directory = BaseUtilities.GetFolderPath();
                SetReportpath();
                resultdocument = DocX.Create(reportpath);
                //Resultdocument = DocX.Create(directory + @"Results\WordResults\Testrr.docx");

                resultdocument.AddHeaders();
                Header ResultHeader = resultdocument.Headers.Odd;

                Image   Headerimage = resultdocument.AddImage(Reports.reportheaderimage);
                Picture picture     = Headerimage.CreatePicture();
                picture.Width  = 150;
                picture.Height = 28;
                Paragraph Header = ResultHeader.InsertParagraph();
                Header.Alignment = Alignment.right;
                Header.AppendPicture(picture);

                Paragraph Date    = resultdocument.InsertParagraph();
                String    StrDate = System.DateTime.Today.ToString("dd-MM-yyyy");
                Paragraph date    = Date.Append("Date: " + StrDate).FontSize(8).Font("Calibri").Color(System.Drawing.Color.FromArgb(1, 74, 73, 71));
                date.Alignment = Alignment.left;



                Paragraph title = resultdocument.InsertParagraph().Append("Test Case Results").FontSize(20).Font("Century Gothic").Color(System.Drawing.Color.FromArgb(1, 91, 168));
                title.Alignment = Alignment.center;
                title.AppendLine();

                String[] Tableheading = { "Feature Name", "ALM TestSet Name", "Scenario Name", "Start Time", "End Time", "Time Taken", "Test Status" };
                String[] Tabledata    = { BaseUtilities.featureFileName, BaseUtilities.testSetName, BaseUtilities.scenarioName, Reports.starttime, Reports.endtime, Reports.timetaken, BaseUtilities.scenarioStatus };

                Table table = resultdocument.AddTable(Tableheading.Length, 2);
                // Specify some properties for this Table.
                table.Alignment = Alignment.center;
                table.AutoFit   = AutoFit.Contents;
                table.Design    = TableDesign.TableGrid;


                for (int row = 0; row < Tableheading.Length; row++)
                {
                    if (Tableheading[row].Trim().ToLower() == "test status")
                    {
                        switch (Tabledata[row].ToLower())
                        {
                        case "pass":

                            table.Rows[row].Cells[0].Paragraphs.First().Append(Tableheading[row]).Bold().Color(System.Drawing.Color.FromArgb(52, 168, 83));
                            table.Rows[row].Cells[1].Paragraphs.First().Append(Tabledata[row]).Color(System.Drawing.Color.FromArgb(52, 168, 83));
                            break;

                        case "fail":
                            table.Rows[row].Cells[0].Paragraphs.First().Append(Tableheading[row]).Bold().Color(System.Drawing.Color.FromArgb(234, 67, 53));
                            table.Rows[row].Cells[1].Paragraphs.First().Append(Tabledata[row]).Color(System.Drawing.Color.FromArgb(234, 67, 53));
                            break;

                        case "skip":
                            table.Rows[row].Cells[0].Paragraphs.First().Append(Tableheading[row]).Bold().Color(System.Drawing.Color.FromArgb(234, 67, 53));
                            table.Rows[row].Cells[1].Paragraphs.First().Append(Tabledata[row]).Color(System.Drawing.Color.FromArgb(234, 67, 53));
                            break;
                        }
                    }
                    else
                    {
                        table.Rows[row].Cells[0].Paragraphs.First().Append(Tableheading[row]).Bold();
                        table.Rows[row].Cells[1].Paragraphs.First().Append(Tabledata[row]);
                    }
                }

                resultdocument.InsertTable(table);
                Paragraph p1 = resultdocument.InsertParagraph();
                p1.AppendLine();
                p1.AppendLine();
                resultdocument.AddFooters();
                Footer    footer_default = resultdocument.Footers.Odd;
                Paragraph footer         = footer_default.InsertParagraph();
                footer.Append(Reports.reportfooterName);

                Paragraph last = resultdocument.InsertParagraph();

                for (int newline = 0; newline <= 36; newline++)
                {
                    last.AppendLine();
                }
                resultdocument.Save();
            }
            catch (Exception e)
            {
                Reports.SetupErrorLog(e);
            }
        }
        public static void GenerateRaport(Dictionary <string, string> tags, string originalImagePath, List <Marker> markerList, string analysisResult)
        {
            //try
            //{
            System.IO.Directory.CreateDirectory("Raporty");
            string path = @"Raporty/" + tags["(0010,0010)"] + "_" + String.Format("{0:MM/dd/yyyy/HH/mm/ss}", DateTime.Now) + ".docx";

            using (DocX document = DocX.Create(path))
            {
                Paragraph title = document.InsertParagraph();

                Table tTitle = document.AddTable(1, 4);

                tTitle.SetColumnWidth(0, 2000);
                string logoPath            = System.IO.Directory.GetCurrentDirectory().Substring(0, System.IO.Directory.GetCurrentDirectory().Length - 10);
                Xceed.Words.NET.Image logo = document.AddImage(logoPath + "\\Images\\icon.png");
                Picture logoImage          = logo.CreatePicture();
                logoImage.Height = 60;
                logoImage.Width  = 100;
                tTitle.Rows[0].Cells[0].Paragraphs[0].AppendPicture(logoImage);

                tTitle.SetColumnWidth(1, 5000);
                tTitle.Rows[0].Cells[1].Paragraphs[0].Alignment = Alignment.center;
                tTitle.Rows[0].Cells[1].Paragraphs[0].Append("Stacja komputerowego wspomagania diagnostyki medycznej na podstawie obrazów siatkówki oka")
                .Font("Times New Roman")
                .FontSize(14)
                .Color(Color.Black)
                .Bold();

                tTitle.SetColumnWidth(3, 2000);
                tTitle.Rows[0].Cells[3].Paragraphs[0].Append("\r\n" + String.Format("{0:MM.dd.yyyy r.}", DateTime.Now))
                .Font("Times New Roman")
                .FontSize(10)
                .Color(Color.Black);

                title.InsertTableAfterSelf(tTitle);

                Paragraph patientData = document.InsertParagraph();
                patientData.Alignment = Alignment.center;
                patientData.Append("\r\n\r\nDane pacjenta").Font("Times New Roman")
                .FontSize(12)
                .Color(Color.Black).Bold();

                Paragraph patient = document.InsertParagraph();

                Table tPatient = document.AddTable(4, 2);

                tPatient.SetColumnWidth(0, 2000);
                tPatient.SetColumnWidth(1, 5000);

                tPatient.Rows[0].Cells[0].Paragraphs[0].Append("Imię i nazwisko:")
                .Font("Times New Roman")
                .FontSize(10)
                .Color(Color.Black)
                .Bold();

                tPatient.Rows[1].Cells[0].Paragraphs[0].Append("Identyfikator:")
                .Font("Times New Roman")
                .FontSize(10)
                .Color(Color.Black).Bold();

                tPatient.Rows[2].Cells[0].Paragraphs[0].Append("Data urodzenia:")
                .Font("Times New Roman")
                .FontSize(10)
                .Color(Color.Black).Bold();

                tPatient.Rows[3].Cells[0].Paragraphs[0].Append("Płeć:")
                .Font("Times New Roman")
                .FontSize(10)
                .Color(Color.Black).Bold();

                tPatient.Rows[1].Cells[1].Paragraphs[0].Append(tags["(0010,0020)"])
                .Font("Times New Roman")
                .FontSize(10)
                .Color(Color.Black);

                tPatient.Rows[0].Cells[1].Paragraphs[0].Append(tags["(0010,0010)"])
                .Font("Times New Roman")
                .FontSize(10)
                .Color(Color.Black);

                patient.InsertTableAfterSelf(tPatient);

                Paragraph studyData = document.InsertParagraph();
                studyData.Alignment = Alignment.center;
                studyData.Append("Opis badania\r\n").Font("Times New Roman")
                .FontSize(12)
                .Color(Color.Black).Bold();

                Paragraph description = document.InsertParagraph();
                description.Alignment = Alignment.left;
                string desc = tags["(0008,1080)"];
                if (desc == "0")
                {
                    desc = "-";
                }
                description.Append(desc).Font("Times New Roman")
                .FontSize(10)
                .Color(Color.Black);

                Paragraph analysisData = document.InsertParagraph();
                analysisData.Alignment = Alignment.center;
                analysisData.Append("Wynik analizy\r\n").Font("Times New Roman")
                .FontSize(12)
                .Color(Color.Black).Bold();

                Paragraph anlysisResult = document.InsertParagraph();
                anlysisResult.Alignment = Alignment.left;
                anlysisResult.Append(analysisResult).Font("Times New Roman")
                .FontSize(10)
                .Color(Color.Black);

                Paragraph images = document.InsertParagraph();

                Table tImages = document.AddTable(4, 2);
                tImages.SetColumnWidth(0, 5000);
                tImages.SetColumnWidth(1, 5000);

                tImages.Rows[0].Cells[0].Paragraphs[0].Alignment = Alignment.center;
                tImages.Rows[0].Cells[1].Paragraphs[0].Alignment = Alignment.center;
                tImages.Rows[1].Cells[0].Paragraphs[0].Alignment = Alignment.center;
                tImages.Rows[1].Cells[1].Paragraphs[0].Alignment = Alignment.center;
                tImages.Rows[2].Cells[0].Paragraphs[0].Alignment = Alignment.center;
                tImages.Rows[2].Cells[1].Paragraphs[0].Alignment = Alignment.center;
                tImages.Rows[3].Cells[0].Paragraphs[0].Alignment = Alignment.center;
                tImages.Rows[3].Cells[1].Paragraphs[0].Alignment = Alignment.center;

                tImages.Rows[0].Cells[0].Paragraphs[0].Append("\r\nObraz oryginalny")
                .Font("Times New Roman")
                .FontSize(10)
                .Color(Color.Black);
                tImages.Rows[0].Cells[1].Paragraphs[0].Append("\r\nKanał zielony obrazu oryginalnego")
                .Font("Times New Roman")
                .FontSize(10)
                .Color(Color.Black);
                tImages.Rows[2].Cells[0].Paragraphs[0].Append("\r\nWysegmentowane naczynia krwionośne\r\n")
                .Font("Times New Roman")
                .FontSize(10)
                .Color(Color.Black);
                tImages.Rows[2].Cells[1].Paragraphs[0].Append("\r\nSzkielet naczyń krwionośnych\r\n")
                .Font("Times New Roman")
                .FontSize(10)
                .Color(Color.Black);

                Xceed.Words.NET.Image image = document.AddImage(originalImagePath + ".jpg");
                Picture originalImage       = image.CreatePicture();
                originalImage.Height = 250;
                originalImage.Width  = 300;
                tImages.Rows[1].Cells[0].Paragraphs[0].AppendPicture(originalImage);

                Xceed.Words.NET.Image image4 = document.AddImage(originalImagePath + "-1.png");
                Picture greenInameg          = image4.CreatePicture();
                greenInameg.Height = 250;
                greenInameg.Width  = 300;
                tImages.Rows[1].Cells[1].Paragraphs[0].AppendPicture(greenInameg);

                Xceed.Words.NET.Image image2 = document.AddImage(originalImagePath + "-2.png");
                Picture segmentationImage    = image2.CreatePicture();
                segmentationImage.Height = 250;
                segmentationImage.Width  = 300;
                tImages.Rows[3].Cells[0].Paragraphs[0].AppendPicture(segmentationImage);

                Xceed.Words.NET.Image image3 = document.AddImage(originalImagePath + "-3.png");
                Picture skelImage            = image3.CreatePicture();
                skelImage.Height = 250;
                skelImage.Width  = 300;
                tImages.Rows[3].Cells[1].Paragraphs[0].AppendPicture(skelImage);

                images.InsertTableAfterSelf(tImages);

                Paragraph measurments = document.InsertParagraph();

                measurments.Alignment = Alignment.center;
                measurments.Append("Pomiary na obrazie\r\n\r\n").Font("Times New Roman")
                .FontSize(12)
                .Color(Color.Black).Bold();

                Xceed.Words.NET.Image image5 = document.AddImage(originalImagePath + "-0.png");
                Picture measurmentsImage     = image5.CreatePicture();
                measurmentsImage.Height = 450;
                measurmentsImage.Width  = 500;
                measurments.AppendPicture(measurmentsImage);

                int   rows = markerList.Count + 1;
                Table t    = document.AddTable(rows, 2);
                t.SetBorder(TableBorderType.Bottom, new Border(Xceed.Words.NET.BorderStyle.Tcbs_single, BorderSize.one, 1, Color.Black));
                t.SetBorder(TableBorderType.InsideH, new Border(Xceed.Words.NET.BorderStyle.Tcbs_single, BorderSize.one, 1, Color.Black));
                t.SetBorder(TableBorderType.InsideV, new Border(Xceed.Words.NET.BorderStyle.Tcbs_single, BorderSize.one, 1, Color.Black));
                t.SetBorder(TableBorderType.Left, new Border(Xceed.Words.NET.BorderStyle.Tcbs_single, BorderSize.one, 1, Color.Black));
                t.SetBorder(TableBorderType.Right, new Border(Xceed.Words.NET.BorderStyle.Tcbs_single, BorderSize.one, 1, Color.Black));
                t.SetBorder(TableBorderType.Top, new Border(Xceed.Words.NET.BorderStyle.Tcbs_single, BorderSize.one, 1, Color.Black));
                t.Alignment = Alignment.center;

                measurments.Append("\r\n").Font("Times New Roman")
                .FontSize(12)
                .Color(Color.Black).Bold();

                t.Rows[0].Cells[0].Paragraphs[0].Append("L.p.")
                .Font("Times New Roman")
                .FontSize(10)
                .Color(Color.Black);
                t.Rows[0].Cells[1].Paragraphs[0].Append("Opis")
                .Font("Times New Roman")
                .FontSize(10)
                .Color(Color.Black);

                for (int r = 1; r < rows; r++)
                {
                    t.Rows[r].Cells[0].Paragraphs[0].Append(markerList[r - 1].Id.ToString())
                    .Font("Times New Roman")
                    .FontSize(10)
                    .Color(Color.Black);
                    t.Rows[r].Cells[1].Paragraphs[0].Append(markerList[r - 1].Description.ToString())
                    .Font("Times New Roman")
                    .FontSize(10)
                    .Color(Color.Black);
                }

                measurments.InsertTableAfterSelf(t);

                document.Save();
            }
            //}
            //catch
            //{
            //    MessageBox.Show("Nie można wydrukować dokumentu", "Błąd");
            //}
        }
Example #27
0
        /// <summary>
        /// Initialize Word Report --> Support Method
        /// </summary>
        public static void InitWordSummarySetup()
        {
            try
            {
                string directory = BaseUtilities.GetFolderPath();

                resultSummarydocument = DocX.Create(Reports.testRunResultWordFolder + "\\" + "Summary Report.docx");
                //Resultdocument = DocX.Create(directory + @"Results\WordResults\Testrr.docx");

                resultSummarydocument.AddHeaders();
                Header ResultHeader = resultSummarydocument.Headers.Odd;

                Image   Headerimage = resultSummarydocument.AddImage(Reports.reportheaderimage);
                Picture picture     = Headerimage.CreatePicture();
                picture.Width  = 150;
                picture.Height = 28;
                Paragraph Header = ResultHeader.InsertParagraph();
                Header.Alignment = Alignment.right;
                Header.AppendPicture(picture);

                Paragraph Date    = resultSummarydocument.InsertParagraph();
                String    StrDate = System.DateTime.Today.ToString("dd-MM-yyyy");
                Paragraph date    = Date.Append("Date: " + StrDate).FontSize(8).Font("Calibri").Color(System.Drawing.Color.FromArgb(1, 74, 73, 71));
                date.Alignment = Alignment.left;

                Paragraph title = resultSummarydocument.InsertParagraph().Append(Reports.reportname).FontSize(12).Font("Century Gothic").Color(System.Drawing.Color.FromArgb(1, 91, 168));
                title.Alignment = Alignment.center;
                title.AppendLine();
                Paragraph tcscountpass = resultSummarydocument.InsertParagraph().Append("Total Test(s) Passed: " + Reports.ttltcspass).Color(System.Drawing.Color.FromArgb(52, 168, 83));
                tcscountpass.Alignment = Alignment.left;
                Paragraph tcscountfail = resultSummarydocument.InsertParagraph().Append("Total Test(s) Failed: " + Reports.ttltcsfail).Color(System.Drawing.Color.FromArgb(234, 67, 53));
                tcscountfail.Alignment = Alignment.left;
                tcscountfail.AppendLine();

                String[] Tableheading = { "S.No", "Scenario Name", "Test Status", "For More Details" };
                String[] Tabledata    = { BaseUtilities.scenarioName, BaseUtilities.scenarioStatus };

                Table table = resultSummarydocument.AddTable(1, 4);
                // Specify some properties for this Table.
                table.Alignment = Alignment.left;
                table.AutoFit   = AutoFit.Contents;
                table.Design    = TableDesign.TableGrid;
                table.SetColumnWidth(0, 667.87);
                table.SetColumnWidth(1, 5347.87);
                table.SetColumnWidth(2, 1255.87);
                table.SetColumnWidth(3, 1825.82);

                table.Rows[0].Cells[0].Paragraphs.First().Append(Tableheading[0]).Bold();
                table.Rows[0].Cells[1].Paragraphs.First().Append(Tableheading[1]).Bold();
                table.Rows[0].Cells[2].Paragraphs.First().Append(Tableheading[2]).Bold();
                table.Rows[0].Cells[3].Paragraphs.First().Append(Tableheading[3]).Bold();


                resultSummarydocument.InsertTable(table);

                resultSummarydocument.AddFooters();
                Footer    footer_default = resultSummarydocument.Footers.Odd;
                Paragraph footer         = footer_default.InsertParagraph();
                footer.Append(Reports.reportfooterName);

                resultSummarydocument.Save();
            }
            catch (Exception e)
            {
                Reports.SetupErrorLog(e);
            }
        }
Example #28
0
        public void fromvariableCreateDocument(GenericDocumentParameters in_documentArgs, String obtainedPath)
        {
            //prepare important days list
            MainXMLprocessor importantDaysProcessor = new MainXMLprocessor();
            importantdays    alldaysListRaw         = importantDaysProcessor.loadImportantDaysListFromFile(obtainedPath);
            Dictionary <System.DateTime, List <importantday> > importantDaysProcessed = importantDaysProcessor.getDictionaryForProcessing(alldaysListRaw);
            //=========
            DocX document = DocX.Create(in_documentArgs.documentName);

            // https://stackoverflow.com/a/90699/
            ConsoleAppCalendar.Properties.Resources.sunrise1f305.Save("sunrisetmp.png");
            ConsoleAppCalendar.Properties.Resources.sunset1f307.Save("sunsettmp.png");
            // https://xceed.com/wp-content/documentation/xceed-words-for-net/Xceed.Words.NET~Xceed.Words.NET.DocX~AddImage(Stream,String).html
            Xceed.Words.NET.Image imgSunrise = document.AddImage("sunrisetmp.png"); Xceed.Words.NET.Picture picSunrise = imgSunrise.CreatePicture();
            picSunrise.Height = (int)Math.Round(picSunrise.Height * 0.32);
            picSunrise.Width  = (int)Math.Round(picSunrise.Width * 0.32);
            Xceed.Words.NET.Image imgSunset = document.AddImage("sunsettmp.png"); Xceed.Words.NET.Picture picSunset = imgSunset.CreatePicture();
            picSunset.Height = (int)Math.Round(picSunset.Height * 0.38);
            picSunset.Width  = (int)Math.Round(picSunset.Width * 0.38);
            System.DateTime theCurrentDate = date1;
            do
            {
                document.PageHeight = in_documentArgs.pageHeight;
                document.PageWidth  = in_documentArgs.pageWidth;
                float btmMargin = 1.0f; float topMargin = 1.0f; float leftMargin = 1.0f; float rightMargin = 1.0f;
                document.MarginBottom = cmToPoints(btmMargin); document.MarginTop = cmToPoints(topMargin); document.MarginLeft = cmToPoints(leftMargin); document.MarginRight = cmToPoints(rightMargin);
                Table  insertedTable = document.InsertTable(in_documentArgs.numrowsTable, in_documentArgs.numcolsTable);
                Border b             = new Border(BorderStyle.Tcbs_single, BorderSize.one, 0, Color.Blue);
                //calculate each column width
                float bestColumnWidth = cmToPixels(((float)in_documentArgs.pageWidth - (float)(leftMargin + rightMargin)) / (float)(in_documentArgs.numcolsTable));
                float bestRowHeightPt = (((float)in_documentArgs.pageHeight - (float)(topMargin + btmMargin)) / (float)(in_documentArgs.numrowsTable));
                // Set the tables Top, Bottom, Left and Right Borders to b.
                insertedTable.SetBorder(TableBorderType.Top, b);
                insertedTable.SetBorder(TableBorderType.Bottom, b);
                insertedTable.SetBorder(TableBorderType.Left, b);
                insertedTable.SetBorder(TableBorderType.Right, b);
                insertedTable.SetBorder(TableBorderType.InsideH, b);
                insertedTable.SetBorder(TableBorderType.InsideV, b);
                byte currentRow = 0; byte currentCol = 0;
                while ((currentRow < in_documentArgs.numrowsTable) && (currentCol < in_documentArgs.numcolsTable) && (theCurrentDate <= date2))
                {
                    Table internalTable1 = insertedTable.Rows[currentRow].Cells[currentCol].InsertTable(1, 2);
                    internalTable1.SetWidthsPercentage(new float[] { 30.0f, 70.0f }, 100.0f);

                    /*
                     *  Paragraph yearMonthP = insertedTable.Rows[currentRow].Cells[currentCol].InsertParagraph(String.Format("{0:yyyy, MMMM}", theCurrentDate));
                     *  Paragraph dayNumberP = insertedTable.Rows[currentRow].Cells[currentCol].InsertParagraph(String.Format("{0:dd}", theCurrentDate));
                     *  Paragraph weekdayP = insertedTable.Rows[currentRow].Cells[currentCol].InsertParagraph(String.Format("{0:dddd}", theCurrentDate));
                     */
                    Paragraph yearMonthP = internalTable1.Rows[0].Cells[1].InsertParagraph(String.Format("{0:yyyy, MMMM}", theCurrentDate));
                    Paragraph dayNumberP = internalTable1.Rows[0].Cells[1].InsertParagraph(String.Format("{0:dd}", theCurrentDate));
                    Paragraph weekdayP   = internalTable1.Rows[0].Cells[1].InsertParagraph(String.Format("{0:dddd}", theCurrentDate));
                    yearMonthP.Alignment = Alignment.center; yearMonthP.Font("Courier New");
                    dayNumberP.Alignment = Alignment.center; dayNumberP.Font("Courier New"); dayNumberP.FontSize(15); dayNumberP.Bold();
                    weekdayP.Alignment   = Alignment.center; weekdayP.Font("Courier New");

                    Tuple <string, string> sunTimes = getSunsetAndSunRise(true, 2, theCurrentDate, 49.4444, 32.0597);
                    Paragraph sunriseParagraph      = internalTable1.Rows[0].Cells[0].InsertParagraph(String.Format("{0}", sunTimes.Item1));
                    // https://xceed.com/wp-content/documentation/xceed-words-for-net/webframe.html#Xceed.Words.NET~Xceed.Words.NET.Paragraph~InsertPicture.html
                    sunriseParagraph.InsertPicture(picSunrise);
                    Paragraph sunsetParagraph = internalTable1.Rows[0].Cells[0].InsertParagraph(String.Format("{0}", sunTimes.Item2));
                    sunsetParagraph.InsertPicture(picSunset);
                    internalTable1.Rows[0].Cells[1].Paragraphs[0].Remove(false);
                    internalTable1.Rows[0].Cells[0].Paragraphs[0].Remove(false);
                    insertedTable.Rows[currentRow].Cells[currentCol].Paragraphs[0].Remove(false);
                    insertedTable.SetColumnWidth(currentCol, bestColumnWidth);
                    // 100*2/3pt -> 3.53 cm
                    // x  px -> bestRowHeightCm
                    if (importantDaysProcessed.ContainsKey(theCurrentDate))
                    {
                        List <importantday> eventsForCurrentDate = importantDaysProcessed[theCurrentDate];
                        bool holidayDisplayed = false;
                        foreach (importantday specialevent in eventsForCurrentDate)
                        {
                            Paragraph eventParagraph = insertedTable.Rows[currentRow].Cells[currentCol].InsertParagraph("\u25EF " + specialevent.description);
                            eventParagraph.Font("Courier New");
                            if ((specialevent.typeOfDay == "holiday") && (holidayDisplayed == false))
                            {
                                holidayDisplayed = true;
                                Paragraph officialWeekendParagraph = internalTable1.Rows[0].Cells[1].InsertParagraph("/вихідний/");
                                officialWeekendParagraph.Alignment = Alignment.center; officialWeekendParagraph.Font("Courier New"); officialWeekendParagraph.FontSize(7.0); officialWeekendParagraph.Bold();
                            }
                        }
                    }

                    insertedTable.Rows[currentRow].Height = Math.Round(bestRowHeightPt * 0.88);

                    theCurrentDate = theCurrentDate.AddDays(1.0);
                    currentCol++;
                    if ((currentCol >= in_documentArgs.numcolsTable) && (currentRow < in_documentArgs.numrowsTable - 1))
                    {
                        currentCol = 0; currentRow++;
                    }
                }

                if (theCurrentDate <= date2)
                {
                    //document.InsertSectionPageBreak();
                    insertedTable.InsertPageBreakAfterSelf();
                }
            } while (theCurrentDate <= date2);


            //document.InsertTable(in_documentArgs.numrowsTable, in_documentArgs.numcolsTable);
            document.Save();
            System.IO.File.Delete("sunsettmp.png");
            System.IO.File.Delete("sunrise.png");
        }
        /// <summary>
        /// Writes given inputs into a document.
        /// </summary>
        /// <param name="input">Inputs.</param>
        /// <param name="document">Word document.</param>
        /// <param name="tractID">Selected tractID.</param>
        private void WriteUndiscoveredDeposits(ReportingAssesmentInputParams input, DocX document)
        {
            string    paragraph         = "";
            Paragraph severalParagraphs = null;
            string    depEst            = "";

            if ((input.IsUndiscDepDone == "Yes (NegativeBinomial)" && File.Exists(depEst = Path.Combine(input.Env.RootPath, "UndiscDep", input.SelectedTractCombination, "SelectedResult", "nDepEst.csv"))) || //käydään läpi että onko depEst tiedostoa olemassa missään muodossa
                (input.IsUndiscDepDone == "Yes (MARK3)" && File.Exists(depEst = Path.Combine(input.Env.RootPath, "UndiscDep", input.SelectedTractCombination, "SelectedResult", "nDepEstMiddle.csv"))) ||
                (input.IsUndiscDepDone == "Yes (Custom)" && File.Exists(depEst = Path.Combine(input.Env.RootPath, "UndiscDep", input.SelectedTractCombination, "SelectedResult", "nDepEstCustom.csv"))))
            {
                severalParagraphs = document.InsertParagraph("Table 1. ").Bold();
                severalParagraphs.Append("Estimated numbers of deposits at 90, 50 and 10 percentile levels of confidence" + "\r\n");
                string value;
                using (TextReader fileReader = File.OpenText(depEst))
                {
                    using (var csv = new CsvReader(fileReader))
                    {
                        csv.Configuration.HasHeaderRecord = false;
                        csv.Configuration.Delimiter       = ";";
                        Table t = null;
                        if (depEst == Path.Combine(input.Env.RootPath, "UndiscDep", input.SelectedTractCombination, "SelectedResult", "nDepEst.csv"))
                        {
                            t = document.AddTable(1, 5);
                        }
                        else if (depEst == Path.Combine(input.Env.RootPath, "UndiscDep", input.SelectedTractCombination, "SelectedResult", "nDepEstMiddle.csv"))
                        {
                            t = document.AddTable(1, 6);
                        }
                        else //(depEst == Path.Combine(input.Env.RootPath, "UndiscDep", "SelectedResult", "nDepEstCustom.csv"))
                        {
                            t = document.AddTable(1, 2);
                        }
                        bool addToFirstRow = true;
                        var  r             = t.Rows[0];
                        int  cellNumber    = 1;
                        // Inserts the data from CSV file corrctly into a table.
                        while (csv.Read())
                        {
                            for (int i = 0; csv.TryGetField <string>(i, out value); i++)
                            {
                                if (depEst == Path.Combine(input.Env.RootPath, "UndiscDep", input.SelectedTractCombination, "SelectedResult", "nDepEstMiddle.csv"))
                                {
                                    if (addToFirstRow == true)
                                    {
                                        r = t.Rows[0];

                                        addToFirstRow = false;
                                        r.Cells[0].Paragraphs[0].Append("TractID");
                                        r.Cells[1].Paragraphs[0].Append("N90");
                                        r.Cells[2].Paragraphs[0].Append("N50");
                                        r.Cells[3].Paragraphs[0].Append("N10");
                                        r.Cells[4].Paragraphs[0].Append("N05");
                                        r.Cells[5].Paragraphs[0].Append("N01");
                                        r = t.InsertRow();
                                        r.Cells[cellNumber].Paragraphs[0].Append(value);
                                        cellNumber++;
                                    }
                                    else
                                    {
                                        r = t.Rows[1];
                                        r.Cells[cellNumber].Paragraphs[0].Append(value);
                                        cellNumber++;
                                    }
                                }
                                else
                                {
                                    r = t.Rows[0];
                                    if (addToFirstRow == true)
                                    {
                                        r             = t.Rows[0];
                                        addToFirstRow = false;
                                        value         = value.Replace("Name", "Estimator");
                                    }
                                    else
                                    {
                                        r = t.InsertRow();
                                    }
                                    string[] cellArray = value.Split(',');
                                    int      cellIndex = 0;
                                    for (int k = 0; k < cellArray.Length; k++)
                                    {
                                        r.Cells[cellIndex].Paragraphs[0].Append(cellArray[k]).ReplaceText("\"", "");
                                        cellIndex++;
                                    }
                                }
                            }
                        }
                        document.InsertTable(t);  // Insert table into the document.
                    }
                    document.InsertParagraph("\r\n");
                }
            }
            if (File.Exists(Path.Combine(input.Env.RootPath, "UndiscDep", input.SelectedTractCombination, "SelectedResult", "summary.txt")) && input.IsUndiscDepDone != "No")
            {
                severalParagraphs = document.InsertParagraph("Table 2. ").Bold();
                severalParagraphs.Append(File.ReadAllText(Path.Combine(input.Env.RootPath, "UndiscDep", input.SelectedTractCombination, "SelectedResult", "summary.txt")) + "\r\n");
            }
            string file = Path.Combine(input.Env.RootPath, "UndiscDep", input.SelectedTractCombination, "SelectedResult", "TractPmf.csv");

            if (File.Exists(file) && input.IsUndiscDepDone != "No")
            {
                severalParagraphs = document.InsertParagraph("Table 3. ").Bold();
                severalParagraphs.Append("Number of deposits and associated probability for the estimated pmf");
                using (TextReader fileReader = File.OpenText(file))
                {
                    using (var csv = new CsvReader(fileReader))
                    {
                        csv.Configuration.HasHeaderRecord = false;
                        csv.Configuration.Delimiter       = ";";
                        var  t             = document.AddTable(1, 3);
                        bool addToFirstRow = true;
                        paragraph = "";
                        // Inserts the data from CSV file correctly into a table.
                        while (csv.Read())
                        {
                            for (int i = 0; csv.TryGetField <string>(i, out paragraph); i++)
                            {
                                string[] cellArray = paragraph.Split(',');
                                var      r         = t.Rows[0];
                                if (addToFirstRow == true)
                                {
                                    r             = t.Rows[0];
                                    addToFirstRow = false;
                                }
                                else
                                {
                                    r = t.InsertRow();
                                }
                                int cellIndex = 0;
                                for (int k = 0; k < cellArray.Length; k++)
                                {
                                    r.Cells[cellIndex].Paragraphs[0].Append(cellArray[k]);
                                    cellIndex++;
                                }
                            }
                        }
                        document.InsertTable(t);  // Insert table into the document.
                    }
                    document.InsertParagraph("\r\n");
                }
            }
            if (File.Exists(Path.Combine(input.Env.RootPath, "UndiscDep", input.SelectedTractCombination, "SelectedResult", "plot.jpeg")) && input.IsUndiscDepDone != "No")
            {
                var     img = document.AddImage(Path.Combine(input.Env.RootPath, "UndiscDep", input.SelectedTractCombination, "SelectedResult", "plot.jpeg"));
                Picture p   = img.CreatePicture(600, 605);
                paragraph = "\r\n";
                Paragraph par = document.InsertParagraph(paragraph);
                par.AppendPicture(p);
                par.Append("\r\n");

                severalParagraphs = document.InsertParagraph("Figure 2. ").Bold();
                severalParagraphs.Append("A. Negative binomial probability mass function representing the number of undiscovered deposits" +
                                         " in the permissive tracts. B. Probability mass function recast as elicitation percentiles (black dots) and" +
                                         " compared to the estimated numbers of undiscovered deposits (red circles). The size of a red circle indicates how many" +
                                         " assessment team members picked the same number of undiscovered deposits." + "\r\n\r\n");
            }
        }
Example #30
0
        public string BuildTranscripts(IEnumerable <FieldInfo> fields, string ESig, string docName, string campus)
        {
            string fileName = @"C:\Websites\DropFolder\Sullivan_Admissions\" + docName + "_" + DateTime.Now.Millisecond + ".docx";

            var paraFormat = new Formatting();

            paraFormat.Size = 12D;

            var headerFormat = new Formatting();

            headerFormat.Size = 15D;
            headerFormat.Bold = true;

            string strSchoolLocation;
            string strAddress;
            string strCity;
            string strZip;

            if (campus == "Lexington")
            {
                strSchoolLocation = "Sullivan University Lexington";
                strAddress        = "2355 Harrodsburg Road";
                strCity           = "Lexington";
                strZip            = "40504";
            }
            else if (campus == "Online")
            {
                strSchoolLocation = "Sullivan University Online";
                strAddress        = "2100 Gardiner Lane Suite 301";
                strCity           = "Louisville";
                strZip            = "40205";
            }
            else if (campus == "Fort Knox")
            {
                strSchoolLocation = "Sullivan University Ft. Knox";
                strAddress        = "P.O. BOX 998";
                strCity           = "Ft. Knox";
                strZip            = "40121";
            }
            else if (campus == "Louisa")
            {
                strSchoolLocation = "Sullivan University Louisa, Center for Learning";
                strAddress        = "PO Box 1540";
                strCity           = "Louisa";
                strZip            = "41230";
            }
            else if (campus == "Northern Kentucky")
            {
                strSchoolLocation = "Sullivan University Center for Learning - Northern Kentucky";
                strAddress        = "207 Grandview Drive, Suite 300";
                strCity           = "Ft. Mitchell";
                strZip            = "40107";
            }
            else
            {
                strSchoolLocation = "Sullivan University Louisville";
                strAddress        = "3101 Bardstown Rd";
                strCity           = "Louisville";
                strZip            = "40232";
            }

            using (DocX doc = DocX.Create(fileName))
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    System.Drawing.Image myImg = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath("img/sus_logo.gif"));

                    myImg.Save(ms, myImg.RawFormat);  // Save your picture in a memory stream.
                    ms.Seek(0, SeekOrigin.Begin);

                    Novacode.Image img = doc.AddImage(ms); // Create image.

                    Paragraph p = doc.InsertParagraph("", false);

                    Picture pic1 = img.CreatePicture(); // Create picture.

                    p.InsertPicture(pic1, 0);           // Insert picture into paragraph.
                }

                doc.InsertParagraph("", false, paraFormat);

                if (docName == "HS-GED")
                {
                    doc.InsertParagraph(RemoveHTML("High School / GED Transcript Request"), false, headerFormat);
                }
                else if (docName == "ROI")
                {
                    doc.InsertParagraph(RemoveHTML("Release of Information"), false, headerFormat);
                }
                else
                {
                    doc.InsertParagraph(RemoveHTML("College Transcript Request"), false, headerFormat);
                }

                doc.InsertParagraph("", false, paraFormat);

                if (docName == "HS-GED" || docName.Contains("College"))
                {
                    doc.InsertParagraph(strSchoolLocation, false, paraFormat);
                    doc.InsertParagraph(strAddress, false, paraFormat);
                    doc.InsertParagraph(strCity + ", KY " + strZip, false, paraFormat);
                    doc.InsertParagraph("", false, paraFormat);

                    doc.InsertParagraph("The student listed below has applied to Sullivan University for admission. Prior to their acceptance by Sullivan University, we must have an up-to-date transcript of all previous work.", false, paraFormat);
                    doc.InsertParagraph("", false, paraFormat);
                    doc.InsertParagraph("We are requesting that a copy of the transcript and a copy of the attached sheet be returned to Sullivan University as soon as possible. " +
                                        "Your institution may retain a photocopy. One copy must be returned in case of name changes. Please mail to " + campus + " " + strAddress + " " + strCity + " KY " + strZip, false, paraFormat);
                    doc.InsertParagraph("", false, paraFormat);
                    doc.InsertParagraph("This release form has been signed electronically by the student to meet the requirements of the Family Education Rights and Privacy Act of 1974(Buckley Amendment).", false, paraFormat);
                    doc.InsertParagraph("", false, paraFormat);
                }

                foreach (var field in fields)
                {
                    //If the label does not have an associated control then it is a stand alone label
                    if ((field.controlType == "Label" || field.controlType == "Panel") && field.controlText == null)
                    {
                        if (field.CssClass.Contains("header") || field.CssClass.Contains("collegeHeader"))
                        {
                            doc.InsertParagraph(RemoveHTML(field.labelText), false, headerFormat);
                        }
                        else
                        {
                            doc.InsertParagraph(RemoveHTML(field.labelText), false, paraFormat);
                        }
                    }
                    //Used to draw labels and their associated controls
                    else
                    {
                        if (field.controlID.Contains("output"))
                        {
                            using (MemoryStream ms = new MemoryStream())
                            {
                                System.Drawing.Image myImg = System.Drawing.Image.FromFile(ESig);

                                myImg.Save(ms, myImg.RawFormat);  // Save your picture in a memory stream.
                                ms.Seek(0, SeekOrigin.Begin);

                                Novacode.Image img = doc.AddImage(ms); // Create image.

                                Paragraph p = doc.InsertParagraph("", false);

                                Picture pic1 = img.CreatePicture(); // Create picture.

                                p.InsertPicture(pic1, 0);           // Insert picture into paragraph.
                            }
                        }
                        else
                        {
                            doc.InsertParagraph(RemoveHTML(field.labelText) + ": " + RemoveHTML(field.controlText), false, paraFormat);
                        }
                    }

                    doc.InsertParagraph("");
                }

                // Save to the output directory:
                doc.Save();
            }

            return(fileName);
        }