Exemplo n.º 1
0
            private static void printSpec(DocX document, SpecInfo spec)
            {
                printName(document, spec);
                printSkipped(document, spec);
                printGiven(document, spec);
                printWhen(document, spec);
                printThen(document, spec);

                document.InsertParagraph();
            }
Exemplo n.º 2
0
 private static void printSkipped(DocX document, SpecInfo spec)
 {
     if (spec.Skipped.IsSkipped)
     {
         document.InsertParagraph()
             .Append(spec.Skipped.ToString())
             .Font(new FontFamily("Cambria"))
                 .FontSize(13)
                 .Bold()
                 .Color(Color.FromArgb(255, 255, 124, 0))
                 ;
     }
 }
Exemplo n.º 3
0
            private void printCategory(SpecCategory category, DocX document)
            {
                document.InsertParagraph()
                        .Append(category.ToString())
                        .Font(new FontFamily("Cambria"))
                        .FontSize(26)
                        .Color(Color.FromArgb(255, 23, 54, 93))
                        .Spacing(2.0f)
                        .AppendLine();

                foreach (var spec in category.Specs)
                    printSpec(document, spec);
            }
Exemplo n.º 4
0
            private static void printGiven(DocX document, SpecInfo spec)
            {
                if (spec.Givens.Length == 0)
                    return;

                document.InsertParagraph()
                    .Append("Given")
                    .Font(new FontFamily("Cambria"))
                        .FontSize(13)
                        .Bold()
                        .Color(Color.FromArgb(255, 79, 129, 189))
                        ;

                foreach (var given in spec.Givens)
                {
                    var description = spec.HasExecutionBeenTriggered
                                          ? string.Format("{0} [{1}]", given.Description,
                                                          given.Passed ? "Passed" : "Failed")
                                          : given.Description;

                    var p = document.InsertParagraph()
                                    .Append(description)
                                    .Color(spec.HasExecutionBeenTriggered ? (given.Passed ? Color.Green : Color.Red) : Color.Black)
                                    .FontSize(12);

                    p.IndentationBefore = 0.5f;
                }

                if (!spec.Givens.All(x => x.Passed) && spec.Exception != null)
                {
                    document.InsertParagraph()
                            .Append(spec.Exception.ToString())
                            .Color(Color.Black)
                            .FontSize(12)
                            .IndentationBefore = 0.5f;
                }
            }
Exemplo n.º 5
0
        public string GenerateBidEvalClauseDocument(gpTenderProjectWebDO gptp)
        {
            string path = Path.Combine(AppDirectory.Temp_Dir(gptp.gpId), "评标条款.docx");

            IGpEvalwayItemGtfService gpEvalwayItemGtfService = new GpEvalwayItemGtfService();

            var result = gpEvalwayItemGtfService.FindListByGsIdAndGewigName(gptp.gpId, string.Empty);

            using (DocX document = DocX.Create(path))
            {
                //标题
                document.InsertParagraph("《评分条款》").FontSize(18d).Bold().SpacingAfter(50d).Alignment = Alignment.center;

                var t = document.AddTable(result.Count() + 1, 11);
                t.Design    = TableDesign.ColorfulList;
                t.Alignment = Alignment.center;

                //标题
                t.Rows[0].Cells[0].Paragraphs[0].Append("编码");
                t.Rows[0].Cells[1].Paragraphs[0].Append("名称");
                t.Rows[0].Cells[2].Paragraphs[0].Append("类型");
                t.Rows[0].Cells[3].Paragraphs[0].Append("最高分");
                t.Rows[0].Cells[4].Paragraphs[0].Append("最低分");
                t.Rows[0].Cells[5].Paragraphs[0].Append("是否需要设置值1");
                t.Rows[0].Cells[6].Paragraphs[0].Append("设置值1的说明");
                t.Rows[0].Cells[7].Paragraphs[0].Append("是否需要设置值2");
                t.Rows[0].Cells[8].Paragraphs[0].Append("设置值2的说明");
                t.Rows[0].Cells[9].Paragraphs[0].Append("算法名称");
                t.Rows[0].Cells[10].Paragraphs[0].Append("备注");

                int indexer = 1;

                foreach (var item in result.OrderBy(x => x.sort))
                {
                    t.Rows[indexer].Cells[0].Paragraphs[0].Append(item.gewigCode);
                    t.Rows[indexer].Cells[1].Paragraphs[0].Append(item.gewigName);
                    t.Rows[indexer].Cells[2].Paragraphs[0].Append(item.gewigType.ToString());
                    t.Rows[indexer].Cells[3].Paragraphs[0].Append(item.maxScore.ToString());
                    t.Rows[indexer].Cells[4].Paragraphs[0].Append(item.minScore.ToString());
                    t.Rows[indexer].Cells[5].Paragraphs[0].Append(item.isNeedFirstPara == 0 ? "不需要" : "需要");
                    t.Rows[indexer].Cells[6].Paragraphs[0].Append(item.firstParaDesc);
                    t.Rows[indexer].Cells[7].Paragraphs[0].Append(item.isNeedSecondPara == 0 ? "不需要" : "需要");
                    t.Rows[indexer].Cells[8].Paragraphs[0].Append(item.secondParaDesc);
                    t.Rows[indexer].Cells[9].Paragraphs[0].Append(item.algoName);
                    t.Rows[indexer].Cells[10].Paragraphs[0].Append(item.remark);

                    indexer++;
                }

                // Insert a new Paragraph into the document.
                var p = document.InsertParagraph("评分条款:");
                p.SpacingAfter(10d);

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

                document.Save();
            }

            return(path);
        }
Exemplo n.º 6
0
        public string GenerateBidEvalScoringPointDocument(gpTenderProjectWebDO gptp)
        {
            string path = Path.Combine(AppDirectory.Temp_Dir(gptp.gpId), "评分点.docx");

            IGpTenderEvalEleService gpTenderEvalEleService = new GpTenderEvalEleService();

            var result = gpTenderEvalEleService.FindListByGsIdAndGteeName(gptp.gpId, string.Empty);

            using (DocX document = DocX.Create(path))
            {
                //标题
                document.InsertParagraph("《评分点》").FontSize(18d).Bold().SpacingAfter(50d).Alignment = Alignment.center;

                var t = document.AddTable(result.Count() + 1, 11);
                t.Design    = TableDesign.ColorfulList;
                t.Alignment = Alignment.center;

                //标题
                t.Rows[0].Cells[0].Paragraphs[0].Append("评标因素名称");
                t.Rows[0].Cells[1].Paragraphs[0].Append("评标因素单位");
                t.Rows[0].Cells[2].Paragraphs[0].Append("评标因素数值");
                t.Rows[0].Cells[3].Paragraphs[0].Append("评标因素数值梯度");
                t.Rows[0].Cells[4].Paragraphs[0].Append("基准分数最大值");
                t.Rows[0].Cells[5].Paragraphs[0].Append("基准分数最小值");
                t.Rows[0].Cells[6].Paragraphs[0].Append("基准");
                t.Rows[0].Cells[7].Paragraphs[0].Append("大于基准算法");
                t.Rows[0].Cells[8].Paragraphs[0].Append("大于基准梯度值");
                t.Rows[0].Cells[9].Paragraphs[0].Append("小于基准算法");
                t.Rows[0].Cells[10].Paragraphs[0].Append("小于基准梯度值");

                int indexer = 1;

                foreach (var item in result)
                {
                    t.Rows[indexer].Cells[0].Paragraphs[0].Append(item.gteeName);
                    t.Rows[indexer].Cells[1].Paragraphs[0].Append(item.evalUnit);
                    t.Rows[indexer].Cells[2].Paragraphs[0].Append(item.evalNum.ToString());
                    t.Rows[indexer].Cells[3].Paragraphs[0].Append(item.evalGrads.ToString());
                    t.Rows[indexer].Cells[4].Paragraphs[0].Append(item.maxScore.ToString());
                    t.Rows[indexer].Cells[5].Paragraphs[0].Append(item.minScore.ToString());
                    t.Rows[indexer].Cells[6].Paragraphs[0].Append(item.standard.ToString());
                    t.Rows[indexer].Cells[7].Paragraphs[0].Append(item.greatWay.ToString());
                    t.Rows[indexer].Cells[8].Paragraphs[0].Append(item.greatNum.ToString());
                    t.Rows[indexer].Cells[9].Paragraphs[0].Append(item.littleWay.ToString());
                    t.Rows[indexer].Cells[10].Paragraphs[0].Append(item.littleNum.ToString());

                    indexer++;
                }

                // Insert a new Paragraph into the document.
                var p = document.InsertParagraph("评分点:");
                p.SpacingAfter(10d);

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

                document.Save();
            }

            return(path);
        }
Exemplo n.º 7
0
        /// <summary>
        /// 插入分层分户平面图
        /// </summary>
        /// <param name="document"></param>
        /// <param name="lstFM"></param>
        /// <param name="p"></param>
        /// <param name="ischild">判断是否作为市级公司的下级</param>
        public void insertFCFH(DocX document, List <FDXXtbl_country> lstFM, List <Parcelmodel> p, bool ischild, bool istrainings, NumoftitleHelper title)
        {
            Paragraph h1_4_1;

            try
            {
                Paragraph h1_4 = document.InsertParagraph("");

                FDXXtbl_country temp = new FDXXtbl_country();
                foreach (FDXXtbl_country fm in lstFM)
                {
                    if (temp != null && temp.ZDXX_MC == fm.ZDXX_MC && temp.FCXX_JZMC == fm.FCXX_JZMC)
                    {
                        continue;
                    }
                    temp = fm;

                    //if(fm.ZDXX_MC == Parcelname)
                    if (fm.ZDXX_ID == parcelID)
                    {
                        Picture       p_deed    = picHelper.getPic(document, PathManager.getSingleton().GetDeedPath(fm.FCXX_ID, false), 450, 886);
                        Picture       p_virtual = picHelper.getPic(document, PathManager.getSingleton().GetVirtualmapPath(fm.FCXX_ID, false), 450, 886);
                        List <string> lstStr    = txt.txtHelper.txtLines(PathManager.getSingleton().GetPlantxtPath(fm.FCXX_ID, false));

                        if (h1_4.Text == "")
                        {
                            //if (p_deed != null || p_virtual != null || lstStr.Count != 0 || t != null)
                            //{
                            if (ischild)
                            {
                                title.Less3Zero();
                                h1_4           = document.InsertParagraph(title.num3title() + "分层分户平面图");
                                h1_4.StyleName = "Heading3";
                                using (FontFamily fontfamily = new FontFamily("宋体"))
                                {
                                    h1_4.Color(Color.Black).FontSize(14).Font(fontfamily);
                                }
                            }
                            else if (istrainings)
                            {
                                title.Less4Zero();
                                h1_4           = document.InsertParagraph(title.num4title() + "分层分户平面图");
                                h1_4.StyleName = "Heading4";
                                using (FontFamily fontfamily = new FontFamily("宋体"))
                                {
                                    h1_4.Color(Color.Black).FontSize(14).Font(fontfamily);
                                }
                            }
                            else
                            {
                                title.Less2Zero();
                                h1_4           = document.InsertParagraph(title.num2title() + "分层分户平面图");
                                h1_4.StyleName = "Heading2";
                                using (FontFamily fontfamily = new FontFamily("宋体"))
                                {
                                    h1_4.Color(Color.Black).FontSize(16).Font(fontfamily);
                                }
                            }
                            //}
                        }
                        if (ischild)
                        {
                            title.Less4Zero();
                            h1_4_1           = document.InsertParagraph(title.num4title() + fm.FCXX_JZMC + "分层分户平面图");
                            h1_4_1.StyleName = "Heading4";
                            using (FontFamily fontfamily = new FontFamily("宋体"))
                            {
                                h1_4_1.Color(Color.Black).FontSize(14).Font(fontfamily).Italic();
                            }
                        }
                        else if (istrainings)
                        {
                            //title.Less4Zero();
                            h1_4           = document.InsertParagraph(title.num5title() + "分层分户平面图");
                            h1_4.StyleName = "Heading5";
                            using (FontFamily fontfamily = new FontFamily("宋体"))
                            {
                                h1_4.Color(Color.Black).FontSize(14).Font(fontfamily);
                            }
                        }
                        else
                        {
                            title.Less3Zero();
                            h1_4_1           = document.InsertParagraph(title.num3title() + fm.FCXX_JZMC + "分层分户平面图");
                            h1_4_1.StyleName = "Heading3";
                            using (FontFamily fontfamily = new FontFamily("宋体"))
                            {
                                h1_4_1.Color(Color.Black).FontSize(14).Font(fontfamily);
                            }
                        }
                        //房产证
                        if (p_deed != null)
                        {
                            var   tbl_deed = document.InsertParagraph();//房产证表格
                            Table t_deed   = tableHelper.picTable(document, p_deed, "房产证");
                            t_deed.Alignment = Alignment.center;
                            t_deed.AutoFit   = AutoFit.Contents;
                            tbl_deed.InsertTableAfterSelf(t_deed);
                        }

                        //实景图
                        if (p_virtual != null)
                        {
                            var   tbl_virtual = document.InsertParagraph();//实景图表格
                            Table t_virtual   = tableHelper.picTable(document, p_virtual, "房产外墙面实景图");
                            t_virtual.Alignment = Alignment.center;
                            t_virtual.AutoFit   = AutoFit.Contents;
                            tbl_virtual.InsertTableAfterSelf(t_virtual);
                        }

                        //平面图
                        var title2 = document.InsertParagraph();//生产综合楼分层分户平面图标题
                        title2.Append("分层分户平面图").FontSize(16);
                        title2.Alignment = Alignment.center;

                        if (lstStr.Count > 0)
                        {
                            Table t = tableHelper.PlanTable(document, companyID, parcelID, fm.FCXX_ID, lstStr);
                            t.Alignment = Alignment.center;
                            t.AutoFit   = AutoFit.Window;

                            document.InsertTable(t).Alignment = Alignment.center;
                        }
                    }


                    //if (fm.ZDXX_MC == Parcelname)
                    //{

                    //}
                }
            }
            catch (System.Exception ex)
            {
                LogHelper.WriteLog(typeof(parcelHelper), ex);
            }
        }
