예제 #1
0
        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            string pathDocument = AppDomain.CurrentDomain.BaseDirectory + "Отчет" + ".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);

            Xceed.Document.NET.Paragraph paragraph2 = document.InsertParagraph();
            paragraph2.Font("Times New Roman");
            paragraph2.FontSize(14);
            paragraph2.Alignment = Alignment.left;
            paragraph2.AppendLine("Список товаров: ").Font("Times New Roman").FontSize(14).Bold();
            paragraph2.AppendLine();
            foreach (Product product in config.list.AllProducts)
            {
                paragraph2.AppendLine("Название: " + product.Name).Font("Times New Roman").FontSize(14);
                paragraph2.AppendLine("Описание: " + product.Desc).Font("Times New Roman").FontSize(12);
                paragraph2.AppendLine();
            }
            paragraph2.AppendLine("Список товаров на складе: ").Font("Times New Roman").FontSize(14).Bold();
            paragraph2.AppendLine();
            foreach (StroredProduct product in config.list.AllstroredProducts)
            {
                paragraph2.AppendLine("Название: " + product.product.Name).Font("Times New Roman").FontSize(14);
                paragraph2.AppendLine("Полочка: " + product.polka).Font("Times New Roman").FontSize(12);
                paragraph2.AppendLine("Количество: " + product.count).Font("Times New Roman").FontSize(12);
                paragraph2.AppendLine("Поставщик: " + product.Postavshick.name).Font("Times New Roman").FontSize(12);
                paragraph2.AppendLine();
            }
            paragraph2.AppendLine("Список заказов: ").Font("Times New Roman").FontSize(14).Bold();
            paragraph2.AppendLine();
            foreach (Zakaz product in config.list.AllZakazs)
            {
                paragraph2.AppendLine("Название товара: " + product.stroredProduct.Name).Font("Times New Roman").FontSize(14);
                paragraph2.AppendLine("Поставщик: " + product.postavshick.name).Font("Times New Roman").FontSize(14);
                paragraph2.AppendLine("Информация по данному поставщику: ").Font("Times New Roman").FontSize(14);
                paragraph2.AppendLine("Адрес: " + product.postavshick.adress);
                paragraph2.AppendLine("Телефон: " + product.postavshick.tel);
            }
            document.Save();
            Process.Start(AppDomain.CurrentDomain.BaseDirectory + "Отчет" + ".docx");
        }
예제 #2
0
 public void OpenTask(Exam exam, Ticket ticket, bool markAnswers)
 {
     CloseWord();
     OneAnswerQuestion[] questions = ticket.GetQuestions().Cast <OneAnswerQuestion>().ToArray();
     using (DocX docXdocument = DocX.Create(path.ToString()))
     {
         int i, j;
         docXdocument.AddFooters();
         docXdocument.SetDefaultFont(new Xceed.Document.NET.Font("Times New Roman"));
         Xceed.Document.NET.Paragraph headerParagraph = docXdocument.InsertParagraph();
         Xceed.Document.NET.Paragraph paragraph       = docXdocument.InsertParagraph();
         headerParagraph.Append($"Перегляд завдання")
         .Bold()
         .FontSize(28);
         paragraph.Append($"Завдання білету \"{ticket.TicketName}\":")
         .FontSize(24);
         Xceed.Document.NET.Table table = docXdocument.AddTable(questions.Length, 2);
         table.SetWidthsPercentage(new[] { 50f, 50 }, docXdocument.PageWidth - docXdocument.PageWidth / 5);
         table.SetBorder(TableBorderType.Bottom, new Xceed.Document.NET.Border(BorderStyle.Tcbs_double, BorderSize.two, 0, Color.Black));
         table.SetBorder(TableBorderType.Top, new Xceed.Document.NET.Border(BorderStyle.Tcbs_double, BorderSize.two, 0, Color.Black));
         table.SetBorder(TableBorderType.Left, new Xceed.Document.NET.Border(BorderStyle.Tcbs_double, BorderSize.two, 0, Color.Black));
         table.SetBorder(TableBorderType.Right, new Xceed.Document.NET.Border(BorderStyle.Tcbs_double, BorderSize.two, 0, Color.Black));
         table.SetBorder(TableBorderType.InsideV, new Xceed.Document.NET.Border(BorderStyle.Tcbs_double, BorderSize.two, 0, Color.Black));
         for (i = 0; i < questions.Length; i++)
         {
             table.Rows[i].Cells[0]
             .InsertParagraph()
             .Append($"{questions[i].QuestionNumber + exam.FirstQuestionNumber}) {questions[i].QuestionContent.Text}")
             .FontSize(12);
             Xceed.Document.NET.Paragraph tableParagraph = table.Rows[i].Cells[1].InsertParagraph();
             for (j = 0; j < questions[i].QuestionContent.Answers.Count; j++)
             {
                 Xceed.Document.NET.Paragraph tempParagraph = tableParagraph.Append($"{(j < questions[i].QuestionContent.Letters.Length ? questions[i].QuestionContent.Letters[j].ToString() : "*")}{questions[i].QuestionContent.Devider} { questions[i].QuestionContent.Answers[j]};{Environment.NewLine}");
                 if (markAnswers && questions[i].Answer.Content == questions[i].QuestionContent.Answers[j])
                 {
                     tempParagraph.Bold()
                     .FontSize(12);
                 }
             }
         }
         docXdocument.InsertTable(table);
         docXdocument.Footers.Odd.InsertParagraph()
         .Append("Створено за допомогою SimplEx Program")
         .FontSize(10)
         .UnderlineStyle(UnderlineStyle.singleLine)
         .Alignment = Alignment.right;
         docXdocument.Save();
     }
     OpenWord();
 }
