Example #1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            DocX doc = DocX.Load(Server.MapPath("APROBACIÓN_ACTUALIZACIÓN_DE_CONOCIMIENTOS.docx"));

            doc.Bookmarks["CarreraCoordinador"].SetText("Holabebe");
            doc.SaveAs(Server.MapPath("Auxiliar.docx"));

            doc = DocX.Load(Server.MapPath("APROBACIÓN_ACTUALIZACIÓN_DE_CONOCIMIENTOS.docx"));
            doc.Bookmarks["CarreraCoordinador"].SetText("Dieguin");
            //t1.Text = doc.Bookmarks["Cuerpo1"].Paragraph.Text;
            doc.SaveAs(Server.MapPath("Auxiliar2.docx"));
            //hola bebecita



            using (FileStream fileStream = File.OpenRead(Server.MapPath("Auxiliar.docx")))
            {
                MemoryStream memStream = new MemoryStream();
                memStream.SetLength(fileStream.Length);
                fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length);

                Response.Clear();
                Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                Response.AddHeader("Content-Disposition", "attachment; filename=dieguin.docx");
                Response.BinaryWrite(memStream.ToArray());
                Response.Flush();
                Response.Write("<script type='text/javascript'> setTimeout('location.reload(true); ', 0);</script>");
                Response.Close();
                Response.End();
            }
        }
 public void GenerateReport(DocX templateDoc, Report report, string outputPath)
 {
     InjectReport(templateDoc, report);
     if (Path.GetExtension(outputPath) == ".docx")
     {
         templateDoc.SaveAs(outputPath);
     }
     else
     {
         templateDoc.SaveAs($"{outputPath}.docx");
     }
 }
Example #3
0
 public static MemoryStream LoadCtrViewDoc(Miles.Dev.Controls.MRichEditOnly mRichEditOnly, string fileName)
 {
     using (DocX document = DocX.Load(fileName))
     {
         MemoryStream streamBody = new MemoryStream();
         document.SaveAs(streamBody);
         string filename = System.IO.Path.Combine("Report", "tmp.docx");
         document.SaveAs(filename);
         mRichEditOnly.LoadDocument(filename);
         return(streamBody);
     }
 }
Example #4
0
        public string SavePDF()
        {
            MemoryStream stream = new MemoryStream();

            document.SaveAs(stream);
            stream.Position = 0;
            Aspose.Words.Document doc = new Aspose.Words.Document(stream);
            string fileName           = DateTime.Now.ToString("yyyyMMddhhmmssfff");
            string filePath           = string.Format(@"{0}{1}.pdf", this.configManager.getConfig("path.pdf"), fileName);

            doc.Save(filePath, Aspose.Words.SaveFormat.Pdf);
            return(fileName + ".pdf");
        }
Example #5
0
        private Stream CreateLetter(NewLetterModel info)
        {
            try
            {
                var distributor    = _distributorService.GetDistributorById(info.DistNumber);
                var sponsor        = _distributorService.GetDistributorById(info.SponsorNumber);
                var platium        = _distributorService.GetDistributorById(info.PlatiumNumber);
                var oldDistributor = _distributorService.GetDistributorById(info.OldDistNumber);
                var outputStream   = new MemoryStream();


                string filePath   = Server.MapPath(Url.Content("~/Template/LetterTemplate.docx"));
                DocX   document   = DocX.Load(filePath);
                Stream mainStream = new MemoryStream();
                document.SaveAs(mainStream);
                mainStream.Position = 0;
                mainStream          = CreateLetterTemplate(mainStream, distributor, sponsor, platium, oldDistributor);

                //TODO: Add contant for file name
                Stream distributorLetter = CreateLetterAddress(mainStream, distributor);
                //zip.AddEntry("Re-apps letter-Nguoi dang ky lai.docx", distributorLetter);


                Stream sponsorLetter = CreateLetterAddress(mainStream, sponsor);
                //zip.AddEntry("Re-apps letter -Tuyen tren cu.docx", sponsorLetter);

                DocX docx = DocX.Load(distributorLetter);
                docx.InsertSectionPageBreak();
                docx.InsertDocument(DocX.Load(sponsorLetter));

                if (info.SponsorNumber != info.PlatiumNumber)
                {
                    Stream platiumLetter = CreateLetterAddress(mainStream, platium);
                    //zip.AddEntry("Re-apps letter -Platinum cu.docx", platiumLetter);
                    docx.InsertSectionPageBreak();
                    docx.InsertDocument(DocX.Load(platiumLetter));
                }
                docx.SaveAs(outputStream);
                _distributorService.AddNewLetter(new DistributorLetter
                {
                    DistName           = info.DistName,
                    OldDistNumber      = info.OldDistNumber,
                    PlatiniumSponsorId = info.PlatiumNumber,
                    SponsorId          = info.SponsorNumber,
                    DistNumber         = info.DistNumber,
                    LetterDate         = DateTime.Now,
                    UserId             = _workContext.User.UserID,
                    WHId = _workContext.User.WarehouseId
                });


                outputStream.Position = 0;
                return(outputStream);
            }
            catch (Exception ex)
            {
                //TODO: Redirect to error Page
                return(null);
            }
        }
        public FileStreamResult CreateLieferschein(LieferscheinViewModel model)
        {
            LieferscheinData data = Mapper.Map <LieferscheinData>(model);

            if (model.BestehenderKunde != null)
            {
                SetKundenInfo(data, model.BestehenderKunde);
            }

            SetPrices(data);
            SetLieferscheinNr(data);
            data = CalculateService.CalulateLieferscheinTotals(data);

            DocX doc = LieferscheinService.Create(data);

            MemoryStream ms = new MemoryStream();

            doc.SaveAs(ms);
            ms.Position = 0;

            string FILENAME = $"Lieferschein_{data.LieferNr.ToString()}.docx";

            var file = new FileStreamResult(ms, CONTENTTYPEWORD)
            {
                FileDownloadName = string.Format(FILENAME)
            };

            return(file);
        }