Exemplo n.º 8
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}");
            }
        }
Exemplo n.º 9
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();
            }
        }
Exemplo n.º 10
0
        private void createExportDoc()
        {
            try
            {
                DBManager con = new DBManager();

                var modelSpecies = con.getSpeciesList();

                if (extension == string.Empty)
                {
                    MessageBox.Show("Не выбран тип экспортруемого файла");
                    return;
                }

                switch (extension)
                {
                case (".docx"):
                    string pathDocumentDOCX = Session.baseDir + "породы животных" + extension;
                    DocX   document         = DocX.Create(pathDocumentDOCX);
                    Xceed.Document.NET.Paragraph paragraph = document.InsertParagraph();
                    paragraph.
                    AppendLine("Документ '" + "Отчет о породах животных" + "' создан " + DateTime.Now.ToShortDateString()).
                    Font("Time New Roman").
                    FontSize(16).Bold().Alignment = Alignment.left;

                    paragraph.AppendLine();
                    Xceed.Document.NET.Table doctable = document.AddTable(modelSpecies.Count + 1, 2);
                    doctable.Design       = TableDesign.TableGrid;
                    doctable.TableCaption = "порода животного";

                    doctable.Rows[0].Cells[0].Paragraphs[0].Append("Порода животного").Font("Times New Roman").FontSize(14);

                    for (int i = 0; i < modelSpecies.Count; i++)
                    {
                        doctable.Rows[i + 1].Cells[0].Paragraphs[0].Append(modelSpecies[i].Title).Font("Times New Roman").FontSize(14);
                    }
                    document.InsertParagraph().InsertTableAfterSelf(doctable);
                    document.Save();
                    MessageBox.Show("Отчет успешно сформирован!");
                    Process.Start(pathDocumentDOCX);
                    break;

                case (".xlsx"):
                    Excel.Application excel;
                    Excel.Workbook    worKbooK;
                    Excel.Worksheet   worKsheeT;
                    Excel.Range       celLrangE;

                    string pathDocumentXLSX = Session.baseDir + "Породы животных" + extension;

                    try
                    {
                        excel               = new Excel.Application();
                        excel.Visible       = false;
                        excel.DisplayAlerts = false;
                        worKbooK            = excel.Workbooks.Add(Type.Missing);


                        worKsheeT      = (Microsoft.Office.Interop.Excel.Worksheet)worKbooK.ActiveSheet;
                        worKsheeT.Name = "Породы животных";

                        worKsheeT.Range[worKsheeT.Cells[1, 1], worKsheeT.Cells[1, 8]].Merge();
                        worKsheeT.Cells[1, 1]     = "Породы животных";
                        worKsheeT.Cells.Font.Size = 15;

                        for (int i = 0; i < modelSpecies.Count; i++)
                        {
                            worKsheeT.Cells[i + 3, 1] = modelSpecies[i].Title;
                        }

                        worKbooK.SaveAs(pathDocumentXLSX);;
                        worKbooK.Close();
                        excel.Quit();
                        MessageBox.Show("Отчет успешно сформирован!");
                        Process.Start(pathDocumentXLSX);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    finally
                    {
                        worKsheeT = null;
                        celLrangE = null;
                        worKbooK  = null;
                    }

                    break;


                case (".pdf"):
                    string pathDocumentPDF = Session.baseDir + "Породы животных" + extension;
                    if (File.Exists(Session.baseDir + "Породы животных.docx"))
                    {
                        Word.Application appWord = new Word.Application();
                        var wordDocument         = appWord.Documents.Open(Session.baseDir + "Породы животных.docx");
                        wordDocument.ExportAsFixedFormat(pathDocumentPDF, Word.WdExportFormat.wdExportFormatPDF);
                        MessageBox.Show("Отчет успешно сформирован!");
                        wordDocument.Close();
                        Process.Start(pathDocumentPDF);
                    }
                    else
                    {
                        MessageBox.Show("Сначала сформируйте отчет .docx");
                    }
                    break;
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Отсутсвие Ms Office на компьютере. Пожалуйста скачайте его.");
                Process.Start("https://www.microsoft.com/ru-ru/microsoft-365/compare-all-microsoft-365-products?tab=1&rtc=1");
            }
        }
Exemplo n.º 11
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");
            }
        }
Exemplo n.º 12
0
 private static void agregarParrafo(DocX document, string texto)
 {
     document.InsertParagraph().Font("Calibri").FontSize(15).SpacingBefore(5).SpacingAfter(3).InsertText(texto);
 }
Exemplo n.º 13
0
 private static void printName(DocX document, SpecInfo spec)
 {
     document.InsertParagraph()
             .Append(spec.Name)
             .Font(new FontFamily("Cambria"))
             .FontSize(13)
             .Bold()
             .Color(Color.FromArgb(255, 54, 95, 145))
             ;
 }
Exemplo n.º 14
0
        public static void GenReport(string filename, int startIndex, string fontName)
        {
            Dictionary <string, string> syn = GenSyn();
            FileStream   srcFs    = File.OpenRead(filename);
            XmlDocument  dataFile = new XmlDocument();
            GZipStream   g        = new GZipStream(srcFs, CompressionMode.Decompress);
            MemoryStream ms       = new MemoryStream();

            byte[] bytes = new byte[40960];
            int    n;

            while ((n = g.Read(bytes, 0, bytes.Length)) > 0)
            {
                ms.Write(bytes, 0, n);
            }
            g.Close();
            ms.Position = 0;
            byte[] eData = ms.ToArray();
            for (int i = 0; i < eData.Length; i++)
            {
                eData[i] = (byte)(eData[i] + i);
            }
            ms = new MemoryStream(eData);
            dataFile.Load(ms);
            srcFs.Close();
            XmlNode       root     = dataFile.SelectSingleNode("ListDocument");
            var           projName = root.SelectSingleNode("Proj").Attributes["name"].InnerText;
            List <string> items    = new List <string>();

            foreach (XmlNode i in root.SelectSingleNode("ItemList").ChildNodes)
            {
                items.Add(i.Attributes["name"].InnerText);
            }
            List <string> lots = new List <string>();

            foreach (XmlNode i in root.SelectSingleNode("Lots").ChildNodes)
            {
                lots.Add(i.Attributes["l"].InnerText);
            }
            Dictionary <string, string> STD = new Dictionary <string, string>();

            foreach (XmlNode i in root.SelectSingleNode("STD").ChildNodes)
            {
                STD.Add(i.Attributes["suf"].InnerText, i.Attributes["item"].InnerText);
            }
            List <ListInj> injs = new List <ListInj>();

            foreach (XmlNode i in root.SelectSingleNode("List").ChildNodes)
            {
                injs.Add(new ListInj(int.Parse(i.Attributes["count"].InnerText), i.Attributes["name"].InnerText));
            }
            injs = SimplifyList(injs);
            // Below is writing docx file using items, lots, STD, injs
            Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("zh-CN");
            string temp          = Environment.GetEnvironmentVariable("TEMP");
            Random rnd           = new Random();
            string shortFileName = filename.Substring(filename.LastIndexOf("\\") + 1, filename.Length - filename.LastIndexOf("\\") - 5);

            if (temp == "")
            {
                temp = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + shortFileName + "_" + rnd.Next(0, 500).ToString() + ".docx";
            }
            else
            {
                temp = temp + "\\" + shortFileName + "_" + rnd.Next(0, 500).ToString() + ".docx";
            }
            using (DocX document = DocX.Create(temp, DocumentTypes.Document))
            {
                //Start of title
                string title = projName;
                foreach (var i in items)
                {
                    title += syn[i] + "、";
                }
                title  = title.Substring(0, title.Length - 1);
                title += "测定";
                document.InsertParagraph(title).FontSize(16d).SpacingAfter(8).Font(new Font(fontName)).Alignment = Alignment.center;
                // End of Title (OK)
                // Start of Lot
                var p = document.InsertParagraph();
                // Append some text and add formatting.
                p.Append("批号:\t").Font(new Font(fontName)).FontSize(13);
                p.Append(ParseLotReport(lots).Replace("[and_placeholder]", "&")).Font(new Font(fontName)).FontSize(13);
                //End of Lot
                //Start of Table
                var t        = document.AddTable(1, 3);
                var colWidth = new float[] { 180f, 700f, 150f };
                t.SetWidths(colWidth);
                t.Alignment = Alignment.center;
                t.Design    = TableDesign.TableGrid;
                WordPlugin.Formatting f = new WordPlugin.Formatting();
                f.FontFamily = new Font(fontName);
                f.Size       = 13;
                t.Rows[0].Cells[0].Paragraphs[0].Append("图谱编号", f);
                t.Rows[0].Cells[0].VerticalAlignment = VerticalAlignment.Center;
                t.Rows[0].Cells[1].Paragraphs[0].Append("图谱内容", f);
                t.Rows[0].Cells[1].VerticalAlignment = VerticalAlignment.Center;
                t.Rows[0].Cells[2].Paragraphs[0].Append("备注", f);
                t.Rows[0].Cells[2].VerticalAlignment = VerticalAlignment.Center;
                if (startIndex != 1)
                {
                    injs.Insert(0, new ListInj(startIndex - 1, ""));
                }
                startIndex = 1;
                foreach (var inj in injs)
                {
                    string strIndex = startIndex.ToString();
                    if (inj.Count != 1)
                    {
                        strIndex += "-";
                    }
                    startIndex += inj.Count;
                    if (inj.Count != 1)
                    {
                        strIndex += (startIndex - 1).ToString();
                    }
                    var c = t.InsertRow();
                    c.Cells[0].Paragraphs[0].Append(strIndex, f);
                    c.Cells[0].VerticalAlignment = VerticalAlignment.Center;
                    c.Cells[1].Paragraphs[0].Append(inj.Name == "" ? "" : ParseInjName(inj.Name).Replace("[and_placeholder]", "&"), f);
                    c.Cells[1].VerticalAlignment = VerticalAlignment.Center;
                    c.Cells[2].Paragraphs[0].Append("--", f);
                    c.Cells[2].VerticalAlignment = VerticalAlignment.Center;
                }
                document.InsertParagraph().InsertTableAfterSelf(t);
                document.Save();
            }
            System.Diagnostics.Process.Start("winword.exe", temp);
        }
