InsertTableAfterSelf() public method

Insert a new Table after this Table, this Table can be from this document or another document.
public InsertTableAfterSelf ( Table t ) : Table
t Table The Table t to be inserted
return Table
Ejemplo n.º 1
0
        private static Table CreateAndInsertInvoiceTableAfter(Table t, ref DocX document)
        {
            // Grab data from somewhere (Most likely a database)
            schooldbEntities DAO = new schooldbEntities();
            List<teacher> tlist = (from tt in DAO.teachers select tt).ToList<teacher>();

            /*
             * The trick to replacing one Table with another,
             * is to insert the new Table after the old one,
             * and then remove the old one.
             */
            Table invoice_table = t.InsertTableAfterSelf(tlist.Count + 1, 4);
            invoice_table.Design = TableDesign.LightShadingAccent1;

            #region Table title
            Formatting table_title = new Formatting();
            table_title.Bold = true;

            invoice_table.Rows[0].Cells[0].Paragraph.InsertText("Serial No.", false, table_title);
            invoice_table.Rows[0].Cells[0].Paragraph.Alignment = Alignment.center;
            invoice_table.Rows[0].Cells[1].Paragraph.InsertText("Employee Name", false, table_title);
            invoice_table.Rows[0].Cells[1].Paragraph.Alignment = Alignment.center;
            invoice_table.Rows[0].Cells[2].Paragraph.InsertText("Account No.", false, table_title);
            invoice_table.Rows[0].Cells[2].Paragraph.Alignment = Alignment.center;
            invoice_table.Rows[0].Cells[3].Paragraph.InsertText("Salary", false, table_title);
            invoice_table.Rows[0].Cells[3].Paragraph.Alignment = Alignment.center;
            #endregion

            // Loop through the rows in the Table and insert data from the data source.
            for (int row = 1; row < tlist.Count; row++)
            {

                    Paragraph cell_paragraph = invoice_table.Rows[row].Cells[0].Paragraph;
                    cell_paragraph.InsertText(row.ToString(), false);

                    cell_paragraph = invoice_table.Rows[row].Cells[1].Paragraph;
                    cell_paragraph.InsertText(tlist[row - 1].TeacherName.ToString(), false);

                    cell_paragraph = invoice_table.Rows[row].Cells[2].Paragraph;
                    cell_paragraph.InsertText(tlist[row - 1].Account_Number.ToString(), false);

                    cell_paragraph = invoice_table.Rows[row].Cells[3].Paragraph;
                    cell_paragraph.InsertText(tlist[row - 1].BasicSalary.ToString(), false);

            }

            // Let the tables coloumns expand to fit its contents.
            invoice_table.AutoFit = AutoFit.Contents;

            // Center the Table
            invoice_table.Alignment = Alignment.center;

            // Return the invloce table now that it has been created.
            return invoice_table;
        }