Example #7
0
        public void crearwordRegistroproyecto()
        {
            string destinipath = "Formatos\\" + solicitante.NoControl;

            if (!Directory.Exists(destinipath))
            {
                Directory.CreateDirectory(destinipath);
            }

            DocX testTemplate = DocX.Load(@"Templatesformatos\Registrodeproyecto.docx");
            //Paragraph p = testTemplate.InsertParagraph("Hello World.");

            DocX testDoc = testTemplate;

            //Paragraph pa = testDoc.InsertParagraph("Foo.");
            try
            {
                testDoc.ReplaceText("{fecha}", DateTime.Now.Date.ToString());
                testDoc.ReplaceText("{correoelectronico}", solicitante.Correo);
                testDoc.ReplaceText("{numtelefono}", solicitante.Telefono);
                testDoc.ReplaceText("{nombreproyecto}", solicitante.Proyecto_Residencia.Nombre_Proyecto);
                testDoc.ReplaceText("{nombreestudiante}", solicitante.Nombre + " " + solicitante.Apellido_Paterno + " " + solicitante.Apellido_Materno);
                testDoc.ReplaceText("{numestudiantes}", "1");
                testDoc.ReplaceText("{asesorinterno}", solicitante.Proyecto_Residencia.Asesor_Interno.Nombre);
                testDoc.ReplaceText("{nombreempresa}", solicitante.Proyecto_Residencia.Nombre_de_la_Empresa);
                testDoc.ReplaceText("{nocontrol}", solicitante.NoControl.ToString());
            }
            catch { }



            testDoc.SaveAs(destinipath + @"\Registrodeproyecto" + solicitante.NoControl + ".docx");
            testTemplate.Save();
        }
Example #8
0
        public void crearwordconstanciarevisores()
        {
            string destinipath = "Formatos\\" + solicitante.NoControl;

            if (!Directory.Exists(destinipath))
            {
                Directory.CreateDirectory(destinipath);
            }

            DocX testTemplate = DocX.Load(@"Templatesformatos\constanciarevisores.docx");
            //Paragraph p = testTemplate.InsertParagraph("Hello World.");

            DocX testDoc = testTemplate;

            //Paragraph pa = testDoc.InsertParagraph("Foo.");
            try
            {
                testDoc.ReplaceText("{nombrealumno}", solicitante.Nombre + " " + solicitante.Apellido_Paterno + " " + solicitante.Apellido_Materno);
                testDoc.ReplaceText("{nocontrol}", solicitante.NoControl.ToString());
                testDoc.ReplaceText("{nombreproyecto}", solicitante.Proyecto_Residencia.Nombre_Proyecto);
                testDoc.ReplaceText("{nombreempresa}", solicitante.Proyecto_Residencia.Nombre_de_la_Empresa);
                testDoc.ReplaceText("{nombreasesorinterno}", solicitante.Proyecto_Residencia.Asesor_Interno.Nombre);
                testDoc.ReplaceText("{nombreasesorexterno}", solicitante.Proyecto_Residencia.Nombre_Asesor_Externo);
            }
            catch { }



            testDoc.SaveAs(destinipath + @"\constanciarevisores" + solicitante.NoControl + ".docx");
            testTemplate.Save();
        }
Example #9
0
        public string AddInvoiceLine(string description, string hourlySalary, string hoursWorked)
        {
            using (DocX document = DocX.Load(Filepath() + "\\temp.docx"))
            {
                Table invoiceTable = document.Tables.FirstOrDefault(t => t.TableCaption == "INVOICE_TABLE");

                if (invoiceTable == null)
                {
                    return("Fejl. Kunne ikke finde tabel i skabelon.");
                }
                else
                {
                    double hourlySalaryDouble = Convert.ToDouble(hourlySalary);
                    double hoursWorkedDouble  = Convert.ToDouble(hoursWorked);
                    double total = hourlySalaryDouble * hoursWorkedDouble;
                    finalPrice += total;

                    Row rowPattern = invoiceTable.Rows[1];
                    Row invoiceRow = invoiceTable.InsertRow(rowPattern, invoiceTable.RowCount);
                    invoiceRow.Cells[0].Paragraphs.First().Append(description.ToUpper()).Italic();
                    invoiceRow.Cells[1].Paragraphs.First().Append(hourlySalary + " DKK");
                    invoiceRow.Cells[2].Paragraphs.First().Append(hoursWorked);
                    invoiceRow.Cells[3].Paragraphs.First().Append(total.ToString() + " DKK").Bold();

                    document.SaveAs(Filepath() + "\\temp.docx");
                    rowCount++;
                    return(total.ToString());
                }
            }
        }