예제 #3
0
        private void ManipulateWord(string dest, string[] paths)
        {
            richTextBox1.Text += "Generating to print file(.doc): " + dest + "... " + "\n";
            var doc = DocX.Create(dest);

            doc.MarginLeft   = 47;
            doc.MarginRight  = 47;
            doc.MarginTop    = 56;
            doc.MarginBottom = 56;
            Xceed.Document.NET.Paragraph par = doc.InsertParagraph();
            int successedCard = 0;

            foreach (string _path in paths)
            {
                try
                {
                    FileInfo fileInfo = new FileInfo(_path);
                    richTextBox1.Text += "Processing card number: " + fileInfo.Name.Replace(".jpg", "") + "... ";

                    string  tempPath = Path.GetTempPath() + fileInfo.Name;
                    Image   img      = doc.AddImage(_path);
                    Picture p        = img.CreatePicture();
                    double  _r       = 37.788578371810449574726609963548;
                    p.Width  = (int)(5.9 * _r);
                    p.Height = (int)(8.6 * _r);
                    //Create a new paragraph
                    par.AppendPicture(p);
                    successedCard++;
                    richTextBox1.Text += "Success!" + "\n";
                }
                catch (Exception ex)
                {
                    richTextBox1.Text += "Fail! " + ex.Message + "\n";
                }
            }

            if (successedCard > 0)
            {
                doc.Save();
                richTextBox1.Text += "Generated print file(.doc): " + dest + "\n";
                if (convertWordToPdf(dest, dest.Replace(".doc", ".pdf")))
                {
                    File.Delete(dest);
                }
            }
        }