Exemplo n.º 15
0
        public void TestTFS()
        {
            #region Start up
            ExtentTest test = null;

            DateTime now      = DateTime.Now;
            string   testName = "TFSDoc";
            DocX     doc      = DocX.Create(testName);

            // Test Case Pull
            PropertiesReader config = new PropertiesReader("config.txt");

            Properties props = new Properties();
            props.PersonalAccessToken = config.get("personalaccesstoken");
            props.TestPlanId          = Convert.ToInt32(config.get("testplanid"));
            props.TestSuiteId         = Convert.ToInt32(config.get("testsuiteid"));
            props.Project             = config.get("project");
            props.Uri                = config.get("server");
            props.SaveLocation       = config.get("saveLocation");
            props.FileName           = StringTools.addExtension(config.get("fileName"), "xlsx");;
            props.ExecutionSheetName = config.get("executionsheetname");
            props.ScriptSheetName    = config.get("scriptsheetname");
            props.TestPlanId         = Convert.ToInt32(config.get("testplanid"));
            props.TestSuiteId        = Convert.ToInt32(config.get("testsuiteid"));

            Logger logger = new Logger(props.SaveLocation);

            props.Logger = logger;

            TestCase thisTestCase = new TestCase();
            RequirementsTraceabilityJobs requirementsTraceabilityJob = new RequirementsTraceabilityJobs(props);
            thisTestCase = requirementsTraceabilityJob.GetSingleTestCase(152599, 152048);
            foreach (TestStep testStep in thisTestCase.TestSteps)
            {
                string action   = testStep.Action;
                string expected = testStep.Expected;
            }
            #endregion

            using (context)
            {
                context.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
                context.Url = "http://somedomain/url_that_delays_loading";
                IWebElement myDynamicElement = context.FindElement(By.Id("someDynamicElement"));
            }
            using (context)
            {
                context.Url = "http://somedomain/url_that_delays_loading";
                WebDriverWait wait             = new WebDriverWait(context, TimeSpan.FromSeconds(10));
                IWebElement   myDynamicElement = wait.Until <IWebElement>(d => d.FindElement(By.Id("someDynamicElement")));
            }

            try
            {
                foreach (TestStep testStep in thisTestCase.TestSteps)
                {
                    string    action   = testStep.Action;
                    string    expected = testStep.Expected;
                    Paragraph par      = doc.InsertParagraph(action + ": " + expected);
                }
                doc.Save();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
Exemplo n.º 16
0
        private void Generate(int count)
        {
            while (true)
            {
                List <List <double> > table = new List <List <double> >()
                {
                    new List <double>()
                    {
                        r.Next(-15, 15), r.Next(-15, 15), r.Next(-15, 15)
                    },
                    new List <double>()
                    {
                        r.Next(-15, 15), r.Next(-15, 15), r.Next(-15, 15)
                    },
                    new List <double>()
                    {
                        r.Next(-15, 15), r.Next(-15, 15), r.Next(-15, 15)
                    },
                    new List <double>()
                    {
                        r.Next(-15, 15), r.Next(-15, 15), r.Next(-15, 15)
                    },
                    new List <double>()
                    {
                        0, r.Next(-15, 15), r.Next(-15, 15)
                    }
                };

                List <double> result = new List <double>();
                for (int i = 0; i < table[0].Count - 1; i++)
                {
                    result.Add(new double());
                }

                List <List <double> > table_result = new List <List <double> >();

                Function f = r.Next(10) % 2 == 0 ? Function.Max : Function.Min;

                Function fr = f;
                int      f1 = (int)table[4][1];
                int      f2 = (int)table[4][2];

                bool flag  = true;
                bool nnull = true;
                int  _c    = 0;

                if (f == Function.Max)
                {
                    changeSign(ref table);
                }

                for (int i = 0; i < table.Count; i++)
                {
                    for (int k = 0; k < table[i].Count; k++)
                    {
                        if (k == 0)
                        {
                            if (table[i][k] < 0)
                            {
                                flag = false;
                                continue;
                            }
                        }
                        else
                        {
                            if (table[i][k] < 0)
                            {
                                _c++;
                            }
                            else if (table[i][k] > 0)
                            {
                                if (!nnull)
                                {
                                    nnull = true;
                                }
                            }
                            else
                            {
                                nnull = false;
                            }
                        }

                        if (_c == 2)
                        {
                            flag = false;
                        }
                    }
                    if (!nnull)
                    {
                        break;
                    }
                    _c = 0;
                }

                if (!flag || !nnull)
                {
                    continue;
                }

                Simplex S = new Simplex(table, f, Operation.Generate);
                table_result = S.Calculate(ref result);

                if (table_result == null)
                {
                    continue;
                }

                if (result[0] != (int)result[0] || result[1] != (int)result[1] || result[0] == 0 || result[1] == 0 || result[0] < -30 || result[0] > 30 || result[1] < -30 || result[1] > 30)
                {
                    continue;
                }

                string sign = fr == Function.Max ? ">=" : "<=";

                doc_output.InsertParagraph("Билет №" + count.ToString())
                .Font(new System.Drawing.FontFamily("Calibri"))
                .FontSize(14)
                .Alignment = Alignment.center;
                doc_output.InsertParagraph("Решить симплексным методом, с использованием симплексной таблицы при следующих условиях: ")
                .SpacingAfter(0)
                .Font(new System.Drawing.FontFamily("Calibri"))
                .FontSize(14);
                doc_output.InsertParagraph(string.Format(" {0}x1+({1}x2) <= {2}", table[0][1], table[0][2], table[0][0]))
                .Font(new System.Drawing.FontFamily("Calibri"))
                .FontSize(14);
                doc_output.InsertParagraph(string.Format(" {0}x1+({1}x2) <= {2}", table[1][1], table[1][2], table[1][0]))
                .Font(new System.Drawing.FontFamily("Calibri"))
                .FontSize(14);
                doc_output.InsertParagraph(string.Format(" {0}x1+({1}x2) <= {2}", table[2][1], table[2][2], table[2][0]))
                .Font(new System.Drawing.FontFamily("Calibri"))
                .FontSize(14);
                doc_output.InsertParagraph(string.Format(" {0}x1+({1}x2) <= {2}", table[3][1], table[3][2], table[3][0]))
                .Font(new System.Drawing.FontFamily("Calibri"))
                .FontSize(14);
                doc_output.InsertParagraph(" x1x2 " + ">=" /*sign*/ + " 0")
                .Font(new System.Drawing.FontFamily("Calibri"))
                .FontSize(14);
                doc_output.InsertParagraph(string.Format("F(x1,x2) = {0}x1 + ({1}x2) -> {2}", f1, f2, sign == ">=" ? "max" : "min"))
                .Font(new System.Drawing.FontFamily("Calibri"))
                .FontSize(14);
                doc_output.InsertParagraph()
                .Font(new System.Drawing.FontFamily("Calibri"))
                .FontSize(14);

                doc_answer.InsertParagraph(string.Format("Билет № {2} x1 = {0}, x2 = {1}", result[0], result[1], count))
                .Font(new System.Drawing.FontFamily("Calibri"))
                .FontSize(14);

                return;
            }
        }
Exemplo n.º 17
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();
                }
            }
        }
Exemplo n.º 18
0
            private static void printThen(DocX document, SpecInfo spec)
            {
                document.InsertParagraph()
                    .Append("Then")
                    .Font(new FontFamily("Cambria"))
                        .FontSize(13)
                        .Bold()
                        .Color(Color.FromArgb(255, 79, 129, 189));

                foreach (var then in spec.Thens)
                {
                    var description = spec.HasExecutionBeenTriggered
                                          ? string.Format("{0} [{1}]", then.Description, then.Passed ? "Passed" : "Failed")

                                          : then.Description;
                    var p = document.InsertParagraph()
                            .Append(description)
                            .FontSize(12)
                            .Color(spec.HasExecutionBeenTriggered ? (then.Passed ? Color.Green : Color.Red) : Color.Black);

                    if (!then.Passed && then.Exception != null)
                        p.AppendLine(then.Exception.ToString());

                    p.IndentationBefore = 0.5f;
                }
            }
Exemplo n.º 19
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);
        }
Exemplo n.º 20
0
        public string GerarTermo(int id_mediacao, string caminho)
        {
            try
            {
                mediacao md = new mediacao();

                md = Obter(id_mediacao);
                // nome = numero + ano
                String nome = md.numero.ToString() + "_" + md.data_mediacao.Year.ToString();
                // nome completo = caminho + nome.docx
                // ex: Desktop\002_2016.docx
                String nomeArquivo = caminho + @"\" + nome + ".docx";

                // gera o documento da mediação

                // Se o arquivo já existe, não salva novamente
                //if (File.Exists(nomeArquivo))
                //{
                //    return nomeArquivo;
                //}

                string modelo = AppDomain.CurrentDomain.BaseDirectory + "modelo_med.docx";
                using (DocX document = DocX.Load(modelo))
                {
                    // adiciona o nome do batalhão no arquivo
                    document.ReplaceText("[batalhao]", md.local.nome, false);
                    // adiciona o nome da companhia no arquivo
                    document.ReplaceText("[companhia]", md.local.descricao, false);
                    // adiciona o numero da mediação no arquivo
                    document.ReplaceText("[numero]", md.numero.ToString(), false);
                    // adiciona o ano no arquivo
                    document.ReplaceText("[ano]", md.data_mediacao.Year.ToString(), false);
                    // informa o tema do conflito
                    document.ReplaceText("[tema_conflito]", md.tema_conflito, false);
                    // rodapé
                    document.ReplaceText("[cidade]", md.local.cidade.nome, false);
                    document.ReplaceText("[data_escrita]", md.data_mediacao.ToLongDateString(), false);

                    string partes = "", nome_partes = "", assinaturas = "";

                    int i = 0;

                    Paragraph p = null;

                    foreach (mediacao_parte mp in md.mediacao_partes)
                    {
                        p = document.InsertParagraph();

                        i++;
                        p.Append("PARTE " + i.ToString() + ": ").Bold().Append(mp.pessoa.nome.ToString() + ", ");
                        p.Append("RG: ").Bold().Append(mp.pessoa.rg + ", ");
                        p.Append("CPF: ").Bold().Append(mp.pessoa.cpf + ", ");
                        p.Append(mp.pessoa.status_civil + ", ");
                        p.Append(mp.pessoa.profissao + ", ");
                        p.Append("NASCIDO EM ").Bold().Append(DateTime.Parse(mp.pessoa.nascimento_data.ToString()).ToShortDateString() + ", ");
                        p.Append("NA CIDADE DE ").Bold().Append(mp.pessoa.cidade1.nome + " - " + mp.pessoa.cidade1.estado + ", ");
                        p.Append("DO SEXO ").Bold().Append(GetSexo(mp.pessoa.sexo.ToString()) + ", ");
                        p.Append("FILHO DE ").Bold().Append(mp.pessoa.nome_pai);
                        p.Append(" E ").Bold().Append(mp.pessoa.nome_mae + ", ");
                        p.Append("RESIDENTE NA ").Bold().Append(mp.pessoa.endereco_logradouro + " nº " +
                                                                mp.pessoa.endereco_numero + ", " +
                                                                mp.pessoa.endereco_bairro + ", " +
                                                                mp.pessoa.cidade.nome + " - " + mp.pessoa.cidade.estado + ", ");
                        if ((mp.pessoa.telefone != null) && (mp.pessoa.telefone != ""))
                        {
                            p.Append("TELEFONE ").Bold().Append(mp.pessoa.telefone + ", ");
                        }
                        p.Append("aceitou a participar da sessão de mediação de conflito onde declarou que: ").Bold().Alignment = Alignment.both;
                        p.AppendLine(mp.descricao_caso);
                        p.AppendLine();
                        p.AppendLine();
                        //p.AppendLine("ASSINATURA (PARTE " + i.ToString() + ")");
                        //p.AppendLine();
                        //p.AppendLine();
                        p = null;

                        document.InsertParagraph("ASSINATURA (PARTE " + i.ToString() + ")").AppendLine().Alignment = Alignment.right;

                        if (i > 1)
                        {
                            partes = partes + ", " + mp.pessoa.nome;
                        }
                        else
                        {
                            partes = mp.pessoa.nome;
                        }
                        if (i > 1)
                        {
                            nome_partes = nome_partes + ", e ";
                        }
                        if (mp.pessoa.sexo == 'M')
                        {
                            nome_partes = nome_partes + "Sr. " + mp.pessoa.nome;
                        }
                        else
                        {
                            nome_partes = nome_partes + "Sra. " + mp.pessoa.nome;
                        }

                        assinaturas = assinaturas + "__________________________________" + Environment.NewLine +
                                      "RG:" + Environment.NewLine + Environment.NewLine;
                    }

                    // adiciona o nome das partes no arquivo
                    document.ReplaceText("[partes]", partes, false);

                    Paragraph p2 = document.InsertParagraph();

                    // =========== DECLARAÇÃO FINAL MEDIAÇÃO =============
                    p2.InsertPageBreakBeforeSelf();
                    p2.Append("Pelo presente Termo de \"MEDIAÇÃO\", as partes, " + nome_partes +
                              " presentes no núcleo de Mediação Comunitária do " + md.local.nome + "/" + md.local.descricao +
                              ", situado na " + md.local.logradouro + ", nº " + md.local.numero + ", " +
                              "Bairro " + md.local.bairro + ", na cidade de " + md.local.cidade.nome + " - " + md.local.cidade.estado +
                              " resolvem aceitar a adoção do " +
                              "procedimento de mediação para a resolução de conflito relatado neste instrumento de registro " +
                              "policial, obrigando - se a manter sigilo, assim como o mediador, de toda e qualquer informação, " +
                              "documentos, papéis em geral, enfim, de tudo que lhes seja apresentado ou chegue ao seu conhecimento " +
                              "em razão do procedimento de mediação aqui homologado. O descumprimento da obrigação de sigilo por " +
                              "qualquer das partes ou pelo mediador implicará em responsabilidade civil e criminal.").Alignment = Alignment.both;
                    // objeto da mediação
                    p2.AppendLine();

                    Paragraph objeto = document.InsertParagraph();
                    objeto.AppendLine("O objeto da mediação é o seguinte:").AppendLine(md.objeto).AppendLine().Alignment = Alignment.left;
                    // assinaturas
                    objeto.AppendLine(assinaturas).AppendLine();

                    Paragraph p3 = document.InsertParagraph();

                    p3.AppendLine(md.mediador.nome).Bold();
                    p3.AppendLine(md.mediador.patente + " - Mediador").Alignment = Alignment.right;

                    // ACOMPANHAMENTOS


                    List <acompanhamento> listAcomp = new List <acompanhamento>();

                    listAcomp = ListarAcompanhamentos(md.id);

                    if (listAcomp.Count > 0)
                    {
                        Paragraph p4 = document.InsertParagraph();
                        p4.InsertPageBreakBeforeSelf();

                        foreach (acompanhamento acp in listAcomp)
                        {
                            p4.AppendLine("Acompanhamento do mediador:").Bold().AppendLine();
                            p4.AppendLine("Data: " + acp.data.ToString());
                            p4.AppendLine("Verificação: " + acp.verificacao).AppendLine();
                            p4.AppendLine("Assinatura/Carimbo: ").AppendLine();
                        }
                    }

                    // salva o documento
                    document.SaveAs(nomeArquivo);
                }

                return(nomeArquivo);
            }
            catch (Exception e)
            {
                message = e.Message;
                return("");
            }
        }