Ejemplo n.º 2
0
        private static Table CreateAndInsertInvoiceTableAfter(Table t, ref DocX document)
        {
            // Grab data from somewhere (Most likely a database)
            DataTable data = GetDataFromDatabase();

            /*
             * The trick to replacing one Table with another,
             * is to insert the new Table after the old one,
             * and then remove the old one.
             */
            Table invoice_table = t.InsertTableAfterSelf(data.Rows.Count + 1, data.Columns.Count);
            invoice_table.Design = TableDesign.LightShadingAccent1;

            #region Table title
            Formatting table_title = new Formatting();
            table_title.Bold = true;

            invoice_table.Rows[0].Cells[0].Paragraphs[0].InsertText("Description", false, table_title);
            invoice_table.Rows[0].Cells[0].Paragraphs[0].Alignment = Alignment.center;
            invoice_table.Rows[0].Cells[1].Paragraphs[0].InsertText("Hours", false, table_title);
            invoice_table.Rows[0].Cells[1].Paragraphs[0].Alignment = Alignment.center;
            invoice_table.Rows[0].Cells[2].Paragraphs[0].InsertText("Rate", false, table_title);
            invoice_table.Rows[0].Cells[2].Paragraphs[0].Alignment = Alignment.center;
            invoice_table.Rows[0].Cells[3].Paragraphs[0].InsertText("Amount", false, table_title);
            invoice_table.Rows[0].Cells[3].Paragraphs[0].Alignment = Alignment.center;
            #endregion

            // Loop through the rows in the Table and insert data from the data source.
            for (int row = 1; row < invoice_table.RowCount; row++)
            {
                for (int cell = 0; cell < invoice_table.Rows[row].Cells.Count; cell++)
                {
                    Paragraph cell_paragraph = invoice_table.Rows[row].Cells[cell].Paragraphs[0];
                    cell_paragraph.InsertText(data.Rows[row - 1].ItemArray[cell].ToString(), false);
                }
            }

            // We want to fill in the total by suming the values from the amount column.
            Row total = invoice_table.InsertRow();
            total.Cells[0].Paragraphs[0].InsertText("Total:", false);
            Paragraph total_paragraph = total.Cells[invoice_table.ColumnCount - 1].Paragraphs[0];

            /*
             * Lots of people are scared of LINQ,
             * so I will walk you through this line by line.
             *
             * invoice_table.Rows is an IEnumerable<Row> (i.e a collection of rows), with LINQ you can query collections.
             * .Where(condition) is a filter that you want to apply to the items of this collection.
             * My condition is that the index of the row must be greater than 0 and less than RowCount.
             * .Select(something) lets you select something from each item in the filtered collection.
             * I am selecting the Text value from each row, for example €100, then I am remove the €,
             * and then I am parsing the remaining string as a double. This will return a collection of doubles,
             * the final thing I do is call .Sum() on this collection which return one double the sum of all the doubles,
             * this is the total.
             */
            double totalCost =
            (
                invoice_table.Rows
                .Where((row, index) => index > 0 && index < invoice_table.RowCount - 1)
                .Select(row => double.Parse(row.Cells[row.Cells.Count() - 1].Paragraphs[0].Text.Remove(0, 1)))
            ).Sum();

            // Insert the total calculated above using LINQ into the total Paragraph.
            total_paragraph.InsertText(string.Format("€{0}", totalCost), false);

            // Let the tables columns expand to fit its contents.
            invoice_table.AutoFit = AutoFit.Contents;

            // Center the Table
            invoice_table.Alignment = Alignment.center;

            // Return the invloce table now that it has been created.
            return invoice_table;
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Se utiliza para crear el CV que se carga a la BD.
        /// </summary>
        /// <param name="idCV"></param>
        /// <param name="rutaPlantilla"></param>
        /// <returns></returns>
        public MemoryStream CrearCurriculum(int idCV, string rutaPlantilla)
        {
            LNPlantillaCV lnPlantilla = new LNPlantillaCV();
            DataSet       Result      = lnPlantilla.ObtenerDatosParaPlantilla(idCV);

            System.Data.DataTable Person               = Result.Tables[0];
            System.Data.DataTable Education            = Result.Tables[1];
            System.Data.DataTable Experience           = Result.Tables[2];
            System.Data.DataTable AditionalInformation = Result.Tables[3];

            MemoryStream stream = new MemoryStream();

            Mustache mustache     = new Mustache();
            string   blockPattern = @"{{><model>}}";

            using (FileStream fileStream = System.IO.File.OpenRead(rutaPlantilla))
            {
                stream.SetLength(fileStream.Length);
                fileStream.Read(stream.GetBuffer(), 0, (int)fileStream.Length);
            }

            using (DocX doc = DocX.Load(stream))
            {
                dynamic template = new Template(rutaPlantilla)
                                   .Build()
                                   .Compile();

                #region person

                object person = new
                {
                    // Informacion basica
                    firstname        = Convert.ToString(Person.Rows[0]["Nombres"]).ToUpper(),
                    lastname         = Convert.ToString(Person.Rows[0]["Apellidos"]).ToUpper(),
                    document         = Convert.ToString(Person.Rows[0]["NumeroDocumento"]),
                    documentType     = Convert.ToString(Person.Rows[0]["TipoDocumento"]),
                    address          = Convert.ToString(Person.Rows[0]["Direccion"]),
                    district         = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Convert.ToString(Person.Rows[0]["DireccionDistrito"])),
                    celphone         = Convert.ToString(Person.Rows[0]["TelefonoCelular"]),
                    email            = Convert.ToString(Person.Rows[0]["CorreoElectronico"]),
                    emailAlternative = Convert.ToString(Person.Rows[0]["CorreoElectronico2"]),
                    profile          = Convert.ToString(Person.Rows[0]["Perfil"]),
                    birthdate        = Convert.ToString(Person.Rows[0]["FechaNacimiento"])
                };

                if (Convert.ToBoolean(template.person.inlines.Count))
                {
                    foreach (string i in template.person.inlines)
                    {
                        doc.ReplaceText(i, mustache.Compile(i).Render(new { person = person }));
                    }
                }

                #endregion

                #region education

                object         education;
                string         educationPattern = blockPattern.Replace("<model>", "education");
                Novacode.Table educationWrapper;

                try
                {
                    educationWrapper = doc
                                       .Tables
                                       .Where(e => e.Paragraphs[0].Text.Contains(educationPattern))
                                       .ToList()[0];

                    // Clean reference template
                    educationWrapper.Rows[1].Remove();

                    foreach (DataRow data in Education.Rows)
                    {
                        educationWrapper.InsertTableAfterSelf(template.education.blocks[1]);

                        education = new
                        {
                            institute = Convert.ToString(data["Institucion"]),
                            study     = Convert.ToString(data["Estudio"]),
                            period    = ConvertirMes(Convert.ToInt32(data["FechaInicioMes"])) + Convert.ToString(data["FechaInicioAno"]).Substring(2, 2) +
                                        "-" + (data["FechaFinMes"] == DBNull.Value && data["FechaFinAno"] == DBNull.Value
                                    ? "Cont"
                                    : ConvertirMes(Convert.ToInt32(data["FechaFinMes"])) + Convert.ToString(data["FechaFinAno"]).Substring(2, 2))
                        };

                        foreach (string i in template.education.inlines)
                        {
                            doc.ReplaceText(i, mustache.Compile(i).Render(new { education = education }));
                        }
                    }

                    // Clean reference pointer
                    educationWrapper.Rows[0].Remove();
                }
                catch (Exception e) { }

                #endregion

                #region experience

                string         experiencePattern = blockPattern.Replace("<model>", "experience");
                Novacode.Table experienceWrapper;

                Dictionary <string, dynamic>        enterprises = new Dictionary <string, dynamic>();
                Dictionary <string, List <object> > experiences = new Dictionary <string, List <object> >();
                string[] enterpriseFields = new string[] { "Ciudad", "DescripcionEmpresa", "PaisDescripcion", "Empresa" };

                System.Data.DataTable Enterprises = Experience.DefaultView.ToTable(true, enterpriseFields);
                foreach (DataRow enterprise in Enterprises.Rows)
                {
                    List <object> aux = new List <object>();
                    int           timeOfExperience = 0;

                    System.Data.DataTable experiencesOfEnterprise = Experience.Select("Empresa = '" + Convert.ToString(enterprise["Empresa"]) + "'").CopyToDataTable();
                    foreach (DataRow data in experiencesOfEnterprise.Rows)
                    {
                        string period      = String.Empty;
                        string periodStart = String.Empty;
                        string periodEnd   = String.Empty;

                        periodStart = ConvertirMes(Convert.ToInt32(data["FechaInicioCargoMes"])) +
                                      Convert.ToString(data["FechaInicioCargoAno"]).Substring(2, 2);

                        periodEnd = (data["FechaFinCargoMes"] == DBNull.Value && data["FechaFinCargoAno"] == DBNull.Value)
                            ? "Cont"
                            : ConvertirMes(Convert.ToInt32(data["FechaFinCargoMes"])) +
                                    Convert.ToString(data["FechaFinCargoAno"]).Substring(2, 2);

                        period = String.Format("{0}-{1}", periodStart, periodEnd);

                        aux.Add(new
                        {
                            period            = period,
                            office            = Convert.ToString(data["NombreCargo"]),
                            officeDescription = Convert.ToString(data["DescripcionCargo"])
                        });

                        int yearStart  = Convert.ToInt32(data["FechaInicioCargoAno"]);
                        int monthStart = Convert.ToInt32(data["FechaInicioCargoMes"]);
                        int yearEnd    = (data["FechaFinCargoAno"] == DBNull.Value)
                            ? DateTime.Now.Year
                            : Convert.ToInt32(data["FechaFinCargoAno"]);
                        int monthEnd = (data["FechaFinCargoMes"] == DBNull.Value)
                            ? DateTime.Now.Month
                            : Convert.ToInt32(data["FechaFinCargoMes"]);

                        timeOfExperience += (yearEnd - yearStart) * 12 + monthEnd + 1 - monthStart;
                    }

                    enterprises.Add(Convert.ToString(enterprise["Empresa"]), new
                    {
                        enterprise                 = Convert.ToString(enterprise["Empresa"]),
                        enterpriseDescription      = Convert.ToString(enterprise["DescripcionEmpresa"]),
                        enterpriseTimeOfExperience = String.Format("({0} años, {1} meses)", Math.Truncate(timeOfExperience / 12.0), timeOfExperience % 12),
                        enterpriseCountry          = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Convert.ToString(enterprise["PaisDescripcion"])),
                        enterpriseCity             = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Convert.ToString(enterprise["Ciudad"]))
                    });
                    experiences.Add(Convert.ToString(enterprise["Empresa"]), aux);
                }

                try
                {
                    experienceWrapper = doc
                                        .Tables
                                        .Where(e => e.Paragraphs[0].Text.Contains(experiencePattern))
                                        .ToList()[0];

                    // Clean reference template
                    experienceWrapper.Rows[1].Remove();

                    foreach (var data in enterprises)
                    {
                        Novacode.Table enterpriseWrapper = experienceWrapper.InsertTableAfterSelf(template.experience.blocks[1]);

                        // Render enterprise info
                        for (int i = 0; i < enterpriseFields.Count() + 1; i++)
                        {
                            doc.ReplaceText(
                                template.experience.inlines[i],
                                mustache
                                .Compile(template.experience.inlines[i])
                                .Render(new
                            {
                                experience = enterprises[data.Key]
                            })
                                );
                        }

                        Novacode.Table enterpriseExperienceWrapper = enterpriseWrapper.Rows[1].Tables[0];
                        foreach (object experience in experiences[data.Key])
                        {
                            enterpriseExperienceWrapper.InsertTableAfterSelf(template.experience.blocks[2]);

                            foreach (string i in template.experience.inlines)
                            {
                                doc.ReplaceText(i, mustache.Compile(i).Render(new { experience = experience }));
                            }
                        }

                        enterpriseExperienceWrapper.Rows[0].Remove();
                    }

                    // Clean reference pointer
                    experienceWrapper.Rows[0].Remove();
                }
                catch (Exception e) { }

                #endregion

                #region aditional information

                object         aditionalInformation;
                string         aditionalInformationPattern = blockPattern.Replace("<model>", "aditionalInformation");
                Novacode.Table aditionalInformationWrapper;

                try
                {
                    aditionalInformationWrapper = doc
                                                  .Tables
                                                  .Where(e => e.Paragraphs[0].Text.Contains(aditionalInformationPattern))
                                                  .ToList()[0];

                    // Clean reference template
                    aditionalInformationWrapper.Rows[1].Remove();

                    foreach (DataRow data in AditionalInformation.Rows)
                    {
                        aditionalInformationWrapper.InsertTableAfterSelf(template.aditionalInformation.blocks[1]);

                        aditionalInformation = new
                        {
                            knowledge = Convert.ToString(data["Conocimiento"]),
                            level     = Convert.ToString(data["NivelConocimientoDescripcion"]),
                            institute = Convert.ToString(data["InstituciónDeEstudio"]),
                            date      = Convert.ToString(data["FechaConocimientoHastaAno"])
                        };

                        foreach (string i in template.aditionalInformation.inlines)
                        {
                            doc.ReplaceText(i, mustache.Compile(i).Render(new { aditionalInformation = aditionalInformation }));
                        }
                    }

                    // Clean reference pointer
                    aditionalInformationWrapper.Rows[0].Remove();
                }
                catch (Exception e) { }

                #endregion

                doc.Save();
            }

            return(stream);
        }