예제 #4
0
        }///////////Создание файла и запись информации о клиентах

        private void WriteService(string fileName)
        {
            int checkedRowsCount = 0;

            for (int i = 0; i < data.RowCount; i++)
            {
                if (Convert.ToBoolean(data[checkBoxColumnIndex, i].Value))
                {
                    checkedRowsCount++;
                }
            }
            DocX doc = DocX.Create(fileName);

            Paragraph paragraph = doc.InsertParagraph();

            paragraph.Alignment = Alignment.right;
            paragraph.AppendLine("ElecPair").Font("Arial Black").FontSize(16).UnderlineStyle(UnderlineStyle.singleLine).Highlight(Highlight.magenta);
            paragraph.AppendLine($"(29) 970 - 14 - 80\r\[email protected]").Font("Arial Black").FontSize(12);
            Table table = doc.AddTable(checkedRowsCount + 1, 3);

            table.Design = TableDesign.TableGrid;

            table.Rows[0].Cells[0].Paragraphs[0].Append("Тип оборудования").Font("Arial").Bold();
            table.Rows[0].Cells[1].Paragraphs[0].Append("Вид работ").Font("Arial").Bold();
            table.Rows[0].Cells[2].Paragraphs[0].Append("Стоимость, руб").Font("Arial").Bold();

            int index = 1;

            for (int i = 0; i < checkedRowsCount; i++)
            {
                table.Rows[index].Cells[0].Paragraphs[0].Append(data[1, i].Value.ToString()).Font("Arial");
                table.Rows[index].Cells[1].Paragraphs[0].Append(data[2, i].Value.ToString()).Font("Arial");
                table.Rows[index].Cells[2].Paragraphs[0].Append(data[3, i].Value.ToString()).Font("Arial");

                index++;
            }
            doc.InsertParagraph().InsertTableAfterSelf(table);
            doc.AddProtection(EditRestrictions.readOnly);
            doc.Save();
        }//////////Создание файла и запись информации об услугах