Example #10
0
        public void substituidor(string[,] subst)
        {
            // We will need a file name for our output file (change to suit your machine):
            string origem = functions.word_open();

            if (origem != null)
            {
                // Let's save the file with a meaningful name, including the
                // applicant name and the letter date:
                string destino = functions.word_save();
                if (destino != null)
                {
                    DocX letter = DocX.Load(origem);

                    // Perform the replace:
                    for (int i = 0; i < subst.GetLength(0); i++)
                    {
                        letter.ReplaceText(subst[i, 0], subst[i, 1]);
                    }

                    // Save as New filename:
                    letter.SaveAs(destino);
                }
            }
        }
Example #11
0
 public void saveFile(string outputPath, DocX templateDoc)
 {
     if (!File.Exists(outputPath))
     {
         templateDoc.SaveAs(outputPath);
     }
 }
Example #12
0
 //Sử dụng docx dll để tạo file word từ template
 public static void CreateWordDocument(string file_location, string output_location, List <string> list_nguon, List <string> list_dich)
 {
     try
     {
         // Load the document.
         using (DocX document = DocX.Load(file_location))
         {
             if (list_nguon.Count == list_dich.Count)
             {
                 for (int i = 0; i < list_nguon.Count; i++)
                 {
                     // Replace text in this document.
                     document.ReplaceText(list_nguon[i], list_dich[i]);
                 }
             }
             //Remove empty paragraph
             //document.RemoveParagraphAt
             //document.ReplaceText("^p^p", "^p");
             // Save changes made to this document.
             //document.Save();
             document.SaveAs(output_location);
         } // Release this document from memory.
     }
     catch
     {
         MessageBox.Show("File mẫu đang mở, liên hệ bộ phận Điện toán để kiểm tra");
         return;
     }
 }
        private void GenerarWord()
        {
            string filename = txtNResolucion.Text + "-P-CD-FISEI-UTA-2020";
            //Definimos la ruta del archivo que ya se creo
            DocX document = DocX.Load(Server.MapPath("~/Plantilla/APROBACION_REINGRESO.docx"));



            document.Bookmarks["FechaResolucion"].SetText(txtFecha.Text);
            document.Bookmarks["NResolucion"].SetText(txtNResolucion.Text);
            document.Bookmarks["CoordinadorCarrera"].SetText(ddlCoordinadores.SelectedValue);
            document.Bookmarks["CarreraCoordinador"].SetText(ddlCarrerasCoordinador.SelectedValue);

            document.Bookmarks["TipoSesion"].SetText(ddlSesion.SelectedValue);
            document.Bookmarks["FechaSesion"].SetText(txtFechaSesion.Text);
            document.Bookmarks["NAcuerdo"].SetText(txtNMemorando.Text);
            document.Bookmarks["FechaAcuerdo"].SetText(txtFechaMemorando.Text);
            document.Bookmarks["PresidenteCAF"].SetText(txtPresidente.Text);
            document.Bookmarks["EstudianteCI"].SetText(txtCedula.Text);
            document.Bookmarks["EstudianteM"].SetText(txtApellidos.Text.ToUpper() + " " + TxtNombres.Text.ToUpper());
            document.Bookmarks["CarreraEstudiante"].SetText(txtCarreraEstudiante.Text);
            document.Bookmarks["EstudianteM2"].SetText(txtApellidos.Text.ToUpper() + " " + TxtNombres.Text.ToUpper());
            document.Bookmarks["EstudianteCI2"].SetText(txtCedula.Text);
            document.Bookmarks["CarreraEstudianteM"].SetText(txtCarreraEstudiante.Text.ToUpper());

            document.Bookmarks["PeriodoAcademico"].SetText(txtPeriodo.Text.ToUpper());
            document.Bookmarks["CoordinadorCarreraR"].SetText(txtCarreraEstudiante.Text.ToUpper());



            document.Bookmarks["Miembro"].SetText(txtAtentamente.Text);
            document.Bookmarks["MiembroCargo"].SetText(txtCargoMiembro.Text + "\n");
            //Llevar el cuerpo
            string cuerpo = document.Bookmarks["Cuerpo1"].Paragraph.Text + "\n\n";

            cuerpo = cuerpo + document.Bookmarks["Cuerpo2"].Paragraph.Text + "\n\n";
            cuerpo = cuerpo + document.Bookmarks["Cuerpo3"].Paragraph.Text + "\n\n";
            cuerpo = cuerpo + document.Bookmarks["Cuerpo4"].Paragraph.Text + "\n\n";
            cuerpo = cuerpo + document.Bookmarks["Cuerpo5"].Paragraph.Text + "\n\n";
            //Saco el nombre del archivo
            document.SaveAs(Server.MapPath("~/Plantilla/Auxiliar.docx"));
            GuardarBaseDatos(cuerpo, filename);

            ///
            using (FileStream fileStream = File.OpenRead(Server.MapPath("~/Plantilla/Auxiliar.docx")))
            {
                MemoryStream memStream = new MemoryStream();
                memStream.SetLength(fileStream.Length);
                fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length);

                Response.Clear();
                Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + filename + ".docx");
                Response.BinaryWrite(memStream.ToArray());
                Response.Flush();
                Response.Write("<script type='text/javascript'> setTimeout('location.reload(true); ', 0);</script>");
                Response.Close();
                Response.End();
            }
        }
