Example #1
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 #2
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 #3
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 #4
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 ProcessData(ReleaseData data, Dictionary <string, List <ChangesetInfo> > categorizedChangesets,
                                IEnumerable <ClientWorkItem> workItems, IEnumerable <ClientWorkItem> pbi)
        {
            var    dTestDocx = @"D:\test.docx";
            string fileName  = @"D:\Template.docx";

            using (var doc = DocX.Load(fileName))
            {
                doc.ReplaceText("{ReleaseName}", data.ReleaseName);
                doc.ReplaceText("{ReleaseDate}", data.ReleaseDateFormated);
                doc.ReplaceText("{TfsBranch}", data.TfsBranch);
                doc.ReplaceText("{QaBuildName}", data.QaBuildName);
                doc.ReplaceText("{QaBuildDate}", data.QaBuildDateFormated);
                doc.ReplaceText("{CoreBuildName}", data.CoreBuildName);
                doc.ReplaceText("{CoreBuildDate}", data.CoreBuildDateFormated);
                doc.ReplaceText("{PsRefreshChangeset}", data.PsRefresh.Id.ToString());
                doc.ReplaceText("{PsRefreshDate}", data.PsRefresh.Created.ToString("yyyy-MM-dd HH:mm", new CultureInfo("en-US")));
                doc.ReplaceText("{PsRefreshName}", data.PsRefresh.Comment);
                doc.ReplaceText("{CoreChangeset}", data.CoreChange.Id.ToString());
                doc.ReplaceText("{CoreDate}", data.CoreChange.Created.ToString("yyyy-MM-dd HH:mm", new CultureInfo("en-US")));
                var lastParagraph = doc.Paragraphs[doc.Paragraphs.Count - 1];
                var secondSection = SecondSection(categorizedChangesets, lastParagraph);
                var thirdSection  = ThirdSection(workItems, secondSection);
                var fourthSection = FourthSection(pbi, thirdSection);

                var fifthSection = fourthSection.CreateHeadingSection("Test Report");
                var sixthSection = fifthSection.CreateHeadingSection("Known issues in this Release");

                doc.SaveAs(dTestDocx);
            }

            Process.Start(dTestDocx);
        }