예제 #5
0
        private void WriteClients(string fileName)
        {
            DocX doc = DocX.Create(fileName);

            for (int i = 0; i < data.RowCount; i++)
            {
                if (Convert.ToBoolean(data[checkBoxColumnIndex, i].Value))
                {
                    Paragraph paragraph = doc.InsertParagraph();
                    paragraph.Alignment = Alignment.right;
                    paragraph.AppendLine("ElecPair").Font("Arial Black").FontSize(16).UnderlineStyle(UnderlineStyle.singleLine).Highlight(Highlight.magenta);;
                    paragraph.AppendLine($"(29) 970 - 14 - 80\r\[email protected]").Font("Arial Black").FontSize(12);

                    doc.InsertParagraph($"Клиент: {data[1, i].Value}").Font("Arial Black").FontSize(14);
                    doc.InsertParagraph($"Телефон: {data[2, i].Value}").Font("Arial Black").FontSize(14);

                    doc.InsertParagraph($"Сотрудник: {userFullName}").Font("Arial Black").FontSize(14);

                    doc.InsertParagraph($"Дата принятия в ремонт: {data[3, i].Value}").Font("Arial Black").FontSize(12);

                    Table table = doc.AddTable(4, 2);
                    table.Design = TableDesign.TableGrid;

                    table.Rows[0].Cells[0].Paragraphs[0].Append("Принятое оборудование").Font("Arial").Bold();
                    table.Rows[1].Cells[0].Paragraphs[0].Append("Заявленная неисправность").Font("Arial").Bold();
                    table.Rows[2].Cells[0].Paragraphs[0].Append("Вид работ").Font("Arial").Bold();
                    table.Rows[3].Cells[0].Paragraphs[0].Append("Сумма, руб").Font("Arial").Bold();

                    table.Rows[0].Cells[1].Paragraphs[0].Append(data[5, i].Value.ToString()).Font("Arial");
                    table.Rows[1].Cells[1].Paragraphs[0].Append(data[6, i].Value.ToString()).Font("Arial");
                    table.Rows[2].Cells[1].Paragraphs[0].Append(data[7, i].Value.ToString()).Font("Arial");
                    table.Rows[3].Cells[1].Paragraphs[0].Append(data[8, i].Value.ToString()).Font("Arial");

                    doc.InsertParagraph().InsertTableAfterSelf(table);
                    doc.InsertParagraph($"Дата выдачи: {data[4, i].Value}").Font("Arial Black").FontSize(12);;
                }
            }
            doc.AddProtection(EditRestrictions.readOnly);
            doc.Save();
        }///////////Создание файла и запись информации о клиентах
        //Word Document
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            int    number     = 0;
            int    quantity   = 0;
            double totalPrice = 0;

            using (IndividueelProjectEntities2 ctx = new IndividueelProjectEntities2())
            {
                if (cmbCustomer.SelectedValue != null)
                {
                    var        cus         = ctx.Klants.Select(x => x).Where(x => x.ID == (int)cmbCustomer.SelectedValue).FirstOrDefault();
                    string     fileName    = cus.Voornaam + "_" + cus.Achternaam + "_" + loggedInUser.Username + "_" + DateTime.Now.ToString("dd_MMMM_yyyy");
                    var        doc         = DocX.Create(fileName);
                    string     title       = "Palfi Computer Warehouse";
                    Formatting titleFormat = new Formatting();
                    titleFormat.FontFamily     = new Xceed.Document.NET.Font("Times new roman");
                    titleFormat.Size           = 20D;
                    titleFormat.Position       = 40;
                    titleFormat.FontColor      = System.Drawing.Color.Blue;
                    titleFormat.UnderlineColor = System.Drawing.Color.Black;

                    string CustomerData = $"{cus.Voornaam + "" + cus.Achternaam }" + Environment.NewLine +
                                          cus.Gemeente + " " + cus.Postcode + Environment.NewLine +
                                          cus.Straatnaam + " " + cus.Huisnummer + "/" + cus.Bus + Environment.NewLine +
                                          cus.Emailadres + Environment.NewLine +
                                          cus.Telefoonnummer + Environment.NewLine +
                                          Environment.NewLine;

                    Formatting customerDataFormat = new Formatting();
                    customerDataFormat.FontFamily = new Xceed.Document.NET.Font("Century Gothic");
                    customerDataFormat.Size       = 12D;

                    Xceed.Document.NET.Paragraph paragraphTitel = doc.InsertParagraph(title, false, titleFormat);
                    paragraphTitel.Alignment = Alignment.center;

                    doc.InsertParagraph(CustomerData, false, customerDataFormat);



                    for (int i = 0; i <= myProductinKars.Count(); i++)
                    {
                        number++;
                    }
                    Xceed.Document.NET.Table table = doc.AddTable(number, 4);
                    table.Alignment = Alignment.center;
                    table.Design    = TableDesign.ColorfulList;

                    table.Rows[0].Cells[0].Paragraphs.First().Append("Product");
                    table.Rows[0].Cells[1].Paragraphs.First().Append("Quantity");
                    table.Rows[0].Cells[2].Paragraphs.First().Append("TAX");
                    table.Rows[0].Cells[3].Paragraphs.First().Append("Price");
                    for (int i = 0; i < myProductinKars.Count(); i++)
                    {
                        table.Rows[i + 1].Cells[0].Paragraphs.First().Append(myProductinKars[i].ProductInKarNaam);
                        table.Rows[i + 1].Cells[1].Paragraphs.First().Append(myProductinKars[i].Quantity.ToString() + " " + myProductinKars[i].Unit);
                        table.Rows[i + 1].Cells[2].Paragraphs.First().Append(myProductinKars[i].Btw.ToString() + "%");
                        table.Rows[i + 1].Cells[3].Paragraphs.First().Append((((myProductinKars[i].Price + myProductinKars[i].Margin1) * (1 + myProductinKars[i].Btw / 100)) * myProductinKars[i].Quantity).ToString() + "€");
                    }
                    doc.InsertTable(table);

                    Xceed.Document.NET.Table sum = doc.AddTable(1, 4);
                    sum.Alignment = Alignment.center;
                    sum.Design    = (TableDesign)TableBorderType.Bottom;


                    foreach (var item in myProductinKars)
                    {
                        totalPrice += ((item.Price + item.Margin1) * (1 + item.Btw / 100)) * item.Quantity;
                        quantity   += item.Quantity;
                    }

                    sum.Rows[0].Cells[1].Paragraphs.First().Append("Total  " + quantity.ToString());
                    sum.Rows[0].Cells[2].Paragraphs.First().Append("With TAX");
                    sum.Rows[0].Cells[3].Paragraphs.First().Append("Total price  " + totalPrice.ToString());
                    doc.InsertTable(sum);
                    doc.Save();
                }
            }
        }
        private void createExportDoc()
        {
            try
            {
                DBManager con = new DBManager();

                var modelAnimalpark = con.getAnimalparkList();

                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(modelAnimalpark.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 < modelAnimalpark.Count; i++)
                    {
                        doctable.Rows[i + 1].Cells[0].Paragraphs[0].Append(modelAnimalpark[i].Number).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 < modelAnimalpark.Count; i++)
                        {
                            worKsheeT.Cells[i + 3, 1] = modelAnimalpark[i].Number;
                        }

                        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");
            }
        }