Exemplo n.º 21
0
 private void GerarSubtitulo(DocX docX)
 {
     docX.InsertParagraph("Questionário Avaliativo Dissertativo").Bold().FontSize(12).Alignment = Alignment.center;
     docX.InsertParagraph("(Deve ser entregue pelo aluno no término do Estágio Supervisionado) ").FontSize(10).Alignment = Alignment.center;
     docX.InsertParagraph(System.Environment.NewLine).AppendLine();
 }
Exemplo n.º 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();
            }
        }
Exemplo n.º 23
0
        private void procesoPPC(DocX doc, Formatting formatoTituloColumna)
        {
            indices.Clear();
            renglones = 1;
            columnas  = 1;

            // Se recorre el arreglo para saber agregar los indices que indicarán qué valores
            // serán mostrados en la tabla, el tamaño del arreglo serán las columnas
            for (int ind = 0; ind < PPC.Count; ind++)
            {
                if (PPC[ind])
                {
                    indices.Add(ind);
                }
            }
            columnas = indices.Count;

            // Primero que nada se consulta el número de pagos completados para los renglones
            co.Comando("SELECT COUNT(*) FROM PagoProgramado WHERE NumTotalPagos = 0;");
            if (co.LeerRead)
            {
                renglones = co.Leer.GetInt32(0);
            }

            if (renglones != 0)
            {
                doc.InsertParagraph("Pagos programados completados", false, formatoTituloColumna);
            }
            else
            {
                doc.InsertParagraph("No hay pagos programados completados", false, formatoTituloColumna);
                return;
            }

            Table t = doc.AddTable(renglones + 1, columnas);

            t.Alignment = Alignment.left;
            t.Design    = TableDesign.LightGridAccent3;

            // Columna por columna se le agrega el título que es obtenido de la siguiente manera:
            // El contador "col" va de 0 hasta el tamaño del arreglo de indices
            // Se recorren los índices para mandarlo al metodo de los nombres y así obtener
            //    de qué columna se trata
            for (int col = 0; col < indices.Count; col++)
            {
                t.Rows[0].Cells[col].Paragraphs.First().Append(columnasPPC(indices[col]));
            }

            co.Comando("SELECT p.ID, e.Nombre, t.Nombre, IFNULL(pro.Nombre,'Sin Proyecto'), p.NumTotalPagos  " +
                       "FROM Empleado AS e " +
                       "INNER JOIN Pago_Empleado_Trabajos AS pet ON(pet.EmpleadoID = e.ID) " +
                       "INNER JOIN PagoProgramado AS p ON(pet.PagoProgramadoID = p.ID) " +
                       "INNER JOIN Trabajos AS t ON(t.ID = pet.TrabajosID) " +
                       "LEFT OUTER JOIN Proyectos AS pro ON(pro.ID = t.ProyectosID) " +
                       "WHERE p.NumTotalPagos = 0");

            int i = 0;

            while (co.LeerRead)
            {
                for (int col = 0; col < columnas; col++)
                {
                    t.Rows[i + 1].Cells[col].Paragraphs.First().Append(valoresPPC(indices[col]));
                }
                i++;
            }
            doc.InsertTable(t);
            doc.InsertParagraph("\n");
        }
Exemplo n.º 24
0
        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");
            //}
        }
Exemplo n.º 25
0
        private void procesoPR(DocX doc, Formatting formatoTituloColumna)
        {
            bool band = true;

            indices.Clear();
            renglones = 1;
            columnas  = 1;

            // Se recorre el arreglo para saber agregar los indices que indicarán qué valores
            // serán mostrados en la tabla, el tamaño del arreglo serán las columnas
            for (int ind = 0; ind < PR.Count; ind++)
            {
                if (PR[ind])
                {
                    indices.Add(ind);
                }
            }
            columnas = indices.Count;

            // Se obtienen el total de pagos realizados y se almacena en renglones
            // -------------------------------------------------------------------------------
            co.Comando("SELECT COUNT(*) FROM Pagos WHERE PagoProgramadoID IS NOT NULL AND FechaPago BETWEEN '" + fechaA + "' AND '" + fechaB + "';");
            if (co.LeerRead)
            {
                renglones = co.Leer.GetInt32(0);
            }

            if (renglones != 0)
            {
                doc.InsertParagraph("Pagos realizados", false, formatoTituloColumna);
            }
            else
            {
                doc.InsertParagraph("No hay pagos realizados", false, formatoTituloColumna);
                return;
            }

            // En caso de que se pida el total, entonces se agrega un renglón donde se mostrará el total
            if (indices.Contains(5))
            {
                columnas--;
                renglones++;
                if (columnas <= 1)
                {
                    columnas = 2;
                }
            }

            // Primera parte para la generación de tabla solamente con totales
            if (indices.Count == 1 && indices[0] == 5)
            {
                columnas  = 2;
                renglones = 0;
            }

            Table t = doc.AddTable(renglones + 1, columnas);

            t.Alignment = Alignment.left;
            t.Design    = TableDesign.LightGridAccent3;

            // Segunda parte para la generación de tabla solamente con totales
            if (indices.Count == 1 && indices[0] == 5)
            {
                columnas  = 2;
                renglones = 1;
                t.Rows[t.RowCount - 1].Cells[columnas - 2].Paragraphs.First().Append("Total");
                t.Rows[t.RowCount - 1].Cells[columnas - 1].Paragraphs.First().Append("$ " + totalPR());
                band = false;
            }

            if (band)
            {
                // Columna por columna se le agrega el título que es obtenido de la siguiente manera:
                // El contador "col" va de 0 hasta el tamaño del arreglo de indices
                // Se recorren los índices para mandarlo al método de los nombres y así obtener
                //    de qué columna se trata
                for (int col = 0; col < columnas; col++)
                {
                    if (indices[col] != 5)
                    {
                        t.Rows[0].Cells[col].Paragraphs.First().Append(columnasPR(indices[col]));
                    }
                }

                //De los pagos realizados se obtien el ID, nombre del empleado y trabajo, fecha de pago
                co.Comando("SELECT Distinct  p.ID, e.Nombre, t.Nombre ,concat(DAY(p.FechaPago), '/', MONTH(p.FechaPago), '/', YEAR(p.FechaPago)), p.monto " +
                           "FROM Pagos as p INNER JOIN PagoProgramado as PaPr ON(p.PagoProgramadoID = PaPr.ID) " +
                           "INNER JOIN Pago_Empleado_Trabajos as Pet ON(Papr.ID = Pet.PagoProgramadoID)" +
                           "INNER JOIN Empleado_Trabajos as Et ON(Pet.EmpleadoID = Et.EmpleadoID)" +
                           "INNER JOIN Empleado as e ON(Pet.EmpleadoID = e.ID)" +
                           "INNER JOIN Trabajos as t ON(Pet.TrabajosID = t.ID)" +
                           "WHERE p.FechaPago BETWEEN '" + fechaA + "' AND '" + fechaB + "' ;");

                int i = 0;
                while (co.LeerRead)
                {
                    for (int col = 0; col < columnas; col++)
                    {
                        if (indices[col] != 5)
                        {
                            t.Rows[i + 1].Cells[col].Paragraphs.First().Append(valoresPR(indices[col]));
                        }
                    }
                    i++;
                }
                if (indices.Contains(5))
                {
                    t.Rows[t.RowCount - 1].Cells[columnas - 2].Paragraphs.First().Append("Total");
                    t.Rows[t.RowCount - 1].Cells[columnas - 1].Paragraphs.First().Append("$ " + totalPR());
                }
            }
            doc.InsertTable(t);
            doc.InsertParagraph("\n");
        }
Exemplo n.º 26
0
        /// <summary>
        /// 插入宗地图模块
        /// </summary>
        /// <param name="document"></param>
        /// <param name="ischild">判断是否作为市级公司的下级</param>
        public void insertZDT(DocX document, bool ischild, bool istrainings, NumoftitleHelper title)
        {
            try
            {
                Paragraph h1_1;
                Picture   p = picHelper.getPic(document, PathManager.getSingleton().GetParcelpicPath(parcelID, false), 724, 833);
                //if (p == null) return;
                if (p != null)
                {
                    if (ischild)
                    {
                        title.Less3Zero();
                        h1_1           = document.InsertParagraph(title.num3title() + "宗地图");
                        h1_1.StyleName = "Heading3";
                        using (FontFamily fontfamily = new FontFamily("宋体"))
                        {
                            h1_1.Color(Color.Black).FontSize(14).Font(fontfamily);
                        }
                    }
                    else if (istrainings)
                    {
                        title.Less4Zero();
                        h1_1           = document.InsertParagraph(title.num4title() + "宗地图");
                        h1_1.StyleName = "Heading4";
                        using (FontFamily fontfamily = new FontFamily("宋体"))
                        {
                            h1_1.Color(Color.Black).FontSize(14).Font(fontfamily);
                        }
                    }
                    else
                    {
                        title.Less2Zero();
                        h1_1           = document.InsertParagraph(title.num2title() + "宗地图");
                        h1_1.StyleName = "Heading2";
                        using (FontFamily fontfamily = new FontFamily("宋体"))
                        {
                            h1_1.Color(Color.Black).FontSize(16).Font(fontfamily);
                        }
                    }
                    h1_1.AppendLine();
                    var   parcelPic = document.InsertParagraph();
                    Table t         = tableHelper.parcelpicTabel(document, p, "宗地图");
                    t.Alignment = Alignment.center;
                    t.AutoFit   = AutoFit.Contents;
                    parcelPic.InsertTableAfterSelf(t).Alignment = Alignment.center;
                    //t.AutoFit = AutoFit.
                    //picHelper.insert(document, parcelPic, path.pathHelper.GetParcelpicPath(CompanyID, Parcelname), 592, 630);
                    parcelPic.AppendLine();
                }

                using (FontFamily fontFamily = new FontFamily("宋体"))
                {
                    var landusePic = document.InsertParagraph("国有土地使用证", false, format.formatHelper.SetParagraphFormat(fontFamily, 16, Color.Black));
                    //landusePic.Append("国有土地使用证").FontSize(16);
                    landusePic.AppendLine();
                    picHelper.insert(document, landusePic, PathManager.getSingleton().GetLandusepicPath(parcelID, false), 406, 570);
                }
            }
            catch (System.Exception ex)
            {
                LogHelper.WriteLog(typeof(parcelHelper), ex);
            }
        }