Example #6
0
 private void saveFileDialog_FileOk(object sender, CancelEventArgs e)
 {
     try
     {
         Customer mCus = new KhachHangLDM().GetElement(mConsume.CustomerID.Value);
         var      doc  = DocX.Load(@"..\..\doc\HoaDon.docx");
         doc.ReplaceText("<MaSo>", (MyRandom.RandomString(9) + mConsume.ID));
         doc.ReplaceText("<TenKhachHang>", mCus.User.DisplayName);
         doc.ReplaceText("<SoCMT>", mCus.PassportID);
         doc.ReplaceText("<DiaChi>", mCus.User.Address);
         doc.ReplaceText("<ThoiGian>", thoiGian);
         doc.ReplaceText("<LuongDienTieuThu>", mConsume.ElectricConsume.ToString() + " (Kwh)");
         doc.ReplaceText("<LuongNuocTieuThu>", mConsume.WaterConsume.ToString() + " (khối)");
         doc.ReplaceText("<TongTienDien>", (mConsume.ElectricConsume.Value * mPrice.ElectricPrice.Value).ToString("#,###"));
         doc.ReplaceText("<TongTienNuoc>", (mConsume.WaterConsume.Value * mPrice.WaterPrice.Value).ToString("#,###"));
         doc.ReplaceText("<TongCong>", ((mConsume.WaterConsume.Value * mPrice.WaterPrice.Value) + (mConsume.ElectricConsume.Value * mPrice.ElectricPrice.Value)).ToString("#,###"));
         doc.ReplaceText("<Ngay>", DateTime.Now.Day.ToString());
         doc.ReplaceText("<Thang>", DateTime.Now.Month.ToString());
         doc.ReplaceText("<Nam>", DateTime.Now.Year.ToString());
         Stream       stream = saveFileDialog.OpenFile();
         StreamWriter sw     = new StreamWriter(stream);
         doc.SaveAs(stream);
         sw.Close();
         stream.Close();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Example #7
0
        public override void ExecuteResult(ControllerContext context)
        {
            var wc           = new WebClient();
            var bytes        = wc.DownloadData(template);
            var ms           = new MemoryStream(bytes);
            var doctemplate  = DocX.Load(ms);
            var replacements = new EmailReplacements(DbUtil.Db, doctemplate);
            var q            = peopleId.HasValue
                ? DbUtil.Db.PeopleQuery2(peopleId)
                : DbUtil.Db.PeopleQuery(guid);

            if (!q.Any())
            {
                throw new Exception("no people in query");
            }
            var finaldoc = replacements.DocXReplacements(q.First());

            foreach (var p in q.Skip(1))
            {
                finaldoc.InsertParagraph().InsertPageBreakAfterSelf();
                var doc = replacements.DocXReplacements(p);
                finaldoc.InsertDocument(doc);
            }
            context.HttpContext.Response.Clear();
            context.HttpContext.Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            context.HttpContext.Response.AddHeader("Content-Disposition", $"attachment;filename={filename}-{DateTime.Now.ToSortableDateTime()}.docx");
            finaldoc.SaveAs(context.HttpContext.Response.OutputStream);
        }
Example #8
0
        /// <summary>
        /// 设置表格列宽(页面比例)
        /// </summary>
        /// <param name="fromPath"></param>
        /// <param name="tbl"></param>
        /// <param name="sPercent">各列所占表格的百分比</param>
        /// <param name="sPagePercent">表格所占页面的百分比</param>
        /// <returns></returns>
        public Table SetTableColWidth(string fromPath, Table tbl, string sPercent, string sPagePercent)
        {
            DocX doc = DocX.Load(fromPath);

            string[] aPercent = sPercent.Split(',');
            if (tbl.ColumnCount != aPercent.Length)
            {
                return(tbl);
            }
            double nPagePercent = Convert.ToDouble(sPagePercent) / 100;
            double sum_aPercent = 0.0;

            for (int i = 0; i < aPercent.Length; i++)
            {
                sum_aPercent += Convert.ToDouble(aPercent[i]);
            }
            float[] colWidths = new float[aPercent.Length];
            for (int i = 0; i < aPercent.Length; i++)
            {
                colWidths[i] = (float)(Convert.ToDouble(aPercent[i]) / sum_aPercent * nPagePercent * doc.PageWidth);
            }
            tbl.SetWidths(colWidths);

            tbl.Alignment = Alignment.center;
            tbl.AutoFit   = AutoFit.ColumnWidth;

            return(tbl);
        }
Example #9
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 #10
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 #11
0
        //added by LIUJIE 2017-09-18
        /// <summary>
        /// 插入图片及图片注释(对图片尺寸没有要求)
        /// </summary>
        /// <param name="oldPath">添加的doc路径</param>
        /// <param name="oPath">添加图片的数组</param>
        /// <param name="replaceFlag">替换符</param>
        /// <param name="oRemark">图片备注数组</param>
        public void AddWordPic(string oldPath, object[] oPath, string replaceFlag, object[] oRemark)
        {
            DocX      oldDocument = DocX.Load(oldPath);
            Paragraph ss          = null;

            Novacode.Image img = null;
            ss = GetParagraphByReplaceFlag(oldDocument, replaceFlag, "CENTER");
            ss.ReplaceText(replaceFlag, "");
            if (!(oPath == null || oRemark == null))
            {
                try
                {
                    string[] imagePath = classLims_NPOI.dArray2String1(oPath);
                    string[] remark    = classLims_NPOI.dArray2String1(oRemark);
                    for (int i = 0; i < imagePath.Length; i++)
                    {
                        img = oldDocument.AddImage(imagePath[i]);
                        Picture pic = img.CreatePicture();
                        ss.AppendPicture(pic);
                        pic.Height = Convert.ToInt32(Convert.ToDouble(pic.Height) / Convert.ToDouble(pic.Width) * Convert.ToDouble(oldDocument.PageWidth));
                        pic.Width  = Convert.ToInt32(Convert.ToDouble(oldDocument.PageWidth));
                        ss.AppendLine(remark[i] + "\n");
                        //ss.AppendLine("\n");
                        ss.Alignment = Alignment.center;
                    }
                }
                catch (System.InvalidOperationException e)
                {
                    classLims_NPOI.WriteLog(e, "");
                    return;
                }
            }
            oldDocument.Save();
            return;
        }
Example #12
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 #13
0
        public IHttpActionResult ApproveOrReject(bool approve, string fileFrom, string fileTo = "")
        {
            Configs config = new Configs();
            string  root   = config.BlogRoot + "\\";

            fileFrom = root + "\\" + config.ReviewFolder + "\\" + fileFrom;
            string response = "";

            fileFrom += ".docx";
            var document = DocX.Load(fileFrom);

            if (approve)
            {
                string fileName = fileFrom.Split('\\').Last();
                fileTo = root + fileTo + fileName;
                document.SaveAs(fileTo);
                response = "Approved";
                File.Delete(fileFrom);
            }
            else
            {
                document.Dispose();
                response = "Rejected";
                File.Delete(fileFrom);
            }

            return(Ok(response));
        }
        public void Test(string ofdQuestFileName, string ofdAnswerFileName)
        {
            using (var questDoc = DocX.Load(ofdQuestFileName))
            {
                foreach (var paragraph in questDoc.Paragraphs)
                {
                    foreach (var m in paragraph.MagicText)
                    {
                        var f = new Formatting {
                            UnderlineStyle = UnderlineStyle.doubleLine
                        };
                        paragraph.ReplaceText(m.text, m.text, false, RegexOptions.None, f);
                    }
                }
                questDoc.SaveAs($"{ofdQuestFileName}.magicTest");
            }
            return;

            using (FileStream stream = File.OpenRead(ofdQuestFileName))
            {
                XWPFDocument doc = new XWPFDocument(stream);
                //foreach (var para in doc.Paragraphs)
                //{
                //    if (para.Runs.Any())
                //    {
                //        var r = para.Runs.First();
                //        r.SetUnderline(UnderlinePatterns.Double);
                //    }
                //}
                FileStream out1 = new FileStream($"simple.{DateTime.Now.ToString("yyyyMMddHHmmss")}.docx", FileMode.Create);
                doc.Write(out1);
            }
        }
Example #15
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 #16
0
        public DocX InlocuiesteCuvinte()
        {
            //string template = @"D:\faculta\An4\SEM 1\PSSC\Teme\Tema2\doc generator\tema2final\AdeverintaMedicala.docx";
            string template = @"Reteta.docx";
            DocX   letter   = DocX.Load(template);

            // Perform the replace:
            letter.ReplaceText("%JUDEUL%", dateSpital.judet);
            letter.ReplaceText("%LOCALITATEA%", dateSpital.localitate);
            letter.ReplaceText("%UNITATEA SANITARA%", dateSpital.unitateSanitara);

            letter.ReplaceText("%GRATUIT%", gratuit);

            letter.ReplaceText("%NUME INTREG%", pacient.numePacient.toString());
            letter.ReplaceText("%SEX% ", pacient.sex);

            var varsta = pacient.CalculeazaVarsta().ToString();

            letter.ReplaceText("%VARSTA%", varsta);

            letter.ReplaceText("%JUDETUL%", pacient.adresa.judet);
            letter.ReplaceText("%LOCALITATEA%", pacient.adresa.localitate);
            letter.ReplaceText("%STRADA%", pacient.adresa.strada);
            letter.ReplaceText("%NUMAR STRADA%", pacient.adresa.nrStrada.ToString());

            letter.ReplaceText("%DIAGNOSTIC%", diagnostic);
            letter.ReplaceText("%NR RETETA%", nrReteta.ToString());
            letter.ReplaceText("%RETETA%", reteta);

            letter.ReplaceText("%DATA%", data.toString());

            return(letter);
        }
Example #17
0
        /// <summary>
        /// Load and change a document password protection.
        /// </summary>
        public static void ChangePasswordProtection()
        {
            Console.WriteLine("\tChangePasswordProtection()");

            // Load a password protected document.
            using (var document = DocX.Load(ProtectionSample.ProtectionSampleResourceDirectory + @"PasswordProtected.docx"))
            {
                // Check if the document is password protected.
                if (document.IsPasswordProtected)
                {
                    // Remove existing password protection.
                    document.RemovePasswordProtection("xceed");

                    // Set the document as read only and add a new password to unlock it.
                    document.AddPasswordProtection(EditRestrictions.readOnly, "words");
                }

                // Replace displayed text in document.
                document.ReplaceText("xceed", "words");

                // Save this document to disk.
                document.SaveAs(ProtectionSample.ProtectionSampleOutputDirectory + @"UpdatedPasswordProtected.docx", "words");
                Console.WriteLine("\tCreated: UpdatedPasswordProtected.docx\n");
            }
        }
Example #18
0
        //Sindicato
        private void PlantillaSindicato(string file, string newPath, int[] empleados)
        {
            Empleados emp = new Empleados();
            Puestos   ps  = new Puestos();

            foreach (var item in empleados)
            {
                using (var document = DocX.Load(file))
                {
                    var empleado = emp.GetEmpleadoById(item);
                    var contrato = emp.ObtenerContratoEmpleadoPorId(item);
                    var newDoc   = newPath + empleado.APaterno + "_" + empleado.AMaterno + "_" + empleado.Nombres + "_.docx";
                    document.ReplaceText("<<Empleado_FechaDeAlta>>", contrato.FechaAlta.ToString("dd/MM/yyyy"));
                    document.ReplaceText("<<Empleado_Paterno>>", empleado.APaterno);
                    document.ReplaceText("<<Empleado_Materno>>", empleado.AMaterno);
                    document.ReplaceText("<<Empleado_Nombres>>", empleado.Nombres);
                    document.ReplaceText("<<Empleado_Domicilio>>", empleado.Direccion);
                    document.ReplaceText("<<Empleado_RFC>>", empleado.RFC);
                    document.ReplaceText("<<Empleado_CURP>>", empleado.CURP);
                    var puesto = ps.GetPuesto(contrato.IdPuesto);
                    document.ReplaceText("<<Empleado_Puesto>>", puesto.Descripcion);


                    document.SaveAs(newDoc);
                }
            }
        }
Example #19
0
        public void Parse()
        {
            File.Copy(TemplateFile, TempFile, true);
            Doc = DocX.Load(TempFile);
            string        re = "{{.+?}}";
            List <string> es = Doc.FindUniqueByPattern(re, regexOptions);

            Expressions = es.Select(s => Expression <SCOPE> .Factory(s, new SCOPE())).ToList();
            Regex regex = new Regex(@"{{(.+)\[i\]");

            foreach (Expression <SCOPE> e in Expressions.ToList())
            {
                Match m = regex.Match(e.Raw);
                if (m.Success)
                {
                    string code = m.Groups[1].Value;
                    code += ".Count";
                    Expressions.Add(new Expression <SCOPE>(Scope)
                    {
                        Code = code
                    });
                    for (int i = 0; i <= NbIteration - 1; i++)
                    {
                        code = e.Code.Replace("[i]", "[" + i + "]");
                        Expressions.Add(new Expression <SCOPE>(Scope)
                        {
                            Code = code
                        });
                    }
                }
            }
        }
        private void MyFunc()
        {
            var list = new OpstiUsloviDa().Prep();

            foreach (var item in list)
            {
                if (item.Length > 3)
                {
                    var downloadDirectory = HttpRuntime.AppDomainAppPath + "Uslovi\\";
                    if (!Directory.Exists(downloadDirectory))
                    {
                        Directory.CreateDirectory(downloadDirectory);
                    }
                    var    outFileName     = string.Format("pu_{0}.docx", item);
                    string docTemplatePath = HttpRuntime.AppDomainAppPath + "Templates\\blank_0.docx";
                    string docOutputPath   = downloadDirectory + outFileName;
                    ////create copy of template so that we don't overwrite it
                    File.Copy(docTemplatePath, docOutputPath);
                    // Load a .docx file
                    using (DocX document = DocX.Load(docOutputPath))
                    {
                        var imetabela = item.Split('_')[0];
                        var stranici  = item.Split('_')[1];
                        foreach (var grupa in stranici.Split(';'))
                        {
                            int start = 0;
                            int stop  = 0;
                            if (grupa.Contains('-'))
                            {
                                start = int.Parse(grupa.Split('-')[0]);
                                stop  = int.Parse(grupa.Split('-')[1]);
                            }
                            else
                            {
                                start = stop = int.Parse(grupa);
                            }
                            for (int i = start; i <= stop; i++)
                            {
                                try
                                {
                                    Image image =
                                        document.AddImage(downloadDirectory + "izvod\\" + imetabela + "\\" + "uslovi_" +
                                                          i +
                                                          ".jpg");
                                    var picture   = image.CreatePicture(1100, 778);
                                    var paragraph = document.InsertParagraph("", false);
                                    paragraph.InsertPicture(picture);
                                    paragraph.Alignment = Alignment.center;
                                }
                                catch (Exception ex)
                                {
                                    Logger.Error(ex);
                                }
                            }
                        }
                        document.Save();
                    }
                }
            }
        }
Example #21
0
        static void WriteToDoc(string docPath, int clientId, string recoginzed, DateTime timeStamp)
        {
            DocX doc;

            if (!System.IO.File.Exists(docPath))
            {
                doc = DocX.Create(docPath);
            }
            else
            {
                doc = DocX.Load(docPath);
            }

            var headerFormat = new Formatting();

            headerFormat.FontFamily = new Font("Arial Black");
            headerFormat.Size       = 20;
            headerFormat.Bold       = true;

            doc.InsertParagraph($"client: {clientId}", false, headerFormat);

            var para = doc.InsertParagraph();

            para.Append($"@ {timeStamp.ToUniversalTime().ToString("s")} says: {recoginzed} ");

            doc.Save();
        }
Example #22
0
        public DocX InlocuiesteCuvinte()
        {
            string template = @"AdeverintaMedicala.docx";
            DocX   letter   = DocX.Load(template);

            // Perform the replace:
            letter.ReplaceText("%JUDEUL%", dateSpital.judet);
            letter.ReplaceText("%LOCALITATEA%", dateSpital.localitate);
            letter.ReplaceText("%UNITATEA SANITARA%", dateSpital.unitateSanitara);
            letter.ReplaceText("%CARNET DE SANATATE%", nrFisa.ToString());
            letter.ReplaceText("%NUME INTREG%", pacient.numePacient.toString());
            letter.ReplaceText("%SEX% ", pacient.sex);
            letter.ReplaceText("%ANUL%", pacient.dataNastere.an.ToString());
            letter.ReplaceText("%LUNA%", pacient.dataNastere.luna.ToString());
            letter.ReplaceText("%ZIUA%", pacient.dataNastere.zi.ToString());
            letter.ReplaceText("%JUDETUL%", pacient.adresa.judet);
            letter.ReplaceText("%LOCALITATEA%", pacient.adresa.localitate);
            letter.ReplaceText("%STRADA%", pacient.adresa.strada);
            letter.ReplaceText("%NUMAR STRADA%", pacient.adresa.nrStrada.ToString());
            letter.ReplaceText("%OCUPATIA%", pacient.ocupatie);
            letter.ReplaceText("%LOCUL DE MUNCA%", pacient.locMunca);
            letter.ReplaceText("%BOALA% ", afectiune);
            letter.ReplaceText("%RECOMANDARE%", recomandare);
            letter.ReplaceText("%SERIVRE%", servire);
            letter.ReplaceText("%AN ELIBERARE%", data.an.ToString());
            letter.ReplaceText("%LUNA ELIBERARE%", data.luna.ToString());
            letter.ReplaceText("%ZI ELIBERARE%", data.zi.ToString());

            return(letter);
        }
        public async Task <MemoryStream> ParseDocument(IList <DocumentPositionKeyValue> keyValues, string documentPath)
        {
            var documentTemplate = new MemoryStream();

            await using (var file = File.Open(documentPath, FileMode.OpenOrCreate))
            {
                await file.CopyToAsync(documentTemplate);
            }

            documentTemplate.Position = 0;
            var parsedDocument = new MemoryStream();

            using (var wordDocument = DocX.Load(documentTemplate))
            {
                foreach (var keyValue in keyValues)
                {
                    wordDocument.ReplaceText(keyValue.Key, keyValue.Value);
                }

                wordDocument.SaveAs(parsedDocument);
            }

            parsedDocument.Position = 0;
            return(parsedDocument);
        }
Example #24
0
        /// <summary>
        /// Load a document with bookmarks and replace the bookmark's text.
        /// </summary>
        public static void ReplaceText()
        {
            Console.WriteLine("\tReplaceBookmarkText()");

            // Load a document
            using (var document = DocX.Load(BookmarkSample.BookmarkSampleResourcesDirectory + @"DocumentWithBookmarks.docx"))
            {
                // Get the regular bookmark from the document and replace its Text.
                var regularBookmark = document.Bookmarks["regBookmark"];
                if (regularBookmark != null)
                {
                    regularBookmark.SetText("Regular Bookmark has been changed");
                }

                // Get the formatted bookmark from the document and replace its Text.
                var formattedBookmark = document.Bookmarks["formattedBookmark"];
                if (formattedBookmark != null)
                {
                    formattedBookmark.SetText("Formatted Bookmark has been changed");
                }

                document.SaveAs(BookmarkSample.BookmarkSampleOutputDirectory + @"ReplaceBookmarkText.docx");
                Console.WriteLine("\tCreated: ReplaceBookmarkText.docx\n");
            }
        }
Example #25
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 #26
0
        /// <summary>
        /// For each of the documents in the folder 'docs\',
        /// Replace the string a with the string b,
        /// Do this in Parrallel accross many CPU cores.
        /// </summary>
        static void ReplaceTextParallel()
        {
            Console.WriteLine("\tReplaceTextParallel()\n");
            const string a = "apple";
            const string b = "pear";

            // Directory containing many .docx documents.
            DirectoryInfo di = new DirectoryInfo(@"docs\");

            // Loop through each document in this specified direction.
            Parallel.ForEach
            (
                di.GetFiles(),
                currentFile =>
            {
                // Load the document.
                using (DocX document = DocX.Load(currentFile.FullName))
                {
                    // Replace text in this document.
                    document.ReplaceText(a, b);

                    // Save changes made to this document.
                    document.Save();
                }     // Release this document from memory.
            }
            );
            Console.WriteLine("\tCreated: None\n");
        }
Example #27
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 #28
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 #29
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();
        }
Example #30
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");
            }
        }