예제 #8
0
        public ActionResult GetDocx()
        {
            try
            {
                using (var ManNac = new EmpleadosEntities())
                {
                    var ListNac = ManNac.Nacionalidad.ToList();

                    //Ubicacion de Archivo
                    string filename = @"C:\Users\Rodrigo_Menares\Downloads\ListaNacionalidades.docx";
                    var    doc      = DocX.Create(filename);

                    //Carga una imagen en formato JPG
                    var image = doc.AddImage(Server.MapPath("/Imagenes/bg.jpg"));
                    // Set Picture Height and Width.
                    var picture = image.CreatePicture(50, 50);
                    picture.Width  = 50;
                    picture.Height = 50;

                    //Titulo Del Documento
                    string title = "Lista De Cargos";

                    //Formato del Titulo
                    Formatting titleFormat = new Formatting();
                    //Specify font family
                    titleFormat.FontFamily = new Xceed.Document.NET.Font("Arial Black");
                    //Specify font size y color del texto
                    titleFormat.Size           = 14D;
                    titleFormat.Position       = 40;
                    titleFormat.FontColor      = System.Drawing.Color.Orange;
                    titleFormat.UnderlineColor = System.Drawing.Color.Gray;
                    titleFormat.Italic         = true;

                    //combina el titulo con el formato definido
                    Xceed.Document.NET.Paragraph paragraphTitle = doc.InsertParagraph(title, false, titleFormat);

                    // alinea el titulo al centro
                    paragraphTitle.Alignment = Alignment.center;

                    //Insert text
                    Table tbl = doc.AddTable(ListNac.Count + 1, 2);

                    //hace que la tabla este al centro de la pagina
                    tbl.Alignment = Alignment.center;
                    tbl.Design    = TableDesign.ColorfulList;

                    //agrega los titulos de la tabla
                    tbl.Rows[0].Cells[0].Paragraphs.First().Append("Código Nacionalidad").FontSize(12D).Alignment = Alignment.center;
                    tbl.Rows[0].Cells[1].Paragraphs.First().Append("Nombre Nacionalidad").FontSize(12D).Alignment = Alignment.center;

                    //llena las celdas con los datos
                    int fila    = 1;
                    int columna = 0;
                    foreach (var item in ListNac)
                    {
                        tbl.Rows[fila].Cells[columna].Paragraphs.First().Append(Convert.ToString(item.Id_Nac)).FontSize(12D).Alignment = Alignment.right;
                        columna++;
                        tbl.Rows[fila].Cells[columna].Paragraphs.First().Append(Convert.ToString(item.Descripcion)).FontSize(12D).Alignment = Alignment.center;
                        fila++;
                        columna = 0;
                    }
                    //inserta la tabla dentro del documento
                    doc.InsertTable(tbl);

                    //Genera el Pie de Pagina del Documento
                    doc.AddFooters();
                    //Indica que que la primera página tendrá pies de página independientes
                    doc.DifferentFirstPage = true;
                    //Indica que que la página par e impar tendrá pies de página separados
                    doc.DifferentOddAndEvenPages = true;
                    Footer    footer_main = doc.Footers.First;
                    Paragraph pFooter     = footer_main.Paragraphs.First();
                    pFooter.Alignment = Alignment.center;
                    pFooter.Append("Página ").Bold();
                    pFooter.AppendPageNumber(PageNumberFormat.normal).Bold();
                    pFooter.Append("/").Bold();
                    pFooter.AppendPageCount(PageNumberFormat.normal).Bold();

                    //graba el documento
                    doc.Save();

                    //abre word y el documento
                    Process.Start("WINWORD", filename);

                    return(RedirectToAction("Index"));
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Error On:", ex);
                Response.StatusCode        = 500;
                Response.StatusDescription = ex.Message;
                return(Json(Response));
            }
        }
예제 #9
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");
        }