Example #14
0
        public static void patientPrint(patient pat)
        {
            string template = @"TransferbladTemplate.docx";

            using (DocX doc = DocX.Load(template))
            {
                doc.AddCustomProperty(new CustomProperty("VolgNr", pat.Id));
                doc.AddCustomProperty(new CustomProperty("InschrNR", pat.Inschrijvingsnr));
                doc.AddCustomProperty(new CustomProperty("NaaM", pat.Naam));
                doc.AddCustomProperty(new CustomProperty("VoorNaaM", pat.Voornaam));
                doc.AddCustomProperty(new CustomProperty("gebDatum", pat.Geboortedatum.ToString()));
                doc.AddCustomProperty(new CustomProperty("opnameDat", pat.TijdOpname.ToString()));
                doc.AddCustomProperty(new CustomProperty("ontslagDat", pat.TijdOntslag.ToString()));
                doc.AddCustomProperty(new CustomProperty("Artsen", pat.BehandelArts));
                doc.AddCustomProperty(new CustomProperty("AnamNese", pat.Anamnese));
                doc.AddCustomProperty(new CustomProperty("thuisMed", pat.ThuisMed));
                doc.AddCustomProperty(new CustomProperty("RitMe", pat.Ritme));
                doc.AddCustomProperty(new CustomProperty("pP", pat.WhatIsP));
                doc.AddCustomProperty(new CustomProperty("BDD", pat.Bd));
                doc.AddCustomProperty(new CustomProperty("Dieet", pat.Dieet));
                doc.AddCustomProperty(new CustomProperty("SV", pat.Sv));
                doc.AddCustomProperty(new CustomProperty("Diagno", pat.Diagnose));
                doc.AddCustomProperty(new CustomProperty("ZorGen", pat.Zorgen));
                doc.AddCustomProperty(new CustomProperty("Verslag", pat.Verslag));
                doc.AddCustomProperty(new CustomProperty("teleMetrie", pat.Telemetrie.ToString()));
                doc.AddCustomProperty(new CustomProperty("ZalVing", pat.Zalving));
                doc.AddCustomProperty(new CustomProperty("KinE", pat.Kine));
                doc.SaveAs("printPat.docx");
            }
            Process.Start("WINWORD.EXE", "printPat.docx");
        }
        public void TestCreate_One_Product_Pizza()
        {
            // Arrange
            IRechnungService rechnung = new RechnungService();
            RechnungData     data     = new RechnungData
            {
                Kunde            = "Metzgerei Siegfried",
                AdressZeile1     = "Bottigenstrasse 22",
                AdressZeile2     = "3018 Bern",
                RechnungsDatum   = DateTime.Today,
                LieferDatum      = DateTime.Today,
                RechnungsNummer  = "0079",
                EinzelpreisPizza = 10.00m,
                TotalPizza       = 20.00m,
                MengePizza       = 2,
                SubTotal         = 20.00m,
                Total            = 20.00m
            };

            // Act
            DocX document = rechnung.Create(data);

            document.SaveAs(FILE_NAME);

            // Assert
            Assert.IsNotNull(document);
            Assert.IsTrue(File.Exists(FILE_NAME));
            Assert.IsFalse(document.Tables.Any(x => x.Rows.Any(y => y.Cells.Any(p => p.Paragraphs.Any(t => t.Text.Contains(Bearfoods.BBQ))))));
            Assert.IsFalse(document.Tables.Any(x => x.Rows.Any(y => y.Cells.Any(p => p.Paragraphs.Any(t => t.Text.Contains(Bearfoods.Jus))))));
            Assert.IsTrue(document.Tables.Any(x => x.Rows.Any(y => y.Cells.Any(p => p.Paragraphs.Any(t => t.Text.Contains(Bearfoods.Pizza))))));
        }
Example #16
0
        public ActionResult Generate(JIUViewModel model)
        {
            //get temp name from reg expression plus lang plus symb
            string fname = model.tempname.ToString();

            g_assembly = Assembly.GetExecutingAssembly();

            //   string source = Server.MapPath(Path.Combine("/", "IN/" + fname + ".docx"));
            //  string Dest = Server.MapPath(Path.Combine("/", "OUT/" + fname + ".docx"));

            string source = Server.MapPath(Path.Combine("/", "GDGS/IN/" + fname + ".docx"));
            string Dest   = Server.MapPath(Path.Combine("/", "GDGS/OUT/" + fname + ".docx"));

            string tempname = fname.Remove(fname.Length - 1);

            model.tempname = tempname;
            g_document     = DocX.Load(source);
            g_document     = CreateDocA(DocX.Load(source), model, source);

            g_document.SaveAs(Dest);
            g_document.AddCoreProperty("dc:title", model.Sym.ToString());
            // g_document.AddCoreProperty("dc:author", model.Sym.ToString());
            g_document.Save();
            //   Changegdoc(source);
            return(RedirectToAction("download", "JIU", new { name = fname }));
        }