Exemplo n.º 27
0
        private void procesoGR(DocX doc, Formatting formatoTituloColumna, String nombreArchivo)
        {
            indices.Clear();
            renglones = 1;
            columnas  = 1;

            // Se recorre el arreglo para saber agregar los indices que indicarán qué valores
            // serán mostrados en la tabla, el tamaño del arreglo serán las columnas
            for (int ind = 0; ind < GR.Count; ind++)
            {
                if (GR[ind])
                {
                    indices.Add(ind);
                }
            }
            columnas = indices.Count;

            // Se obtienen el total de gastos realizados y se almacena en renglones
            co.Comando("SELECT renglonesGR('" + fechaA + "', '" + fechaB + "');");
            if (co.LeerRead)
            {
                renglones = co.Leer.GetInt32(0);
            }

            if (renglones != 0)
            {
                doc.InsertParagraph("Gastos realizados", false, formatoTituloColumna);
            }
            else
            {
                doc.InsertParagraph("No hay gastos realizados", false, formatoTituloColumna);
                return;
            }

            // En caso de que se pida el total, entonces se agrega un renglón donde se mostrará el total
            if (indices.Contains(5))
            {
                columnas--;
                renglones++;
                if (columnas <= 1)
                {
                    columnas = 2;
                }
            }

            // Primera parte para la generación de tabla solamente con totales
            if (indices.Count == 1 && indices[0] == 5)
            {
                columnas  = 2;
                renglones = 0;
            }

            Table t = doc.AddTable(renglones + 1, columnas);

            t.Alignment = Alignment.left;
            t.Design    = TableDesign.LightGridAccent3;

            // Segunda parte para la generación de tabla solamente con totales
            if (indices.Count == 1 && indices[0] == 5)
            {
                columnas  = 2;
                renglones = 1;
                t.Rows[t.RowCount - 1].Cells[columnas - 2].Paragraphs.First().Append("Total");
                t.Rows[t.RowCount - 1].Cells[columnas - 1].Paragraphs.First().Append("$ " + totalGR());
                doc.InsertTable(t);
                doc.InsertParagraph("\n");
                doc.Save();
                Process.Start("WINWORD.EXE", nombreArchivo);
                return;
            }

            // Columna por columna se le agrega el título que es obtenido de la siguiente manera:
            // El contador "col" va de 0 hasta el tamaño del arreglo de indices
            // Se recorren los índices para mandarlo al metodo de los nombres y así obtener
            //    de qué columna se trata
            for (int col = 0; col < columnas; col++)
            {
                if (indices[col] != 5)
                {
                    t.Rows[0].Cells[col].Paragraphs.First().Append(columnasGR(indices[col]));
                }
            }

            //Saco los datos de cada gasto y los coloco en la tabla
            co.Comando("SELECT p.ID, g.Concepto, m.Metodo, concat(DAY(p.FechaPago), '/', MONTH(p.FechaPago), '/', YEAR(p.FechaPago)), p.Monto " +
                       "FROM Pagos AS p INNER JOIN Metodo AS m ON(m.ID = p.MetodoID) " +
                       "INNER JOIN Gasto AS g ON(g.ID = p.GastoID) " +
                       "WHERE p.GastoID IS NOT NULL " +
                       "AND p.FechaPago BETWEEN '" + fechaA + "' AND '" + fechaB + "' ;");
            int i = 0;

            while (co.LeerRead)
            {
                for (int col = 0; col < columnas; col++)
                {
                    if (indices[col] != 5)
                    {
                        t.Rows[i + 1].Cells[col].Paragraphs.First().Append(valoresGR(indices[col]));
                    }
                }
                i++;
            }
            if (indices.Contains(5))
            {
                t.Rows[t.RowCount - 1].Cells[columnas - 2].Paragraphs.First().Append("Total");
                t.Rows[t.RowCount - 1].Cells[columnas - 1].Paragraphs.First().Append("$ " + totalGR());
            }
            doc.InsertTable(t);
            doc.InsertParagraph("\n");
        }
Exemplo n.º 28
0
        public string GenerateBidQuestionDocument(gpTenderProjectWebDO gptp)
        {
            string path = Path.Combine(AppDirectory.Temp_Dir(gptp.gpId), "问题澄清.docx");

            IGpTfOperationService gpTfOperationService = new GpTfOperationService();

            //澄清
            var result1 = gpTfOperationService.FindQuestions(gptp.gtpId, gptp.gpId, string.Empty, 1);

            //修改
            var result2 = gpTfOperationService.FindQuestions(gptp.gtpId, gptp.gpId, string.Empty, 2);

            if (result1.Count() == 0 && result2.Count() == 0)
            {
                return(string.Empty);
            }

            using (DocX document = DocX.Create(path))
            {
                //标题
                document.InsertParagraph("《问题澄清》").FontSize(18d).Bold().SpacingAfter(50d).Alignment = Alignment.center;

                //澄清
                var t1 = document.AddTable(result1.Count() + 1, 3);
                t1.Design    = TableDesign.ColorfulList;
                t1.Alignment = Alignment.center;

                //标题
                t1.Rows[0].Cells[0].Paragraphs[0].Append("标题");
                t1.Rows[0].Cells[1].Paragraphs[0].Append("内容");
                t1.Rows[0].Cells[2].Paragraphs[0].Append("创建时间");

                int indexer = 1;

                foreach (var item in result1)
                {
                    t1.Rows[indexer].Cells[0].Paragraphs[0].Append(item.gtoTitle);
                    t1.Rows[indexer].Cells[1].Paragraphs[0].Append(item.gtoContent);
                    t1.Rows[indexer].Cells[2].Paragraphs[0].Append(item.optTime.ToLongDateString());

                    indexer++;
                }

                //修改
                var t2 = document.AddTable(result2.Count() + 1, 3);
                t2.Design    = TableDesign.ColorfulList;
                t2.Alignment = Alignment.center;

                //标题
                t2.Rows[0].Cells[0].Paragraphs[0].Append("标题");
                t2.Rows[0].Cells[1].Paragraphs[0].Append("内容");
                t2.Rows[0].Cells[2].Paragraphs[0].Append("创建时间");

                indexer = 1;

                foreach (var item in result2)
                {
                    t2.Rows[indexer].Cells[0].Paragraphs[0].Append(item.gtoTitle);
                    t2.Rows[indexer].Cells[1].Paragraphs[0].Append(item.gtoContent);
                    t2.Rows[indexer].Cells[2].Paragraphs[0].Append(item.optTime.ToLongDateString());

                    indexer++;
                }

                // Insert a new Paragraph into the document.
                var p1 = document.InsertParagraph("澄清:");
                p1.SpacingAfter(10d);

                // Insert the Table after the Paragraph.
                p1.InsertTableAfterSelf(t1);

                // Insert a new Paragraph into the document.
                var p2 = document.InsertParagraph("修改:");
                p2.SpacingAfter(10d);

                // Insert the Table after the Paragraph.
                p2.InsertTableAfterSelf(t2);

                document.Save();
            }

            return(path);
        }