예제 #10
0
        public ActionResult CargFamDocx()
        {
            try
            {
                using (CargFam = new EmpleadosEntities())
                {
                    var ListCargFam = CargFam.Sp_Mues_CargFam().ToList();

                    //Ubicacion de Archivo
                    string filename = @"C:\Users\Rodrigo_Menares\Downloads\ListaCargFam.docx";
                    var    doc      = DocX.Create(filename);

                    //cambia la orientacion de la pagina
                    doc.PageLayout.Orientation = Orientation.Landscape;

                    //Carga una imagen en formato JPG
                    var image = doc.AddImage(Server.MapPath("/Imagenes/bg.jpg"));
                    // Set Picture Height and Width.
                    var picture = image.CreatePicture(50, 50);
                    picture.Width  = 50;
                    picture.Height = 50;

                    //Titulo Del Documento
                    string title = "Lista De Cargas Familiares";
                    //Formato del Titulo
                    Formatting titleFormat = new Formatting();
                    //Specify font family
                    titleFormat.FontFamily = new Xceed.Document.NET.Font("Arial Black");
                    //Specify font size y color del texto
                    titleFormat.Size           = 14D;
                    titleFormat.Position       = 40;
                    titleFormat.FontColor      = System.Drawing.Color.Orange;
                    titleFormat.UnderlineColor = System.Drawing.Color.Gray;
                    titleFormat.Italic         = true;

                    //combina el titulo con el formato definido
                    Xceed.Document.NET.Paragraph paragraphTitle = doc.InsertParagraph(title, false, titleFormat);

                    // alinea el titulo al centro
                    paragraphTitle.Alignment = Alignment.center;

                    //define las dimensiones de la tabla (tbl(f,c))
                    Table tbl = doc.AddTable(ListCargFam.Count + 1, 11);

                    //hace que la tabla este al centro de la pagina
                    tbl.Alignment = Alignment.center;
                    tbl.Design    = TableDesign.ColorfulList;
                    tbl.AutoFit   = AutoFit.Contents;

                    //agrega los titulos de la tabla
                    tbl.Rows[0].Cells[0].Paragraphs.First().Append("Rut").FontSize(8D).Alignment              = Alignment.center;
                    tbl.Rows[0].Cells[1].Paragraphs.First().Append("Nombre").FontSize(8D).Alignment           = Alignment.center;
                    tbl.Rows[0].Cells[2].Paragraphs.First().Append("Ap. Paterno").FontSize(8D).Alignment      = Alignment.center;
                    tbl.Rows[0].Cells[3].Paragraphs.First().Append("Fono Movil").FontSize(8D).Alignment       = Alignment.center;
                    tbl.Rows[0].Cells[4].Paragraphs.First().Append("Fecha Nacimiento").FontSize(8D).Alignment = Alignment.center;
                    tbl.Rows[0].Cells[5].Paragraphs.First().Append("Sexo").FontSize(8D).Alignment             = Alignment.center;
                    tbl.Rows[0].Cells[6].Paragraphs.First().Append("Dirección").FontSize(8D).Alignment        = Alignment.center;
                    tbl.Rows[0].Cells[7].Paragraphs.First().Append("Comuna").FontSize(8D).Alignment           = Alignment.center;
                    tbl.Rows[0].Cells[8].Paragraphs.First().Append("Correo").FontSize(8D).Alignment           = Alignment.center;
                    tbl.Rows[0].Cells[9].Paragraphs.First().Append("Nombre Empleado").FontSize(8D).Alignment  = Alignment.center;
                    tbl.Rows[0].Cells[10].Paragraphs.First().Append("Comentarios").FontSize(8D).Alignment     = Alignment.center;
                    //llena las celdas con los datos
                    int fila    = 1;
                    int columna = 0;
                    foreach (var item in ListCargFam)
                    {
                        tbl.Rows[fila].Cells[columna].Paragraphs.First().Append(Convert.ToString(item.Rut_Carga)).FontSize(8D).Alignment = Alignment.left;
                        columna++;
                        tbl.Rows[fila].Cells[columna].Paragraphs.First().Append(Convert.ToString(item.Nombre)).FontSize(8D).Alignment = Alignment.left;
                        columna++;
                        tbl.Rows[fila].Cells[columna].Paragraphs.First().Append(Convert.ToString(item.Paterno)).FontSize(8D).Alignment = Alignment.left;
                        columna++;
                        tbl.Rows[fila].Cells[columna].Paragraphs.First().Append(Convert.ToString(item.Fono_Movil)).FontSize(8D).Alignment = Alignment.left;
                        columna++;
                        tbl.Rows[fila].Cells[columna].Paragraphs.First().Append(Convert.ToString(item.Fecha_Nacimiento)).FontSize(8D).Alignment = Alignment.left;
                        columna++;
                        tbl.Rows[fila].Cells[columna].Paragraphs.First().Append(Convert.ToString(item.Sexo)).FontSize(8D).Alignment = Alignment.left;
                        columna++;
                        tbl.Rows[fila].Cells[columna].Paragraphs.First().Append(Convert.ToString(item.Direccion)).FontSize(8D).Alignment = Alignment.left;
                        columna++;
                        tbl.Rows[fila].Cells[columna].Paragraphs.First().Append(Convert.ToString(item.Comuna)).FontSize(8D).Alignment = Alignment.left;
                        columna++;
                        tbl.Rows[fila].Cells[columna].Paragraphs.First().Append(Convert.ToString(item.Email)).FontSize(8D).Alignment = Alignment.left;
                        columna++;
                        tbl.Rows[fila].Cells[columna].Paragraphs.First().Append(Convert.ToString(item.Nombre_Empleado)).FontSize(8D).Alignment = Alignment.left;
                        columna++;
                        tbl.Rows[fila].Cells[columna].Paragraphs.First().Append(Convert.ToString(item.Comentarios)).FontSize(8D).Alignment = Alignment.left;
                        fila++;
                        columna = 0;
                    }
                    //inserta la tabla dentro del documento
                    doc.InsertTable(tbl);

                    //Genera el Pie de Pagina del Documento
                    doc.AddFooters();
                    //Indica que que la primera página tendrá pies de página independientes
                    doc.DifferentFirstPage = true;
                    //Indica que que la página par e impar tendrá pies de página separados
                    doc.DifferentOddAndEvenPages = true;
                    Footer    footer_main = doc.Footers.First;
                    Paragraph pFooter     = footer_main.Paragraphs.First();
                    pFooter.Alignment = Alignment.center;
                    pFooter.Append("Página ").Bold();
                    pFooter.AppendPageNumber(PageNumberFormat.normal).Bold();
                    pFooter.Append("/").Bold();
                    pFooter.AppendPageCount(PageNumberFormat.normal).Bold();

                    //graba el documento
                    doc.Save();
                    //abre word y el documento
                    Process.Start("WINWORD", filename);

                    return(RedirectToAction("Index"));
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Error On:", ex);
                Response.StatusCode        = 500;
                Response.StatusDescription = ex.Message;
                return(Json(Response));
            }
        }
예제 #11
0
 public void OpenBlank(Exam exam, Ticket ticket, bool markAnswers)
 {
     CloseWord();
     using (DocX docXdocument = DocX.Create(path.ToString()))
     {
         int i, j;
         docXdocument.AddFooters();
         docXdocument.SetDefaultFont(new Xceed.Document.NET.Font("Times New Roman"), 14);
         Xceed.Document.NET.Paragraph headerParagraph = docXdocument.InsertParagraph();
         Xceed.Document.NET.Paragraph paragraph       = docXdocument.InsertParagraph();
         headerParagraph.Append($"Виконання завдань")
         .Bold()
         .FontSize(16);
         paragraph = docXdocument.InsertParagraph();
         paragraph.Append($"Здобувач освіти")
         .Bold()
         .Append("\t\t\t\t\t\t\t")
         .UnderlineStyle(UnderlineStyle.singleLine)
         .Append("білет №")
         .Bold()
         .Append("\t\t")
         .UnderlineStyle(UnderlineStyle.singleLine);
         paragraph = docXdocument.InsertParagraph();
         paragraph.Append($"{Environment.NewLine}I частина")
         .Bold()
         .Alignment = Alignment.center;
         paragraph  = docXdocument.InsertParagraph();
         paragraph.Append($"\tОзнайомтесь з тестовим завданням. Дайте відповіді на тестові завдання в таблиці" +
                          $"(поряд із номером запитання зазначте номер правильної відповіді){Environment.NewLine}")
         .Alignment = Alignment.left;
         List <OneAnswerQuestion[]> questionLists = new List <OneAnswerQuestion[]>();
         for (i = 0; i < exam.Themes.Count; i++)
         {
             OneAnswerQuestion[] questions = exam.Themes[i].GetQuestions(ticket).Cast <OneAnswerQuestion>().ToArray();
             Array.Sort(questions,
                        (Question a, Question b) =>
             {
                 if (a.QuestionNumber > b.QuestionNumber)
                 {
                     return(1);
                 }
                 else if (a.QuestionNumber < b.QuestionNumber)
                 {
                     return(-1);
                 }
                 return(0);
             });
             questionLists.Add(questions);
         }
         int max = questionLists.Max(a => a.Length);
         Xceed.Document.NET.Table table = docXdocument.AddTable(max + 1, questionLists.Count * 2);
         table.SetBorder(TableBorderType.Bottom, new Xceed.Document.NET.Border(BorderStyle.Tcbs_double, BorderSize.two, 0, Color.Black));
         table.SetBorder(TableBorderType.Top, new Xceed.Document.NET.Border(BorderStyle.Tcbs_double, BorderSize.two, 0, Color.Black));
         table.SetBorder(TableBorderType.Left, new Xceed.Document.NET.Border(BorderStyle.Tcbs_double, BorderSize.two, 0, Color.Black));
         table.SetBorder(TableBorderType.Right, new Xceed.Document.NET.Border(BorderStyle.Tcbs_double, BorderSize.two, 0, Color.Black));
         List <float> percentages = new List <float>();
         float        pa          = 30 / (table.ColumnCount / 2);
         float        pb          = 70 / (table.ColumnCount / 2);
         for (i = 0; i < table.ColumnCount / 2; i += 2)
         {
             table.Rows[0].MergeCells(i, i + 1);
             percentages.Add(pa);
             percentages.Add(pb);
             i--;
         }
         table.SetWidthsPercentage(percentages.ToArray(), docXdocument.PageWidth - docXdocument.PageWidth / 5);
         for (i = 0; i < exam.Themes.Count; i++)
         {
             table.Rows[0].Cells[i].InsertParagraph()
             .Append(exam.Themes[i].ThemeName)
             .Alignment = Alignment.center;
         }
         for (i = 0; i < table.ColumnCount / 2; i++)
         {
             for (j = 0; j < questionLists[i].Length; j++)
             {
                 table.Rows[1 + j].Cells[i * 2].InsertParagraph()
                 .Append($"{questionLists[i][j].QuestionNumber + exam.FirstQuestionNumber}");
                 if (markAnswers)
                 {
                     int index = questionLists[i][j].QuestionContent.Answers.IndexOf(questionLists[i][j].Answer.Content);
                     table.Rows[1 + j].Cells[i * 2 + 1].InsertParagraph()
                     .Append(index >= 0 && index < questionLists[i][j].QuestionContent.Letters.Length ? questionLists[i][j].QuestionContent.Letters[index].ToString() : "*");
                 }
             }
         }
         docXdocument.InsertTable(table);
         paragraph = docXdocument.InsertParagraph();
         paragraph.Append($"{Environment.NewLine}{Environment.NewLine}Балл: ")
         .Bold()
         .Alignment = Alignment.right;
         if (!markAnswers)
         {
             paragraph.Append("\t\t")
             .UnderlineStyle(UnderlineStyle.singleLine)
             .Alignment = Alignment.right;
         }
         else
         {
             paragraph.Append($"{ticket.MaxPoints:F2}")
             .UnderlineStyle(UnderlineStyle.singleLine)
             .Alignment = Alignment.right;
         }
         docXdocument.Footers.Odd.InsertParagraph()
         .Append("Створено за допомогою SimplEx Program")
         .FontSize(10)
         .UnderlineStyle(UnderlineStyle.singleLine)
         .Alignment = Xceed.Document.NET.Alignment.right;
         docXdocument.Save();
     }
     OpenWord();
 }