Example #17
0
        private static void Action(FileInfo file)
        {
            // Load the document.
            using (DocX document = DocX.Load(file.FullName))
            {
                // Replace texts in this document.
                document.ReplaceText("Apples", "Potatoes");
                document.ReplaceText("An Apple", "A Potato");

                // create the new image
                var newImage = document.AddImage(ParallelSample.ParallelSampleResourcesDirectory + @"potato.jpg");

                // Look in each paragraph and remove its first image to replace it with the new one.
                foreach (var p in document.Paragraphs)
                {
                    var oldPicture = p.Pictures.FirstOrDefault();
                    if (oldPicture != null)
                    {
                        oldPicture.Remove();
                        p.AppendPicture(newImage.CreatePicture(150, 150));
                    }
                }

                document.SaveAs(ParallelSample.ParallelSampleOutputDirectory + "Output" + file.Name);
                Console.WriteLine("\tCreated: Output" + file.Name + ".docx\n");
            }
        }
Example #18
0
        public void CreateDocument()
        {
            if (_patient == null)
            {
                return;
            }
            try
            {
                if (File.Exists(_template))
                {
                    using (_document = DocX.Load(_template))
                    {
                        WriteMainParagraphs();
                        _document.SaveAs(_savePdfDocumentsPath + $@"\{_patientName}.docx");
                    }
                }
                else
                {
                    using (_document = DocX.Create(_savePdfDocumentsPath + $@"\{_patientName}.docx"))
                    {
                        WriteMainParagraphs();
                        _document.Save();
                    }
                }

                System.Diagnostics.Process.Start(_savePdfDocumentsPath + $@"\{_patientName}.docx");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Example #19
0
 public static void CreateWordDocument2(string file_location, string output_location, List <string> list_nguon1, List <string> list_dich1, List <string> list_nguon2, List <string> list_dich2)
 {
     // Load the document.
     using (DocX document = DocX.Load(file_location))
     {
         if (list_nguon1.Count == list_dich1.Count)
         {
             for (int i = 0; i < list_nguon1.Count; i++)
             {
                 // Replace text in this document.
                 document.ReplaceText(list_nguon1[i], list_dich1[i]);
             }
         }
         if (list_nguon2.Count == list_dich2.Count)
         {
             for (int i = 0; i < list_nguon2.Count; i++)
             {
                 // Replace text in this document.
                 document.ReplaceText(list_nguon2[i], list_dich2[i]);
             }
         }
         // Save changes made to this document.
         //document.Save();
         try
         {
             document.SaveAs(output_location);
         }
         catch
         {
             MessageBox.Show("File đang được sử dụng!", "Thông báo", MessageBoxButtons.OK);
         }
     } // Release this document from memory.
 }
Example #20
0
        // Generate an appointment letter for employee of type Staff, Non-Union Represented, Regular-Term.
        // Input:   Appointment object (employee information)
        // Output:  Microsoft .docx file appended with employee information, saved to Content folder.
        public void CreateLetterStaffNonrepTerm(Appointment appointmentForDoc)
        {
            // create a DocX object with the letter template .docx file
            string staffLetterFileName = "NR-Staff-Term-Appt-Ltr_040716.docx";
            string staffFilePath       = AppDomain.CurrentDomain.BaseDirectory + @"content\appointment_letters\" + staffLetterFileName;
            DocX   letter = DocX.Load(staffFilePath);

            // Replace all the fields in the template with atrributes from the Appointment object
            letter.ReplaceText("<<CurrentDate>>", DateTime.Now.ToShortDateString());
            letter.ReplaceText("<<Name>>", appointmentForDoc.Name);
            letter.ReplaceText("<<Address>>", appointmentForDoc.Employee_Address);
            letter.ReplaceText("<<SupervisorName>>", appointmentForDoc.Supervisor_Name);
            letter.ReplaceText("<<WorkingTitle>>", appointmentForDoc.Working_Title);
            letter.ReplaceText("<<JobTitle>>", appointmentForDoc.Job_Title);
            letter.ReplaceText("<<PCN>>", appointmentForDoc.Position_Number);
            letter.ReplaceText("<<Status>>", "Regular Term, " + appointmentForDoc.Full_Time + ", " + appointmentForDoc.Exemption);
            if (appointmentForDoc.Biweekly_Salary.HasValue)
            {
                letter.ReplaceText("<<PayType>>", "Bi-weekly salary");
                letter.ReplaceText("<<PayAmount>>", appointmentForDoc.Biweekly_Salary.ToString() + " per pay period");
            }
            if (appointmentForDoc.Hourly_Rate.HasValue)
            {
                letter.ReplaceText("<<PayType>>", "Hourly rate");
                letter.ReplaceText("<<PayAmount>>", appointmentForDoc.Hourly_Rate.ToString() + " per hour");
            }
            letter.ReplaceText("<<BeginningDate>>", appointmentForDoc.Beginning_Date);
            letter.ReplaceText("<<EndingDate>>", appointmentForDoc.Ending_Date);

            // Save the letter as a temporary document for download
            letter.SaveAs(AppDomain.CurrentDomain.BaseDirectory + @"content\temp_files\TempAppointmentLetter.docx");
        }
Example #21
0
        public static Stream GenerateCover(int sortMainId)
        {
            var sort = SortMainObject.GetSortMain(sortMainId);

            if (sort != null)
            {
                var  toReturn = new MemoryStream();
                DocX doc      = null;

                if (sort.Title.Trim().Substring(0, 7).Equals("INL-CON", StringComparison.OrdinalIgnoreCase) ||
                    sort.Title.Trim().Substring(0, 7).Equals("INL-JOU", StringComparison.OrdinalIgnoreCase))
                {
                    doc = GetJouCover();
                }
                else
                {
                    doc = GetExtCover();
                }

                doc.ReplaceText("{publicationdate}", sort.PublicationDate?.ToString("MMMM yyyy") ?? string.Empty);
                doc.ReplaceText("{stititle}", sort.Title?.RemoveNonAscii() ?? string.Empty);
                doc.ReplaceText("{publishtitle}", sort.PublishTitle?.RemoveNonAscii() ?? string.Empty);
                doc.ReplaceText("{authors}", string.Join(", ", sort.Authors.Select(n => n.FullName))?.RemoveNonAscii() ?? string.Empty);
                doc.ReplaceText("{doctype}", sort.ProductTypeDisplayName?.RemoveNonAscii() ?? string.Empty);
                doc.ReplaceText("{contractnumber}", string.Join(", ", sort.Funding.Select(n => n.ContractNumber))?.RemoveNonAscii() ?? string.Empty);
                doc.ReplaceText("{fundingoffice}", string.Join(", ", sort.Funding.Select(n => n.TitleFundingSourceName))?.RemoveNonAscii() ?? string.Empty);

                doc.SaveAs(toReturn);
                return(toReturn);
            }

            return(null);
        }
Example #22
0
        public void Create()
        {
            paragraphHeader = document.InsertParagraph(header + this.docNumber, false, formattingNormal);
            FormatToGost(paragraphHeader, Alignment.center);
            paragraphName = document.InsertParagraph(theme, false, formattingBold);
            FormatToGost(paragraphName, Alignment.center);
            paragraphTaskHeader = document.InsertParagraph(taskHeader + taskNumber, false, formattingNormal);
            FormatToGost(paragraphTaskHeader, Alignment.both);
            paragraphEmptyLine = document.InsertParagraph("\r", false, formattingNormal);
            FormatToGost(paragraphEmptyLine, Alignment.both);
            document.InsertParagraph(paragraphEmptyLine);
            paragraphCodeHeader = document.InsertParagraph(codeHeader, false, formattingNormal);
            FormatToGost(paragraphCodeHeader, Alignment.both);
            InsertCode(0);
            paragraphResultHeader = document.InsertParagraph(resultHeader, false, formattingNormal);
            InsertScreenshot();
            FormatToGost(paragraphResultHeader, Alignment.both);

            document.InsertParagraph(paragraphEmptyLine);

            for (int i = 1; i < codeDirFolders.Length; i++)
            {
                InsertTask(i);
            }

            try
            {
                document.SaveAs(filePath);
            }
            catch (Exception)
            {
                MessageBox.Show("Ошибка в сохранении файла")
            }
            document.Dispose();
        }
Example #23
0
        public void crearwordasignarrevisor()
        {
            string destinipath = "Formatos\\" + solicitante.NoControl;

            if (!Directory.Exists(destinipath))
            {
                Directory.CreateDirectory(destinipath);
            }

            DocX testTemplate = DocX.Load(@"Templatesformatos\asignarevisor.docx");
            //Paragraph p = testTemplate.InsertParagraph("Hello World.");

            DocX testDoc = testTemplate;

            //Paragraph pa = testDoc.InsertParagraph("Foo.");

            testDoc.ReplaceText("{nombreproyecto}", solicitante.Proyecto_Residencia.Nombre_Proyecto);

            testDoc.ReplaceText("{Nombrealumno}", solicitante.Nombre + " " + solicitante.Apellido_Paterno + " " + solicitante.Apellido_Materno);



            testDoc.SaveAs(destinipath + @"\asignarevisor" + solicitante.NoControl + ".docx");
            testTemplate.Save();
        }
Example #24
0
        public void CreateSampleDocument2(int Id)
        {
            using (Entities1 db = new Entities1())
            {
                Vw_Complaints cm       = db.Vw_Complaints.Where(x => x.ID == Id).FirstOrDefault();
                Apartment     ap       = db.Apartments.Where(x => x.Name == cm.flat).FirstOrDefault();
                Tower         tw       = db.Towers.Where(x => x.Name == cm.Name).FirstOrDefault();
                string        body     = string.Format("وردنا شكوي تسرب مياه صادر علي شقة رقم ({0}) وبخروج فني الصيانة عن مكان التسرب تبين الاتي:", cm.OtherApartment);
                string        subject  = string.Format("المحترم / ساكن الشقة رقم ({0}) برج رقم                 ({1}) المحترم", ap.ID, tw.ID);
                string        footer   = string.Format("صورة مع التحية شقة رقم ({0})", cm.OtherApartment);
                DocX          document = DocX.Load(@"C:\test\Template.docx");
                Paragraph     p0       = document.InsertParagraph();
                p0.Direction = Novacode.Direction.RightToLeft;
                p0.Append(string.Format("التاريخ {0}", string.Format("{0:d/M/yyyy}", DateTime.Now)));
                p0.Bold();
                Paragraph p1 = document.InsertParagraph();
                p1.Direction = Novacode.Direction.RightToLeft;
                p1.Append(subject);
                p1.Bold();
                Paragraph p2 = document.InsertParagraph();
                p2.Direction = Novacode.Direction.RightToLeft;
                p2.Append("السلام عليكم ورحمة الله وبركاتة");
                p2.Bold();
                Paragraph p3 = document.InsertParagraph();
                p3.Direction = Novacode.Direction.RightToLeft;
                p3.Append(body);
                Paragraph p7 = document.InsertParagraph();
                p7.Direction = Novacode.Direction.RightToLeft;
                p7.Append("............................................................................................................................");
                p7.Append("............................................................................................................................");
                p7.Append("............................................................................................................................");
                p7.Append("............................................................................................................................");
                p7.Append("............................................................................................................................");
                p7.Append("............................................................................................................................");

                Paragraph p4 = document.InsertParagraph();
                p4.Direction = Novacode.Direction.RightToLeft;
                p4.Append("شاكرين حسن تعاونكم");
                p4.Alignment = Alignment.center;
                p4.Bold();
                p4.SpacingAfter(20);
                Paragraph p5 = document.InsertParagraph();
                p5.Append("ادارة مجمع اسكان المعذر");
                p5.Alignment = Alignment.left;
                p5.Direction = Novacode.Direction.RightToLeft;
                p5.Bold();
                Paragraph p6 = document.InsertParagraph();
                p6.Direction = Novacode.Direction.RightToLeft;
                p6.Append(footer);
                document.SaveAs(Server.MapPath("/Docs/WordAlignment.docx"));
                Context.Response.Clear();
                FileInfo file = new FileInfo(Server.MapPath("/Docs/WordAlignment.docx"));
                Context.Response.ContentType = "Application/msword";
                Context.Response.AppendHeader("Content-Disposition", "inline; filename=" + file.Name);
                Context.Response.AppendHeader("Content-Length", file.Length.ToString());
                Context.Response.WriteFile(file.FullName);
                Context.Response.End();
                //System.Diagnostics.Process.Start("WordAlignment.docx");
            }
        }
Example #25
0
        public void crearwordasignacionasesorinterno()
        {
            string destinipath = "Formatos\\" + solicitante.NoControl;

            if (!Directory.Exists(destinipath))
            {
                Directory.CreateDirectory(destinipath);
            }

            DocX testTemplate = DocX.Load(@"Templatesformatos\Asignacionasesorinterno.docx");
            //Paragraph p = testTemplate.InsertParagraph("Hello World.");

            DocX testDoc = testTemplate;

            //Paragraph pa = testDoc.InsertParagraph("Foo.");
            try
            {
                testDoc.ReplaceText("{nombrealumno}", solicitante.Nombre + " " + solicitante.Apellido_Paterno + " " + solicitante.Apellido_Materno);
                testDoc.ReplaceText("{correoalumno}", solicitante.Correo);
                testDoc.ReplaceText("{telefonoalumno}", solicitante.Telefono);
                testDoc.ReplaceText("{nombreproyecto}", solicitante.Proyecto_Residencia.Nombre_Proyecto);
                testDoc.ReplaceText("{nombreempresa}", solicitante.Proyecto_Residencia.Nombre_de_la_Empresa);
                testDoc.ReplaceText("{telefonoasesor}", solicitante.Proyecto_Residencia.Telefono_Asesor_Externo);
                testDoc.ReplaceText("{nombreasesor}", solicitante.Proyecto_Residencia.Nombre_Asesor_Externo);
                testDoc.ReplaceText("{cargoasesor}", solicitante.Proyecto_Residencia.Cargo_Asesor_Externo);
            }
            catch { }



            testDoc.SaveAs(destinipath + @"\Asignacionasesorinterno" + solicitante.NoControl + ".docx");
            testTemplate.Save();
        }
Example #26
0
        /// <summary>
        /// Modify an image from a document by writing text into it.
        /// </summary>
        public static void ModifyImage()
        {
            Console.WriteLine("\tModifyImage()");

            // Open the document Input.docx.
            using (DocX document = DocX.Load(ImageSample.ImageSampleResourcesDirectory + @"Input.docx"))
            {
                // Add a title
                document.InsertParagraph(0, "Modifying Image by adding text/circle into the following image", false).FontSize(15d).SpacingAfter(50d).Alignment = Alignment.center;

                // Get the first image in the document.
                var image = document.Images.FirstOrDefault();
                if (image != null)
                {
                    // Create a bitmap from the image.
                    var bitmap = new Bitmap(image.GetStream(FileMode.Open, FileAccess.ReadWrite));
                    // Get the graphic from the bitmap to be able to draw in it.
                    var graphic = Graphics.FromImage(bitmap);
                    if (graphic != null)
                    {
                        // Draw a string with a specific font, font size and color at (0,10) from top left of the image.
                        graphic.DrawString("@copyright", new System.Drawing.Font("Arial Bold", 12), Brushes.Red, new PointF(0f, 10f));
                        // Draw a blue circle of 10x10 at (30, 5) from the top left of the image.
                        graphic.FillEllipse(Brushes.Blue, 30, 5, 10, 10);

                        // Save this Bitmap back into the document using a Create\Write stream.
                        bitmap.Save(image.GetStream(FileMode.Create, FileAccess.Write), ImageFormat.Png);
                    }
                }

                document.SaveAs(ImageSample.ImageSampleOutputDirectory + @"ModifyImage.docx");
                Console.WriteLine("\tCreated: ModifyImage.docx\n");
            }
        }
Example #27
0
        public void crearwordsolicitudresidencia()
        {
            string destinipath = "Formatos\\" + solicitante.NoControl;

            if (!Directory.Exists(destinipath))
            {
                Directory.CreateDirectory(destinipath);
            }

            DocX testTemplate = DocX.Load(@"Templatesformatos\solicitudresidencia.docx");
            //Paragraph p = testTemplate.InsertParagraph("Hello World.");

            DocX testDoc = testTemplate;

            //Paragraph pa = testDoc.InsertParagraph("Foo.");

            testDoc.ReplaceText("{Fecha}", DateTime.Now.Date.ToString());
            testDoc.ReplaceText("{Nombreproyecto}", solicitante.Proyecto_Residencia.Nombre_Proyecto);
            testDoc.ReplaceText("{nombreempresa}", solicitante.Proyecto_Residencia.Nombre_de_la_Empresa);
            testDoc.ReplaceText("{Asesorexterno}", solicitante.Proyecto_Residencia.Nombre_Asesor_Externo);
            testDoc.ReplaceText("{cargoasesor}", solicitante.Proyecto_Residencia.Cargo_Asesor_Externo);
            testDoc.ReplaceText("{asesorexterno}", solicitante.Proyecto_Residencia.Nombre_Asesor_Externo);
            testDoc.ReplaceText("{cargoasesorexterno}", solicitante.Proyecto_Residencia.Cargo_Asesor_Externo);
            testDoc.ReplaceText("{nombrealumno}", solicitante.Nombre + " " + solicitante.Apellido_Paterno + " " + solicitante.Apellido_Materno);
            testDoc.ReplaceText("{Nocontrol}", solicitante.NoControl.ToString());
            testDoc.ReplaceText("{Correoalumno}", solicitante.Correo);
            testDoc.ReplaceText("{telefonoalumno}", solicitante.Telefono);


            testDoc.SaveAs(destinipath + @"\Solicitudresidencia" + solicitante.NoControl + ".docx");
            testTemplate.Save();
        }
        public FileStreamResult CreateRechnung(RechnungViewModel model)
        {
            RechnungData data = Mapper.Map <RechnungData>(model);

            if (model.BestehenderKunde != null)
            {
                SetKundenInfo(data, model.BestehenderKunde);
            }

            SetPrices(data);
            SetRechnungsNr(data);
            data = CalculateService.CalulateRechnungTotals(data);

            DocX doc = RechnungService.Create(data);

            MemoryStream ms = new MemoryStream();

            doc.SaveAs(ms);
            ms.Position = 0;

            string FILENAME = $"Rechnung_{data.RechnungsNummer}.docx";

            var file = new FileStreamResult(ms, CONTENTTYPEWORD)
            {
                FileDownloadName = string.Format(FILENAME)
            };

            return(file);
        }
Example #29
0
        public override Stream Gerar()
        {
            Stream ms     = new MemoryStream();
            string titulo = Documento.TituloDocumento;

            if (Documento.Arquivo != null)
            {
                ms = new MemoryStream(Documento.Arquivo);
                DocX doc = DocX.Load(ms);
                doc.SubstituirCamposDocumento(Dados);
                doc.SaveAs(ms);
            }
            else
            {
                using (DocX doc = DocX.Create(ms))
                {
                    Cabecalho.Gerar(doc);
                    doc.AddTitle(titulo);
                    GerarCorpoDocumento(doc);
                    GerarCampoAdicionais(doc);
                    doc.SaveAs(ms);
                }
            }
            ms.Position = 0;
            return(ms);
        }
Example #30
0
 public static String NewDocXFile(String FileFullName, NcFile ncFile, NcFileDetails ncFileDetails, NcFileFix ncFileFix)
 {
     try
     {
         DocX templateDocument = DocX.Load(@"NcFileDetail.docx");
         foreach (Paragraph paragraph in templateDocument.Paragraphs)
         {
             paragraph.ReplaceText("<Titre-NC>", ncFile.case_title);
             paragraph.ReplaceText("<Createur>", ncFile.nc_user_full_Name);
             paragraph.ReplaceText("<Structure>", ncFile.structure_name);
             paragraph.ReplaceText("<Description>", ncFileDetails.description);
             paragraph.ReplaceText("<N-plan>", ncFileDetails.n_plan);
             paragraph.ReplaceText("<Ens-Partiel>", ncFileDetails.partial_set);
             paragraph.ReplaceText("<Source>", ncFile.source? "interne" : "externe");
             paragraph.ReplaceText("<Date-Creation>", ncFile.creation_date);
             paragraph.ReplaceText("<Cause>", ncFileFix.cause);
             paragraph.ReplaceText("<Description-Action>", ncFileFix.action_description);
             paragraph.ReplaceText("<Type-Action>", ncFileFix.action_type == 1? "correction" : "corrective");
             paragraph.ReplaceText("<Responsable-Action>", ncFileFix.fixer_full_name);
             paragraph.ReplaceText("<Fonction-Responsable-Action>", ncFileFix.fixer_function);
             paragraph.ReplaceText("<Structure-Responsable-Action>", ncFileFix.fixer_structure_name);
             paragraph.ReplaceText("<Temp-Planifie-Debut>", ncFileFix.estimated_start_date);
             paragraph.ReplaceText("<Temp-Planifie-Fin>", ncFileFix.estimated_end_date);
         }
         templateDocument.SaveAs(FileFullName);
         return("ok");
     }
     catch (Exception e) { return(e.Message); }
 }