Exemplo n.º 29
0
        public NewBlank(int id_Заказа, DateTime ДатаЗаказа, int id_Профиля, int Высота, int Ширина, int Количество, bool ustanovka, bool nalichniki, bool zamok, bool ruchka, bool petli, string Заказчик_ФИО, int Заказчик_ТелефонныйПрефикс, int Заказчик_Телефон)
        {
            string ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=" + System.Windows.Forms.Application.StartupPath + @"\Resources\doors.mdf;Integrated Security=True;Connect Timeout=30";

            Directory.CreateDirectory(Environment.CurrentDirectory + @"\Оформленные заказы");
            string path = Environment.CurrentDirectory + @"\Оформленные заказы\Заказ №" + (100000 + id_Заказа).ToString() + ".docx";

            DocX document = DocX.Create(path);

            document.MarginTop    = 30;
            document.MarginLeft   = 30;
            document.MarginRight  = 30;
            document.MarginBottom = 30;

            document.InsertParagraph($"{DataReturner(ДатаЗаказа.Day, ДатаЗаказа.Month, ДатаЗаказа.Year)}\n").
            Font("Times New Roman").
            FontSize(11).
            Alignment = Alignment.right;

            document.InsertParagraph("Бланк-заказ на установку двери\n\n").
            Font("Times New Roman").
            FontSize(28).
            Bold().
            Alignment = Alignment.center;

            document.InsertParagraph
                ("      \"ООО Наши Двери\" именуемое в дальнейшем Исполнитель, в лице менеджера по продажам " +
                $"\"Ирина М.\" и директора компании Никита К. с одной стороны, и {Заказчик_ФИО} " +
                $"именуемое в дальнейшем Заказчик с другой стороны, заключили настоящий договор " +
                $"о нижеследующем." +
                $"\n\n" +
                $"1. Согласно настоящему договору Исполнитель обязуется по заданию Заказчика оказать следующие услуги: ").
            Font("Times New Roman").
            FontSize(12);

            #region СписокТребований
            List СписокТребований = document.AddList();
            document.AddListItem(СписокТребований, $" выполнить изготовление двери(-ей), в количестве: {Количество} экземпляр(-ов)", 1, ListItemType.Numbered);

            if (ustanovka)
            {
                document.AddListItem(СписокТребований, " выполнить установку двери(-ей)", 1, ListItemType.Numbered);
            }

            if (nalichniki)
            {
                document.AddListItem(СписокТребований, " выполнить установку наличников", 1, ListItemType.Numbered);
            }

            if (zamok)
            {
                document.AddListItem(СписокТребований, " выполнить установку замка(-ов) в дверь(-и)", 1, ListItemType.Numbered);
            }

            if (ruchka)
            {
                document.AddListItem(СписокТребований, " выполнить установку ручки (ручек) в дверь(-и)", 1, ListItemType.Numbered);
            }

            if (petli)
            {
                document.AddListItem(СписокТребований, " выполнить установку петель", 1, ListItemType.Numbered);
            }

            document.InsertList(СписокТребований, new Font("Times New Roman"), 12);
            #endregion

            document.InsertParagraph("В свою очередь Заказчик обязуется оплатить эти услуги.\n")
            .Font("Times New Roman")
            .FontSize(12);
            #region Калькулирование Стоимости

            int[]         mass        = new int[5];
            List <double> ЦенаПрофиля = new List <double>();

            #region Запросы к БД
            SqlConnection Connection = new SqlConnection(ConnectionString);
            try
            {
                Connection.Open();
            }
            catch (SqlException)
            {
                MessageBox.Show("Проверьте, достаточно ли места на диске, достаточно ли прав у учетной записи для операций с БД (См. справку), файлы MDF и LDF не должны быть помечены \"Только для чтения\". \n\nВозможно стоит попробовать отключить БД и запустить программу еще раз.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            SqlCommand    comm1    = new SqlCommand("SELECT cena_ustanovki FROM Dopolnitelno", Connection);
            SqlDataReader myReader = comm1.ExecuteReader(CommandBehavior.CloseConnection);
            while (myReader.Read())
            {
                mass[0] = Convert.ToInt32(myReader[0]);
            }
            Connection.Close();
            try
            {
                Connection.Open();
            }
            catch (SqlException)
            {
                MessageBox.Show("Проверьте, достаточно ли места на диске, достаточно ли прав у учетной записи для операций с БД (См. справку), файлы MDF и LDF не должны быть помечены \"Только для чтения\". \n\nВозможно стоит попробовать отключить БД и запустить программу еще раз.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            SqlCommand    comm2     = new SqlCommand("SELECT cena_nalichniki FROM Dopolnitelno", Connection);
            SqlDataReader myReader2 = comm2.ExecuteReader(CommandBehavior.CloseConnection);
            while (myReader2.Read())
            {
                mass[1] = Convert.ToInt32(myReader2[0]);
            }
            Connection.Close();
            try
            {
                Connection.Open();
            }
            catch (SqlException)
            {
                MessageBox.Show("Проверьте, достаточно ли места на диске, достаточно ли прав у учетной записи для операций с БД (См. справку), файлы MDF и LDF не должны быть помечены \"Только для чтения\". \n\nВозможно стоит попробовать отключить БД и запустить программу еще раз.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            SqlCommand    comm3     = new SqlCommand("SELECT cena_zamki FROM Dopolnitelno", Connection);
            SqlDataReader myReader3 = comm3.ExecuteReader(CommandBehavior.CloseConnection);
            while (myReader3.Read())
            {
                mass[2] = Convert.ToInt32(myReader3[0]);
            }
            Connection.Close();
            try
            {
                Connection.Open();
            }
            catch (SqlException)
            {
                MessageBox.Show("Проверьте, достаточно ли места на диске, достаточно ли прав у учетной записи для операций с БД (См. справку), файлы MDF и LDF не должны быть помечены \"Только для чтения\". \n\nВозможно стоит попробовать отключить БД и запустить программу еще раз.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            SqlCommand    comm4     = new SqlCommand("SELECT cena_ruchka FROM Dopolnitelno", Connection);
            SqlDataReader myReader4 = comm4.ExecuteReader(CommandBehavior.CloseConnection);
            while (myReader4.Read())
            {
                mass[3] = Convert.ToInt32(myReader4[0]);
            }
            Connection.Close();
            try
            {
                Connection.Open();
            }
            catch (SqlException)
            {
                MessageBox.Show("Проверьте, достаточно ли места на диске, достаточно ли прав у учетной записи для операций с БД (См. справку), файлы MDF и LDF не должны быть помечены \"Только для чтения\". \n\nВозможно стоит попробовать отключить БД и запустить программу еще раз.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            SqlCommand    comm5     = new SqlCommand("SELECT cena_petli FROM Dopolnitelno", Connection);
            SqlDataReader myReader5 = comm5.ExecuteReader(CommandBehavior.CloseConnection);
            while (myReader5.Read())
            {
                mass[4] = Convert.ToInt32(myReader5[0]);
            }
            Connection.Close();
            try
            {
                Connection.Open();
            }
            catch (SqlException)
            {
                MessageBox.Show("Проверьте, достаточно ли места на диске, достаточно ли прав у учетной записи для операций с БД (См. справку), файлы MDF и LDF не должны быть помечены \"Только для чтения\". \n\nВозможно стоит попробовать отключить БД и запустить программу еще раз.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            SqlCommand    comm6     = new SqlCommand("SELECT cena FROM Profili", Connection);
            SqlDataReader myReader6 = comm6.ExecuteReader(CommandBehavior.CloseConnection);
            while (myReader6.Read())
            {
                ЦенаПрофиля.Add(Math.Round(Convert.ToDouble(myReader6[0]), 4));
            }
            Connection.Close();

            #endregion

            double sum = ЦенаПрофиля[id_Профиля] * Высота * Ширина * Количество +
                         mass[0] * Convert.ToInt32(ustanovka) +
                         mass[1] * Convert.ToInt32(nalichniki) +
                         mass[2] * Convert.ToInt32(zamok) +
                         mass[3] * Convert.ToInt32(ruchka) +
                         mass[4] * Convert.ToInt32(petli);

            #endregion

            document.InsertParagraph($"2. Стоимость оказываемых услуг составляет: {sum} бел.руб.")
            .Font("Times New Roman")
            .FontSize(12)
            .Alignment = Alignment.both;

            document.InsertParagraph($"3. Услуги оплачиваются в течении четырнадцати календарных дней с момента заключения договора.")
            .Font("Times New Roman")
            .FontSize(12)
            .Alignment = Alignment.both;

            document.InsertParagraph($"4. В случае невозможности исполнения, возникшей по вине Заказчика, услуги подлежат оплате в полном объеме.")
            .Font("Times New Roman")
            .FontSize(12)
            .Alignment = Alignment.both;

            document.InsertParagraph($"5. В случае, когда невозможность исполнения возникла по обстоятельствам, за которые ни одна из сторон не отвечает, Заказчик возмещает Исполнителю фактически понесенные им расходы.")
            .Font("Times New Roman")
            .FontSize(12)
            .Alignment = Alignment.both;

            document.InsertParagraph($"6. Заказчик вправе отказаться от исполнения настоящего договора при условии оплаты Исполнителю фактически понесенных им расходов.")
            .Font("Times New Roman")
            .FontSize(12)
            .Alignment = Alignment.both;

            document.InsertParagraph($"7. Исполнитель вправе отказаться от исполнения настоящего договора при условии полного возмещения Заказчику убытков.")
            .Font("Times New Roman")
            .FontSize(12)
            .Alignment = Alignment.both;

            document.InsertParagraph($"8. К настоящему договору применяются общие положения о подряде (статьи 656 - 682 ГК РБ ) и положения о бытовом подряде (статьи 683 - 695 ГК РБ), если это не противоречит статьям 733 - 737 ГК, регулирующим вопросы возмездного оказания услуг.")
            .Font("Times New Roman")
            .FontSize(12)
            .Alignment = Alignment.both;

            document.InsertParagraph($"9. Срок действия настоящего договора:")
            .Font("Times New Roman")
            .FontSize(12)
            .Alignment = Alignment.both;

            #region Подсчет и увеличение срока заказа
            DateTime IncreasedDateOfOrdering = DateTime.Parse($"{ ДатаЗаказа.Day}.{ ДатаЗаказа.Month}.{ ДатаЗаказа.Year}");
            IncreasedDateOfOrdering = IncreasedDateOfOrdering.AddDays(14);
            #endregion

            document.InsertParagraph($"Начало: {DataReturner(ДатаЗаказа.Day, ДатаЗаказа.Month, ДатаЗаказа.Year)}\n" +
                                     $"Конец: {DataReturner(IncreasedDateOfOrdering.Day, IncreasedDateOfOrdering.Month, IncreasedDateOfOrdering.Year)}")
            .Font("Times New Roman")
            .FontSize(12);

            document.InsertParagraph
                ("11. Договор составлен в 2-х экземплярах, по одному для каждой из сторон.")
            .Font("Times New Roman")
            .FontSize(12)
            .Alignment = Alignment.both;

            document.InsertParagraph
                ("12.Адреса и банковские реквизиты сторон:\n\n" +
                $"Заказчик:_________________________________________________________________________________________________________________________________________________________________________. Контактный телефон: +375({Заказчик_ТелефонныйПрефикс}){Заказчик_Телефон}\n\n" +
                "Исполнитель: \"ООО Наши Двери\", ул. Неизвестная 16, г.Минск. \n*Какие-то банковские реквизиты здесь*.\n\n\n")
            .Font("Times New Roman")
            .FontSize(12);

            document.InsertParagraph($"Подпись Заказчика: ____________________\n")
            .Font("Times New Roman")
            .FontSize(12);

            document.InsertParagraph($"Подпись Исполнителя: ____________________")
            .Font("Times New Roman")
            .FontSize(12);

            document.Save();
        }
Exemplo n.º 30
0
        private void StartTest_Copy_Click(object sender, RoutedEventArgs e)
        {
            string pathDocument = AppDomain.CurrentDomain.BaseDirectory + "Отчет " + FIOLABEL.Content + ".docx";

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


            Xceed.Document.NET.Paragraph paragraph = document.InsertParagraph();
            // выравниваем параграф по правой стороне
            paragraph.Alignment = Alignment.center;

            // добавляем отдельную строку со своим форматированием
            paragraph.AppendLine("Служба персонала").Bold().Font("Times New Roman").FontSize(14);
            paragraph.AppendLine("ООО \"Эрнис\"").Bold().Font("Times New Roman").FontSize(14);
            paragraph.AppendLine("ПРОТОКОЛ ТЕСТИРОВАНИЯ").Bold().Font("Times New Roman").FontSize(14);
            Xceed.Document.NET.Paragraph paragraph2 = document.InsertParagraph();
            paragraph2.Font("Times New Roman");
            paragraph2.FontSize(14);
            paragraph2.Alignment = Alignment.left;
            paragraph2.AppendLine("Фамилия: " + _loginPage.SerName.Text).Font("Times New Roman").FontSize(14);
            paragraph2.AppendLine("Имя: " + _loginPage.Name.Text).Font("Times New Roman").FontSize(14);
            paragraph2.AppendLine("Отчество: " + _loginPage.ser2.Text).Font("Times New Roman").FontSize(14);
            paragraph2.AppendLine();
            paragraph2.AppendLine("Всего вопросов: " + scrambled.Count()).Font("Times New Roman").FontSize(14);
            paragraph2.AppendLine("Правильных ответов: " + rightanswes + " (" + (Math.Truncate((double)rightanswes * 100 / (double)scrambled.Count())) + "%)").Font("Times New Roman").FontSize(14);
            Xceed.Document.NET.Paragraph paragraph3 = document.InsertParagraph().Font("Times New Roman").FontSize(14);
            paragraph3.Alignment = Alignment.right;
            paragraph3.Font("Times New Roman");
            paragraph3.FontSize(14);
            paragraph3.AppendLine();
            DateTime time = DateTime.Today;

            if (time.Month < 10)
            {
                paragraph3.AppendLine("Дата: " + time.Day + ".0" + time.Month + "." + time.Year).Font("Times New Roman").FontSize(14);
            }
            else
            {
                paragraph3.AppendLine("Дата: " + time.Day + "." + time.Month + "." + time.Year).Font("Times New Roman").FontSize(14);
            }
            paragraph3.AppendLine("ФИО контролирующего:___________________________________").Font("Times New Roman").FontSize(14);
            paragraph3.AppendLine("Подпись тестируемого:__________________________________").Font("Times New Roman").FontSize(14);
            paragraph3.InsertPageBreakAfterSelf();
            document.InsertSectionPageBreak();
            Xceed.Document.NET.Paragraph paragraph4 = document.InsertParagraph();

            paragraph4.Alignment = Alignment.left;

            paragraph4.AppendLine("Неверные ответы:").Font("Times New Roman").FontSize(14).Alignment = Alignment.center;
            paragraph4.AppendLine().Alignment = Alignment.left;;
            foreach (FailedQuestion failed in otchet)
            {
                paragraph4.AppendLine(failed.text).Font("Times New Roman").FontSize(14);
                paragraph4.AppendLine("Ответ тестируемого:").Font("Times New Roman").FontSize(14);
                foreach (Answer answer in failed.FailedAnswers)
                {
                    paragraph4.AppendLine("-" + answer.text).Font("Times New Roman").FontSize(14);
                }
                paragraph4.AppendLine("Правильный ответ:").Font("Times New Roman").FontSize(14);
                foreach (Answer answer in failed.CorrectAnswers)
                {
                    paragraph4.AppendLine("-" + answer.text).Font("Times New Roman").FontSize(14);
                }
                paragraph4.AppendLine();
            }

            paragraph4.AppendLine("Верные ответы:").Font("Times New Roman").FontSize(14).Alignment = Alignment.center;;
            paragraph4.AppendLine().Alignment = Alignment.left;;
            foreach (Question failed in otchet2)
            {
                paragraph4.AppendLine(failed.text).Font("Times New Roman").FontSize(14);
                paragraph4.AppendLine("Ответ тестируемого:").Font("Times New Roman").FontSize(14);
                foreach (Answer answer in failed.answers.Where(x => x.right == true))
                {
                    paragraph4.AppendLine("-" + answer.text).Font("Times New Roman").FontSize(14);
                }
                paragraph4.AppendLine();
            }



            // сохраняем документ
            document.Save();
            Process.Start(AppDomain.CurrentDomain.BaseDirectory + "Отчет " + FIOLABEL.Content + ".docx");
        }
Exemplo n.º 31
0
        public NewBlank
        (
            System.Windows.Forms.DataVisualization.Charting.Chart chartСпросЗаКвартал,
            System.Windows.Forms.DataVisualization.Charting.Chart chartСпросЗаМесяц
        )
        {
            string ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=" + Application.StartupPath + @"\Resources\doors.mdf;Integrated Security=True;Connect Timeout=30";

            Directory.CreateDirectory(Environment.CurrentDirectory + $@"\Отчеты по продажам\{DateTime.Now.Year}\{НазваниеМесяца(DateTime.Now.Month, true)}\");
            string        path       = Environment.CurrentDirectory + $@"\Отчеты по продажам\{DateTime.Now.Year}\{НазваниеМесяца(DateTime.Now.Month, true)}\Отчет по продажам и предыдущий квартал ({НазваниеМесяца(DateTime.Now.Month, true)} {DateTime.Now.Year}).docx";
            SqlConnection Connection = new SqlConnection(ConnectionString);

            DocX document = DocX.Create(path);

            document.MarginTop    = 30;
            document.MarginLeft   = 30;
            document.MarginRight  = 30;
            document.MarginBottom = 30;

            document.InsertParagraph($"Дата составления: {DataReturner(DateTime.Now.Day, DateTime.Now.Month, DateTime.Now.Year)}\n").
            Font("Times New Roman").
            FontSize(11).
            Alignment = Alignment.right;

            document.InsertParagraph("Отчет о продажах за текущий месяц и предыдущий квартал\n\n").
            Font("Times New Roman").
            FontSize(28).
            Bold().
            Alignment = Alignment.center;

            document.InsertParagraph("На приведенном ниже графике отображен график спроса дверей за месяц:\n")
            .Font("Times New Roman")
            .FontSize(12)
            .Alignment = Alignment.left;

            #region Составление и заполнение графиков продаж за месяц

            PieChart WordChart_СпросЗаМесяц = new PieChart();
            WordChart_СпросЗаМесяц.AddLegend(ChartLegendPosition.Right, false);

            try
            {
                Connection.Open();
            }
            catch (SqlException)
            {
                MessageBox.Show("Проверьте, достаточно ли места на диске, достаточно ли прав у учетной записи для операций с БД (См. справку), файлы MDF и LDF не должны быть помечены \"Только для чтения\". \n\nВозможно стоит попробовать отключить БД и запустить программу еще раз.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            SqlCommand comm     = new SqlCommand("SELECT count(id_profil) FROM Profili", Connection);
            object     езультат = comm.ExecuteScalar();

            if (езультат != null)
            {
                int Количество_профилей = (int)езультат;

                List <string> Name   = new List <string>();
                List <int>    Value  = new List <int>();
                Series        series = new Series("Спрос товара за месяц, группировка по профилю");

                for (int i = 0; i < Количество_профилей; i++)
                {
                    comm = new SqlCommand($"SELECT profil FROM Profili where id_profil={i + 1}", Connection);
                    string НазваниеПрофиля = (string)comm.ExecuteScalar();
                    comm     = new SqlCommand($"select kolvo from Zakazy where id_profil = {i + 1} and data between '{DateTime.Now.Year}/{DateTime.Now.Month}/01' and '{DateTime.Now.Year}/{DateTime.Now.Month}/{DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month)}'", Connection);
                    езультат = comm.ExecuteScalar();
                    if (езультат != null)
                    {
                        Name.Add($"{НазваниеПрофиля} ({(int)Результат})");
                        Value.Add((int)езультат);
                    }
                }
                series.Bind(Name, Value);
                WordChart_СпросЗаМесяц.AddSeries(series);
            }
            Connection.Close();
            document.InsertChart(WordChart_СпросЗаМесяц);
            #endregion

            document.InsertParagraph("\n\nА также диаграмма продаж за предыдущий квартал. Она предоставлена ниже:\n")
            .Font("Times New Roman")
            .FontSize(12)
            .Alignment = Alignment.left;

            #region Составление и заполнение графиков продаж за предыдущий квартал

            BarChart WordChart_СпросЗаКвартал = new BarChart();
            WordChart_СпросЗаКвартал.AddLegend(ChartLegendPosition.Right, false);
            WordChart_СпросЗаКвартал.BarDirection = BarDirection.Column;
            WordChart_СпросЗаКвартал.BarGrouping  = BarGrouping.Clustered;
            WordChart_СпросЗаКвартал.GapWidth     = 200;

            try
            {
                Connection.Open();
            }
            catch (SqlException)
            {
                MessageBox.Show("Проверьте, достаточно ли места на диске, достаточно ли прав у учетной записи для операций с БД (См. справку), файлы MDF и LDF не должны быть помечены \"Только для чтения\". \n\nВозможно стоит попробовать отключить БД и запустить программу еще раз.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            comm     = new SqlCommand("SELECT count(id_profil) FROM Profili", Connection);
            езультат = comm.ExecuteScalar();

            if (езультат != null)
            {
                List <string> Name  = new List <string>();
                List <int>    Value = new List <int>();

                switch (Statistics.КакойКварталОтобразить())
                {
                case 1:
                {
                    comm = new SqlCommand($"SELECT sum(kolvo) FROM Zakazy where data between " +
                                          $"'{DateTime.Now.Year - 1}/10/01' and " +
                                          $"'{DateTime.Now.Year - 1}/10/{DateTime.DaysInMonth(DateTime.Now.Year - 1, 10)}'", Connection);
                    езультат = comm.ExecuteScalar();
                    if (езультат != null)
                    {
                        Name.Add($"Октябрь ({DateTime.Now.Year - 1}) ({(int)Результат})");
                        Value.Add((int)езультат);
                    }
                    else
                    {
                        Name.Add($"Октябрь ({DateTime.Now.Year - 1}) (0)");
                        Value.Add(0);
                    }


                    comm = new SqlCommand($"SELECT sum(kolvo) FROM Zakazy where data between " +
                                          $"'{DateTime.Now.Year - 1}/11/01' and " +
                                          $"'{DateTime.Now.Year - 1}/11/{DateTime.DaysInMonth(DateTime.Now.Year - 1, 11)}'", Connection);
                    езультат = comm.ExecuteScalar();
                    if (езультат != null)
                    {
                        Name.Add($"Ноябрь ({DateTime.Now.Year - 1}) ({(int)Результат})");
                        Value.Add((int)езультат);
                    }
                    else
                    {
                        Name.Add($"Ноябрь ({DateTime.Now.Year - 1}) (0)");
                        Value.Add(0);
                    }

                    comm = new SqlCommand($"SELECT sum(kolvo) FROM Zakazy where data between " +
                                          $"'{DateTime.Now.Year - 1}/12/01' and " +
                                          $"'{DateTime.Now.Year - 1}/12/{DateTime.DaysInMonth(DateTime.Now.Year - 1, 12)}'", Connection);
                    езультат = comm.ExecuteScalar();
                    if (езультат != null)
                    {
                        Name.Add($"Декабрь ({DateTime.Now.Year - 1}) ({(int)Результат})");
                        Value.Add((int)езультат);
                    }
                    else
                    {
                        Name.Add($"Декабрь ({DateTime.Now.Year - 1}) (0)");
                        Value.Add(0);
                    }
                }
                break;

                case 2:
                {
                    comm = new SqlCommand($"SELECT sum(kolvo) FROM Zakazy where data between " +
                                          $"'{DateTime.Now.Year}/01/01' and " +
                                          $"'{DateTime.Now.Year}/01/{DateTime.DaysInMonth(DateTime.Now.Year, 01)}'", Connection);
                    езультат = comm.ExecuteScalar();
                    if (езультат != null)
                    {
                        Name.Add($"Январь ({(int)Результат})");
                        Value.Add((int)езультат);
                    }
                    else
                    {
                        Name.Add($"Январь (0)");
                        Value.Add(0);
                    }
                    Name.Add($"Январь");
                    Value.Add((int)comm.ExecuteScalar());

                    comm = new SqlCommand($"SELECT sum(kolvo) FROM Zakazy where data between " +
                                          $"'{DateTime.Now.Year}/02/01' and " +
                                          $"'{DateTime.Now.Year}/02/{DateTime.DaysInMonth(DateTime.Now.Year, 02)}'", Connection);
                    езультат = comm.ExecuteScalar();
                    if (езультат != null)
                    {
                        Name.Add($"Февраль ({(int)Результат})");
                        Value.Add((int)езультат);
                    }
                    else
                    {
                        Name.Add($"Февраль (0)");
                        Value.Add(0);
                    }

                    comm = new SqlCommand($"SELECT sum(kolvo) FROM Zakazy where data between " +
                                          $"'{DateTime.Now.Year}/03/01' and " +
                                          $"'{DateTime.Now.Year}/03/{DateTime.DaysInMonth(DateTime.Now.Year, 03)}'", Connection);
                    езультат = comm.ExecuteScalar();
                    if (езультат != null)
                    {
                        Name.Add($"Март ({(int)Результат})");
                        Value.Add((int)езультат);
                    }
                    else
                    {
                        Name.Add($"Март (0)");
                        Value.Add(0);
                    }
                }
                break;

                case 3:
                {
                    comm = new SqlCommand($"SELECT sum(kolvo) FROM Zakazy where data between " +
                                          $"'{DateTime.Now.Year}/04/01' and " +
                                          $"'{DateTime.Now.Year}/04/{DateTime.DaysInMonth(DateTime.Now.Year, 04)}'", Connection);
                    езультат = comm.ExecuteScalar();
                    if (езультат != null)
                    {
                        Name.Add($"Апрель ({(int)Результат})");
                        Value.Add((int)езультат);
                    }
                    else
                    {
                        Name.Add($"Апрель (0)");
                        Value.Add(0);
                    }

                    comm = new SqlCommand($"SELECT sum(kolvo) FROM Zakazy where data between " +
                                          $"'{DateTime.Now.Year}/05/01' and " +
                                          $"'{DateTime.Now.Year}/05/{DateTime.DaysInMonth(DateTime.Now.Year, 05)}'", Connection);
                    езультат = comm.ExecuteScalar();
                    if (езультат != null)
                    {
                        Name.Add($"Май ({(int)Результат})");
                        Value.Add((int)езультат);
                    }
                    else
                    {
                        Name.Add($"Май (0)");
                        Value.Add(0);
                    }

                    comm = new SqlCommand($"SELECT sum(kolvo) FROM Zakazy where data between " +
                                          $"'{DateTime.Now.Year}/06/01' and " +
                                          $"'{DateTime.Now.Year}/06/{DateTime.DaysInMonth(DateTime.Now.Year, 06)}'", Connection);
                    езультат = comm.ExecuteScalar();
                    if (езультат != null)
                    {
                        Name.Add($"Июнь ({(int)Результат})");
                        Value.Add((int)езультат);
                    }
                    else
                    {
                        Name.Add($"Июнь (0)");
                        Value.Add(0);
                    }
                }
                break;

                case 4:
                {
                    comm = new SqlCommand($"SELECT sum(kolvo) FROM Zakazy where data between " +
                                          $"'{DateTime.Now.Year}/07/01' and " +
                                          $"'{DateTime.Now.Year}/07/{DateTime.DaysInMonth(DateTime.Now.Year, 07)}'", Connection);
                    езультат = comm.ExecuteScalar();
                    if (езультат != null)
                    {
                        Name.Add($"Июль ({(int)Результат})");
                        Value.Add((int)езультат);
                    }
                    else
                    {
                        Name.Add($"Июль (0)");
                        Value.Add(0);
                    }

                    comm = new SqlCommand($"SELECT sum(kolvo) FROM Zakazy where data between " +
                                          $"'{DateTime.Now.Year}/08/01' and " +
                                          $"'{DateTime.Now.Year}/08/{DateTime.DaysInMonth(DateTime.Now.Year, 08)}'", Connection);
                    езультат = comm.ExecuteScalar();
                    if (езультат != null)
                    {
                        Name.Add($"Август ({(int)Результат})");
                        Value.Add((int)езультат);
                    }
                    else
                    {
                        Name.Add($"Август (0)");
                        Value.Add(0);
                    }

                    comm = new SqlCommand($"SELECT sum(kolvo) FROM Zakazy where data between " +
                                          $"'{DateTime.Now.Year}/09/01' and " +
                                          $"'{DateTime.Now.Year}/09/{DateTime.DaysInMonth(DateTime.Now.Year, 09)}'", Connection);
                    езультат = comm.ExecuteScalar();
                    if (езультат != null)
                    {
                        Name.Add($"Сентябрь ({(int)Результат})");
                        Value.Add((int)езультат);
                    }
                    else
                    {
                        Name.Add($"Сентябрь (0)");
                        Value.Add(0);
                    }
                }
                break;
                }

                var series = new Series("Статистика проданных дверей за квартал");
                series.Bind(Name, Value);
                WordChart_СпросЗаКвартал.AddSeries(series);
            }
            Connection.Close();
            document.InsertChart(WordChart_СпросЗаКвартал);

            #endregion

            try
            {
                document.Save();
            }
            catch (IOException)
            {
                MessageBox.Show($"Ошибка при сохранении. \n\nНе удалось записать в файл. Убедитесь что требуемый файл ({path}) закрыт. \n\nИгнорируйте следующее сообщение");
            }
            MessageBox.Show($"Отчет создан. Он находится в директории: \"{path}\".");
        }
Exemplo n.º 32
0
        private async void Button3_Click(object sender, EventArgs e)
        {
            OleDbCommand command1 = new OleDbCommand("SELECT * FROM [Клиенты]", SqlConnection);

            OleDbDataReader sqlReader1 = null;

            sqlReader1 = command1.ExecuteReader();

            while (await sqlReader1.ReadAsync())
            {
                if (Convert.ToString(sqlReader1["E-mail"]) == Convert.ToString(this.Tag))
                {
                    if (Convert.ToString(sqlReader1["Статус"]) == "Завершен")
                    {
                        SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                        if (saveFileDialog1.ShowDialog() == DialogResult.Cancel)
                        {
                            return;
                        }

                        string filename     = saveFileDialog1.FileName;
                        string pathDocument = filename + ".docx";
                        DocX   document     = DocX.Create(pathDocument);

                        document.InsertParagraph("История клиента " + Convert.ToString(sqlReader1["ФИО"])).
                        FontSize(24).
                        Bold().
                        Alignment = Alignment.center;

                        Paragraph paragraph = document.InsertParagraph();
                        paragraph.Alignment = Alignment.right;

                        SqlConnection = new OleDbConnection(connectString);
                        await SqlConnection.OpenAsync();

                        OleDbDataReader sqlReader = null;

                        OleDbCommand command = new OleDbCommand("SELECT * FROM [Клиенты]", SqlConnection);

                        sqlReader = command.ExecuteReader();

                        int for_for = 0;

                        try
                        {
                            while (await sqlReader.ReadAsync())
                            {
                                if (comboBox5.Items[for_for].ToString() == Convert.ToString(sqlReader["Тема"]))
                                {
                                    document.InsertParagraph("Дата: " + Convert.ToString(sqlReader["Дата"]));
                                    document.InsertParagraph("Телефон: " + Convert.ToString(sqlReader["Телефон"]));
                                    document.InsertParagraph("E-mail: " + Convert.ToString(sqlReader["E-mail"]));
                                    document.InsertParagraph("Текст: " + Convert.ToString(sqlReader["Текст"]));
                                    document.InsertParagraph("Ответ: " + Convert.ToString(sqlReader["Ответ"]));
                                    document.InsertParagraph("");
                                    for_for++;
                                }
                            }

                            document.Save();

                            return;
                        }
                        catch
                        {
                            document.Save();
                        }
                    }
                }
            }
        }
Exemplo n.º 33
0
        /// <summary>
        /// Add three different types of headers and footers to a document.
        /// </summary>
        public static void HeadersFooters()
        {
            Console.WriteLine("\tHeadersFooters()");

            // Create a document.
            using (DocX document = DocX.Create(HeaderFooterSample.HeaderFooterSampleOutputDirectory + @"HeadersFooters.docx"))
            {
                // Insert a Paragraph in the first page of the document.
                var p1 = document.InsertParagraph("This is the ").Append("first").Bold().Append(" page Content.");
                p1.SpacingBefore(70d);
                p1.InsertPageBreakAfterSelf();

                // Insert a Paragraph in the second page of the document.
                var p2 = document.InsertParagraph("This is the ").Append("second").Bold().Append(" page Content.");
                p2.InsertPageBreakAfterSelf();

                // Insert a Paragraph in the third page of the document.
                var p3 = document.InsertParagraph("This is the ").Append("third").Bold().Append(" page Content.");
                p3.InsertPageBreakAfterSelf();

                // Insert a Paragraph in the third page of the document.
                var p4 = document.InsertParagraph("This is the ").Append("fourth").Bold().Append(" page Content.");

                // Add Headers and Footers to the document.
                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.Headers.First.InsertParagraph("This is the ").Append("first").Bold().Append(" page header");

                // Insert a Paragraph into the first Footer.
                document.Footers.First.InsertParagraph("This is the ").Append("first").Bold().Append(" page footer");

                // Insert a Paragraph into the even Header.
                document.Headers.Even.InsertParagraph("This is an ").Append("even").Bold().Append(" page header");

                // Insert a Paragraph into the even Footer.
                document.Footers.Even.InsertParagraph("This is an ").Append("even").Bold().Append(" page footer");

                // Insert a Paragraph into the odd Header.
                document.Headers.Odd.InsertParagraph("This is an ").Append("odd").Bold().Append(" page header");

                // Insert a Paragraph into the odd Footer.
                document.Footers.Odd.InsertParagraph("This is an ").Append("odd").Bold().Append(" page footer");

                // Add the page number in the first Footer.
                document.Footers.First.InsertParagraph("Page #").AppendPageNumber(PageNumberFormat.normal);

                // Add the page number in the even Footers.
                document.Footers.Even.InsertParagraph("Page #").AppendPageNumber(PageNumberFormat.normal);

                // Add the page number in the odd Footers.
                document.Footers.Odd.InsertParagraph("Page #").AppendPageNumber(PageNumberFormat.normal);

                document.Save();
                Console.WriteLine("\tCreated: HeadersFooters.docx\n");
            }
        }
Exemplo n.º 34
0
        public void GenerateDoc(string filePath)
        {
            if (string.IsNullOrWhiteSpace(filePath))
            {
                return;
            }

            DocX doc = DocX.Load("Template/template.docx");

            Paragraph cubicleAddress = doc.InsertParagraph();

            cubicleAddress.Alignment = Alignment.left;

            cubicleAddress.AppendLine();
            cubicleAddress.AppendLine();
            cubicleAddress.AppendLine();

            cubicleAddress.Append(_dataModel.AddressLine).Font(CalibriFont).FontSize(9);
            cubicleAddress.AppendLine();

            var phoneString = $"Phone {_dataModel.Phone}";

            cubicleAddress.Append(phoneString).Font(CalibriFont).FontSize(9);

            Table faxAndInvoiceInfo = doc.AddTable(2, 2);

            faxAndInvoiceInfo.SetWidthsPercentage(new float[] { 50, 50 }, null);

            var faxString = $"Fax {_dataModel.Fax}";

            faxAndInvoiceInfo.Rows[0].Cells[0].Paragraphs.FirstOrDefault().Append(faxString)
            .Font(CalibriFont).FontSize(9).Alignment = Alignment.left;

            var invoiceString = $"INVOICE # { _dataModel.InvoiceId}";

            faxAndInvoiceInfo.Rows[0].Cells[1].Paragraphs.FirstOrDefault().Append(invoiceString)
            .Font(CalibriFont).FontSize(8).Alignment = Alignment.right;

            var dateString = $"DATE: {_dataModel.InvoiceDate.ToShortDateString()}";

            faxAndInvoiceInfo.Rows[1].Cells[1].Paragraphs.FirstOrDefault().Append(dateString)
            .Font(CalibriFont).FontSize(8).Alignment = Alignment.right;

            cubicleAddress.InsertTableAfterSelf(faxAndInvoiceInfo);

            Paragraph emptyParagraph = doc.InsertParagraph();

            emptyParagraph.AppendLine();
            emptyParagraph.AppendLine();
            emptyParagraph.AppendLine();

            Paragraph forParagraph = doc.InsertParagraph();

            forParagraph.Alignment = Alignment.center;

            forParagraph.Append($"FOR: {_dataModel.PersonalName}").Font(CalibriFont).FontSize(11).Bold();

            Table businessNameTable = doc.AddTable(6, 2);

            businessNameTable.SetWidthsPercentage(new float[] { 45.5f, 54.5f }, null);

            businessNameTable.Rows[0].Cells[0].Paragraphs.FirstOrDefault().Append("TO:")
            .Font(CalibriFont).FontSize(8).Bold().Alignment = Alignment.left;
            businessNameTable.Rows[0].Cells[1].Paragraphs.FirstOrDefault().Append(_dataModel.BusinessName)
            .Font(CalibriFont).FontSize(11).Bold().Alignment = Alignment.left;

            businessNameTable.Rows[1].Cells[0].Paragraphs.FirstOrDefault().Append(_davinciAddressModel.Name)
            .Font(CalibriFont).FontSize(9).Alignment = Alignment.left;

            businessNameTable.Rows[2].Cells[0].Paragraphs.FirstOrDefault().Append(_davinciAddressModel.AddressLine1)
            .Font(CalibriFont).FontSize(9).Alignment = Alignment.left;

            businessNameTable.Rows[3].Cells[0].Paragraphs.FirstOrDefault().Append(_davinciAddressModel.AddressLine2)
            .Font(CalibriFont).FontSize(9).Alignment = Alignment.left;

            var davinciPhone = $"Phone: {_davinciAddressModel.Phone}";

            businessNameTable.Rows[4].Cells[0].Paragraphs.FirstOrDefault().Append(davinciPhone)
            .Font(CalibriFont).FontSize(9).Alignment = Alignment.left;

            var davinciFax = $"Fax: {_davinciAddressModel.Fax}";

            businessNameTable.Rows[5].Cells[0].Paragraphs.FirstOrDefault().Append(davinciFax)
            .Font(CalibriFont).FontSize(9).Alignment = Alignment.left;

            forParagraph.InsertTableAfterSelf(businessNameTable);

            Paragraph emptyParagraph2 = doc.InsertParagraph();

            emptyParagraph2.AppendLine();

            Paragraph actionsParagraph = doc.InsertParagraph();

            Table actionsTable = doc.AddTable(15, 4);

            actionsTable.SetWidthsPercentage(new float[] { 60, 20, 10, 10 }, null);

            // Borders

            for (int i = 0; i < actionsTable.RowCount; i++)
            {
                actionsTable.Rows[i].Height = 18;

                if (actionsTable.RowCount - 1 == i)
                {
                    continue;
                }

                for (int j = 0; j < actionsTable.Rows[i].Cells.Count; j++)
                {
                    actionsTable.Rows[i].Cells[j].SetBorder(TableCellBorderType.Bottom, new Border {
                        Size = BorderSize.one
                    });
                    actionsTable.Rows[i].Cells[j].SetBorder(TableCellBorderType.Left, new Border {
                        Size = BorderSize.one
                    });
                    actionsTable.Rows[i].Cells[j].SetBorder(TableCellBorderType.Right, new Border {
                        Size = BorderSize.one
                    });
                    actionsTable.Rows[i].Cells[j].VerticalAlignment = VerticalAlignment.Center;
                }
            }

            actionsTable.SetBorder(TableBorderType.Top, new Border {
                Size = BorderSize.one
            });

            actionsTable.Rows[0].Cells[0].Paragraphs.FirstOrDefault().Append("DESCRIPTION")
            .Bold().Font(CalibriFont).FontSize(8).Alignment = Alignment.center;

            actionsTable.Rows[0].Cells[1].Paragraphs.FirstOrDefault().Append("DATE")
            .Bold().Font(CalibriFont).FontSize(8).Alignment = Alignment.center;

            actionsTable.Rows[0].Cells[2].Paragraphs.FirstOrDefault().Append("RATE")
            .Bold().Font(CalibriFont).FontSize(8).Alignment = Alignment.center;

            actionsTable.Rows[0].Cells[3].Paragraphs.FirstOrDefault().Append("AMOUNT")
            .Bold().Font(CalibriFont).FontSize(8).Alignment = Alignment.center;

            if (_dataModel.Actions != null && _dataModel.Actions.Count > 0)
            {
                int i = 1;

                foreach (var record in _dataModel.Actions)
                {
                    actionsTable.Rows[i].Cells[0].Paragraphs.FirstOrDefault().Append(record.Description);

                    var formattedDate = $"{record.StartDate.ToShortDateString()} - {record.EndDate.ToShortDateString()}";

                    actionsTable.Rows[i].Cells[1].Paragraphs.FirstOrDefault()
                    .Append(formattedDate).Alignment = Alignment.center;

                    actionsTable.Rows[i].Cells[2].Paragraphs.FirstOrDefault()
                    .Append(record.Rate).Alignment = Alignment.right;

                    actionsTable.Rows[i].Cells[3].Paragraphs.FirstOrDefault()
                    .Append($"{record.AmountSign} {record.Amount.ToString("0.00")}").Alignment = Alignment.right;

                    i++;
                }
            }

            var total = $"{_dataModel.Actions.FirstOrDefault().AmountSign} {_dataModel.Actions.Sum(x => x.Amount).ToString("0.00")}";

            var totalCell = actionsTable.Rows.LastOrDefault().Cells[3];

            var totalWord = actionsTable.Rows.LastOrDefault().Cells[2];

            totalWord.VerticalAlignment = VerticalAlignment.Center;

            totalWord.Paragraphs.FirstOrDefault().Append("TOTAL").Font(CalibriFont).FontSize(8).Alignment = Alignment.right;

            totalCell.VerticalAlignment = VerticalAlignment.Center;

            totalCell.SetBorder(TableCellBorderType.Left, new Border {
                Size = BorderSize.one
            });
            totalCell.SetBorder(TableCellBorderType.Right, new Border {
                Size = BorderSize.one
            });
            totalCell.SetBorder(TableCellBorderType.Bottom, new Border {
                Size = BorderSize.one
            });

            totalCell.Paragraphs.FirstOrDefault().Append(total).Alignment = Alignment.right;

            actionsParagraph.InsertTableAfterSelf(actionsTable);

            Paragraph emptyParagraph3 = doc.InsertParagraph();

            emptyParagraph3.AppendLine();

            Paragraph noteParagraph = doc.InsertParagraph();

            noteParagraph.Append($"NOTES: {_dataModel.Notes}")
            .Font(CalibriFont).FontSize(9).Alignment = Alignment.left;

            noteParagraph.AppendLine();
            noteParagraph.AppendLine();

            Paragraph thankYouParagraph = doc.InsertParagraph();

            thankYouParagraph.AppendLine();

            thankYouParagraph.Append("THANK YOU FOR YOUR BUSINESS!")
            .Font(CalibriFont).FontSize(8).Bold().Alignment = Alignment.center;

            doc.SaveAs(filePath);

            doc.Dispose();
        }
Exemplo n.º 35
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);
            }
        }
Exemplo n.º 36
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");
            }
        }
Exemplo n.º 37
0
            private static void printWhen(DocX document, SpecInfo spec)
            {
                document.InsertParagraph()
                        .Append("When")
                        .Font(new FontFamily("Cambria"))
                        .FontSize(13)
                        .Bold()
                        .Color(Color.FromArgb(255, 79, 129, 189));

                var p = document.InsertParagraph()
                    .Append(spec.HasExecutionBeenTriggered ? string.Format("{0} [{1}]", spec.When.Description, spec.When.Passed ? "Passed" : "Failed") : spec.When.Description)
                        .Color(spec.HasExecutionBeenTriggered ? (spec.When.Passed ? Color.Green : Color.Red) : Color.Black)
                        .FontSize(12);

                if (shouldDisplayWhenException(spec))
                {
                    p.AppendLine(spec.Exception.ToString());
                    p.AppendLine(spec.Exception.StackTrace);
                }

                p.IndentationBefore = 0.5f;
            }