A text formatting.
Inheritance: IComparable
Exemplo n.º 1
0
        public static Formatting Parse(XElement rPr)
        {
            Formatting formatting = new Formatting();

            // Build up the Formatting object.
            foreach (XElement option in rPr.Elements())
            {
                switch (option.Name.LocalName)
                {
                    case "lang": formatting.Language = new CultureInfo(option.GetAttribute(XName.Get("val", DocX.w.NamespaceName), null) ?? option.GetAttribute(XName.Get("eastAsia", DocX.w.NamespaceName), null) ?? option.GetAttribute(XName.Get("bidi", DocX.w.NamespaceName))); break;
                    case "spacing": formatting.Spacing = Double.Parse(option.GetAttribute(XName.Get("val", DocX.w.NamespaceName))) / 20.0; break;
                    case "position": formatting.Position = Int32.Parse(option.GetAttribute(XName.Get("val", DocX.w.NamespaceName))) / 2; break;
                    case "kern": formatting.Position = Int32.Parse(option.GetAttribute(XName.Get("val", DocX.w.NamespaceName))) / 2; break;
                    case "w": formatting.PercentageScale = Int32.Parse(option.GetAttribute(XName.Get("val", DocX.w.NamespaceName))); break;
                    case "rFonts": break;
                    case "vanish": formatting.hidden = true; break;
                    case "b": formatting.Bold = true; break;
                    case "i": formatting.Italic = true; break;

                    default: break;
                }
            }

            return formatting;
        }
Exemplo n.º 2
0
        public static void Main(string[] args)
        {
            string pictureFileName = @"..\..\rpg-game.png";
            string textFileName = @"..\..\text.txt";
            string wordDocument = @"..\..\WordDocument.doc";

            var headLineFormat = new Formatting();
            headLineFormat.FontFamily = new System.Drawing.FontFamily("Arial Black");
            headLineFormat.Size = 18D;
            headLineFormat.Position = 12;

            var paraFormat = new Formatting();
            paraFormat.FontFamily = new System.Drawing.FontFamily("Calibri");
            paraFormat.Size = 10D;

            // Create the document in memory:
            var doc = DocX.Create(wordDocument);

            // Insert the now text obejcts;
            doc.InsertParagraph(textFileName, false, headLineFormat);
            doc.InsertParagraph(wordDocument, false, paraFormat);

            // Save to the output directory:
            doc.Save();

            // Open in Word:
            Process.Start("WINWORD.EXE", wordDocument);
        }
Exemplo n.º 3
0
        static void Main()
        {
            string fileName = @"C:\Users\Viktor\Desktop\DocXExample.docx";
            string headlineText = "Constitution of the United States";
            string paraOne = ""
                + "We the People of the United States, in Order to form a more perfect Union, "
                + "establish Justice, insure domestic Tranquility, provide for the common defence, "
                + "promote the general Welfare, and secure the Blessings of Liberty to ourselves "
                + "and our Posterity, do ordain and establish this Constitution for the United "
                + "States of America.";

            // A formatting object for our headline:
            var headLineFormat = new Formatting();
            headLineFormat.FontFamily = new System.Drawing.FontFamily("Arial Black");
            headLineFormat.Size = 18D;
            headLineFormat.Position = 12;

            // A formatting object for our normal paragraph text:
            var paraFormat = new Formatting();
            paraFormat.FontFamily = new System.Drawing.FontFamily("Calibri");
            paraFormat.Size = 10D;

            // Create the document in memory:
            var doc = DocX.Create(fileName);

            // Insert the now text obejcts;
            doc.InsertParagraph(headlineText, false, headLineFormat);
            doc.InsertParagraph(paraOne, false, paraFormat);

            // Save to the output directory:
            doc.Save();

            // Open in Word:
            Process.Start("WINWORD.EXE", fileName);
        }
Exemplo n.º 4
0
 public DocX AddPar(string text=null)
 {
     Formatting par = new Formatting();
     par.Size = 14;
     this.document.InsertParagraph(text, false, par).Alignment = Alignment.left;
     return this.Document;
 }
Exemplo n.º 5
0
 public void CreateDocFizicko()
 {
     string fileName = @"Правни лица/" + Business.BusinessName + "/" + Employee.EmployeeNameSurname + "/" + Employee.EmployeeNameSurname + "_" + Review.ReviewID + "(ZA_VRABOTEN).docx";
     var doc = DocX.Load("templ/templ(ZAVRABOTEN).docx");
     doc.ReplaceText("<ime na vraboten>", Employee.EmployeeNameSurname);
     doc.ReplaceText("<datum na ragjanje>", Employee.EmployeeBirthDate.ToShortDateString());
     doc.ReplaceText("<професија>", Employee.EmployeeProffesion);
     doc.ReplaceText("<rab mesto>", Employee.EmployeeWorks);
     doc.ReplaceText("<datum pregled>", Review.ReviewDate.ToShortDateString());
     Formatting newf = new Formatting();
     newf.UnderlineStyle = UnderlineStyle.singleLine;
     newf.Bold = true;
     newf.Size = 14;
     var tip_pregled = "";
     switch (Review.ReviewType)
     {
         case "1":
             tip_pregled = "СИСТЕМАТСКИ";
             break;
         case "2":
             tip_pregled = "ПЕРИОДИЧЕН";
             break;
         case "3":
             tip_pregled = "ПЕРИОДИЧЕН";
             break;
         case "4":
             tip_pregled = "ПЕРИОДИЧЕН";
             break;
         case "5":
             tip_pregled = "НАСОЧЕН";
             break;
     }
     doc.ReplaceText(tip_pregled, tip_pregled, false, System.Text.RegularExpressions.RegexOptions.None, newf);
     doc.SaveAs(fileName);
 }
Exemplo n.º 6
0
        public override void Change()
        {
            base.Change();
            var doc = DocX.Load(FileName);
            string headlineText = "5 фундаментальных правил успеха разработчика ";
            StringBuilder paraOne = new StringBuilder();
            paraOne.AppendLine("1. Не изобретайте колесо");
            paraOne.AppendLine("2. Не тратьте время на код, сосредоточьтесь на скорейшем завершении проекта");
            paraOne.AppendLine("3. Обеспечьте техническую поддержку кода ");
            paraOne.AppendLine("4. Пользуйтесь правом возврата денег при отсутствии ТП");
            paraOne.AppendLine("5. Проверяйте коды и модули на наличие угроз и уязвимостей");

            var headLineFormat = new Novacode.Formatting();
            headLineFormat.FontFamily = new System.Drawing.FontFamily("Times New Roman");
            headLineFormat.Size = 18D;
            headLineFormat.Position = 12;

            var paraFormat = new Novacode.Formatting();
            paraFormat.FontFamily = new System.Drawing.FontFamily("Courier New");
            paraFormat.Size = 10D;

            doc.InsertParagraph("paragraph 1");
            doc.InsertParagraph(headlineText, false, headLineFormat);
            doc.InsertParagraph(paraOne.ToString(), false, paraFormat);
            doc.Save();
            Save();
        }
 private void RenderParagraph(string value, Formatting formatting)
 {
     if (!String.IsNullOrWhiteSpace(value))
     {
         _wordDocument.InsertParagraph(value, false, formatting);
     }
 }
Exemplo n.º 8
0
        private void insertarGraficoBarra(DocX doc, Empresa empresa, string strDirectorio)
        {
            var RVFormat = new Novacode.Formatting();

            RVFormat.FontFamily = new System.Drawing.FontFamily("Calibri");
            RVFormat.Size       = 12D;
            RVFormat.Bold       = true;
            Paragraph pTit = doc.InsertParagraph("Recursos Valiosos " + empresa.NombreEmpresa.ToUpper(), false, RVFormat);

            pTit.Alignment = Alignment.left;

            var RVParrafo = new Novacode.Formatting();

            RVParrafo.FontFamily = new System.Drawing.FontFamily("Calibri");
            RVParrafo.Size       = 12D;
            RVParrafo.Position   = 3;
            Paragraph pParr = doc.InsertParagraph("Se definen los recursos físicos, organizacionales e intangibles con los que cuenta " + empresa.NombreEmpresa.ToUpper() + ". Los recursos definidos son evaluados por parte del equipo técnico – gerencial desde la perspectiva de inimitable, durabilidad, apropiación, sustitución y superioridad competitiva.", false, RVParrafo);

            pParr.Alignment = Alignment.left;

            string strGrafico = CrearGraficoBarra(empresa, strDirectorio);

            Novacode.Image i    = doc.AddImage(strGrafico);
            Picture        p    = i.CreatePicture();
            Paragraph      pImg = doc.InsertParagraph("").AppendPicture(p);

            pImg.Alignment = Alignment.center;
        }
Exemplo n.º 9
0
        /// <summary>
        /// Crea la tabla de recursos valiosos
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="empresa"></param>
        private void insertarRecursosValiosos(DocX doc, Empresa empresa)
        {
            List <RecursoValioso> listadoRecursoValioso = MatrizBO.ConsultarRecursosValiosos(empresa.IdEmpresa);
            int cantidadRecursos = listadoRecursoValioso.Count;
            var RVParrafo        = new Novacode.Formatting();

            RVParrafo.FontFamily = new System.Drawing.FontFamily("Calibri");
            RVParrafo.Size       = 12D;
            RVParrafo.Position   = 3;

            Paragraph pParr = doc.InsertParagraph("En este sentido se identifican " + cantidadRecursos + " recursos por encima del promedio, los cuales se convierten en valiosos y se listan a continuación", false, RVParrafo);

            pParr.Alignment = Alignment.left;

            Table tab = doc.AddTable(cantidadRecursos + 1, 2);

            tab.AutoFit   = AutoFit.Contents;
            tab.Alignment = Alignment.center;
            tab.Design    = TableDesign.ColorfulGridAccent1;
            tab.Rows[0].Cells[0].Paragraphs.First().Append("Recurso Valioso");
            tab.Rows[0].Cells[0].Paragraphs.First().Alignment = Alignment.center;
            tab.Rows[0].Cells[0].Paragraphs.First().Bold();
            tab.Rows[0].Cells[1].Paragraphs.First().Append("Observaciones");
            tab.Rows[0].Cells[1].Paragraphs.First().Alignment = Alignment.center;
            tab.Rows[0].Cells[1].Paragraphs.First().Bold();

            for (int i = 0; i < cantidadRecursos; i++)
            {
                RecursoValioso recursoValioso = listadoRecursoValioso[i];
                tab.Rows[i + 1].Cells[0].Paragraphs.First().Append(recursoValioso.NombreRecurso);
            }
            doc.InsertTable(tab);
        }
Exemplo n.º 10
0
        private string CreateDoc( ) {
            var fileName = Seged.Seged.CreateFileName(versenyAdatok.VersenysorozatAzonosito, versenyAdatok.Azonosito,
                DokumentumTipus.Startlista.BeiroLap);
                
            document = DocX.Create( fileName );
            document.MarginBottom = 10;
            document.AddHeaders( );

            #region Cimbekezdes
            var titleFormat = new Formatting {Size = 10D, Position = 1, Spacing = 5, Bold = true};
            var header = document.Headers.odd;
            var title = header.InsertParagraph();

            title.Append( Feliratok.HeadLine.Beirolap);
            title.Alignment = Alignment.center;
            titleFormat.Size = 10D;
            title.AppendLine( Feliratok.Tulajdonos );
            title.AppendLine( );
            title.Bold( );
            titleFormat.Position = 12;
            #endregion

            VersenyTablazat( );
            InduloTablazat( );
            EredmenyTablazat( );
            AlairasTablazat( );

            try { document.Save( ); } catch( System.Exception ) { MessageBox.Show( "A dokumentum meg van nyitva!", "Nevezési lista", MessageBoxButton.OK, MessageBoxImage.Error ); }
            return fileName;
        }
Exemplo n.º 11
0
 public DocX AddHead(string text)
 {
     Formatting head=new Formatting();
     head.Size=25;
     head.Bold = true;
     this.document.InsertParagraph(text,false,head).Alignment = Alignment.center;
     return this.Document;
 }
Exemplo n.º 12
0
        private void InitializeIdeaFormatting()
        {
            Tag = new Formatting();

            Tag.Italic = true;

            IdeaText = new Formatting();

            IdeaComment = new Formatting();
        }
Exemplo n.º 13
0
 public DocX BoldItalic()
 {
     Formatting par=new Formatting();
     par.Bold=true;
     par.Size = 14;
     
     this.Document.ReplaceText("role playing game", "role playing game",false,RegexOptions.None,par,null,MatchFormattingOptions.ExactMatch);
     this.Document.ReplaceText("grand prize!","grand prize!",false,RegexOptions.None,par,null,MatchFormattingOptions.ExactMatch);
     return this.Document;
 }
Exemplo n.º 14
0
 private static void CreateHeader(DocX doc)
 {
     string headerText = "SoftUni OOP Game Contest";
     var headerFormat = new Formatting();
     headerFormat.FontFamily = new FontFamily("Tahoma");
     headerFormat.Size = 18D;
     headerFormat.Position = 12;
     var header = doc.InsertParagraph(headerText, false, headerFormat);
     header.Alignment = Alignment.center;
 }
Exemplo n.º 15
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;
        }
Exemplo n.º 16
0
        private void AddHeader( ) {
            var titleFormat = new Formatting {Size = 14D, Position = 1, Spacing = 5, Bold = true};

            Document.AddHeaders( );
            var firstPageHeader = Document.Headers.first;

            var title = firstPageHeader.InsertParagraph();
            title.Append( Feliratok.HeadLine.NevezesiLista );
            title.Alignment = Alignment.center;
            titleFormat.Size = 10D;
            title.AppendLine( Feliratok.Tulajdonos );
            title.AppendLine( );
            title.Bold( );
            titleFormat.Position = 12;
        }
Exemplo n.º 17
0
        public DocX CreateLandscapePart()
        {
            System.IO.MemoryStream ms2 = new System.IO.MemoryStream();
            DocX document2 = DocX.Create(ms2);
            document2.PageLayout.Orientation = Novacode.Orientation.Landscape;

            var titleStyle = new Formatting();
            titleStyle.Size = 12;
            titleStyle.Bold = true;
            titleStyle.FontFamily = new System.Drawing.FontFamily("Times New Roman");

            Paragraph p = document2.InsertParagraph("7. РЕЗУЛТАТИ ОТ ИЗПИТВАНЕ", false, titleStyle);
            p.IndentationBefore = 2;

            return document2;
        }
Exemplo n.º 18
0
        private void AddHeader( ) {
            var titleFormat = new Formatting();
            titleFormat.Size = 14D;
            titleFormat.Position = 1;
            titleFormat.Spacing = 5;
            titleFormat.Bold = true;

            var header = document.Headers.odd;

            var title = header.InsertParagraph();
            title.Append( Feliratok.HeadLine.Csapatlista );
            title.Alignment = Alignment.center;
            titleFormat.Size = 10D;
            title.AppendLine( Seged.Feliratok.Tulajdonos );
            title.AppendLine( );
            title.Bold( );
            titleFormat.Position = 12;
        }
Exemplo n.º 19
0
        private void AddHeader( ) {
            var titleFormat = new Formatting( );
            titleFormat.Size = 14D;
            titleFormat.Position = 1;
            titleFormat.Spacing = 5;
            titleFormat.Bold = true;

            document.AddHeaders( );
            var FirstPageHeader = document.Headers.first;

            var title = FirstPageHeader.InsertParagraph();
            title.Append( Seged.Feliratok.HeadLine.Hianyzoklista );
            title.Alignment = Alignment.center;
            titleFormat.Size = 10D;
            title.AppendLine( Seged.Feliratok.Tulajdonos );
            title.AppendLine( );
            title.Bold( );
            titleFormat.Position = 12;
        }
Exemplo n.º 20
0
        private void ingresarEquipoTrabajo(DocX doc, List <RolesInforme> rolesInforme)
        {
            // Titulo Equipo de Trabajo:
            doc.InsertParagraph();
            doc.InsertParagraph();
            doc.InsertParagraph();
            var equipoTrabajoFormat = new Novacode.Formatting();

            equipoTrabajoFormat.FontFamily = new System.Drawing.FontFamily("Calibri");
            equipoTrabajoFormat.Size       = 12D;
            equipoTrabajoFormat.Bold       = true;
            Paragraph pTit = doc.InsertParagraph("Equipo de Trabajo", false, equipoTrabajoFormat);

            pTit.Alignment = Alignment.center;

            doc.InsertParagraph();
            doc.InsertParagraph();
            doc.InsertParagraph();

            Table tab = doc.AddTable(rolesInforme.Count + 1, 3);

            tab.AutoFit   = AutoFit.Window;
            tab.Alignment = Alignment.center;
            tab.Design    = TableDesign.ColorfulGridAccent1;
            tab.Rows[0].Cells[0].Paragraphs.First().Append("Nombre");
            tab.Rows[0].Cells[0].Paragraphs.First().Alignment = Alignment.center;
            tab.Rows[0].Cells[0].Paragraphs.First().Bold();
            tab.Rows[0].Cells[1].Paragraphs.First().Append("Cargo/Rol");
            tab.Rows[0].Cells[1].Paragraphs.First().Alignment = Alignment.center;
            tab.Rows[0].Cells[1].Paragraphs.First().Bold();
            tab.Rows[0].Cells[2].Paragraphs.First().Append("Fecha");
            tab.Rows[0].Cells[2].Paragraphs.First().Alignment = Alignment.center;
            tab.Rows[0].Cells[2].Paragraphs.First().Bold();
            for (int i = 0; i < rolesInforme.Count; i++)
            {
                RolesInforme rolInforme = rolesInforme[i];
                tab.Rows[i + 1].Cells[0].Paragraphs.First().Append(rolInforme.NombreParticipante);
                tab.Rows[i + 1].Cells[1].Paragraphs.First().Append(rolInforme.Rol);
                tab.Rows[i + 1].Cells[2].Paragraphs.First().Append(rolInforme.Fecha);
            }
            doc.InsertTable(tab);
        }
Exemplo n.º 21
0
        private static void CreateFooter(DocX doc)
        {
            var footerFormat = new Formatting();
            footerFormat.FontFamily = new FontFamily("Tahoma");

            footerFormat.Size = 10D;
            var p = doc.InsertParagraph("The top 3 teams will receive a ", false, footerFormat);
            p.Alignment = Alignment.center;

            footerFormat.Bold = true;
            p.InsertText("SPECTACULAR ", false, footerFormat);

            footerFormat.Bold = false;
            p.InsertText("prize:\n");

            footerFormat.Bold = true;
            footerFormat.UnderlineStyle = UnderlineStyle.singleLine;
            footerFormat.FontColor = System.Drawing.Color.MediumBlue;
            footerFormat.Size = 14D;
            p.InsertText("A HANDSHAKE FROM NAKOV", false, footerFormat);
        }
Exemplo n.º 22
0
    public void CreateNewDocByDocx(string resumsPath, string ResumContent)
    {
        DocxToText1 docTT = new DocxToText1();

        try
        {
            string fileName = resumsPath;
            using (DocX document = DocX.Create(fileName))
            {
                Novacode.Paragraph remainingpara = document.InsertParagraph();
                remainingpara.Append(ResumContent);
                Novacode.Formatting para_formatting = new Novacode.Formatting();
                para_formatting.Bold = false;
                para_formatting.Size = 9;
                document.InsertSection();
                document.SaveAs(fileName);
            }
        }
        catch (Exception ex)
        {
        }
    }
Exemplo n.º 23
0
        public virtual Paragraph InsertParagraph(int index, string text, bool trackChanges, Formatting formatting)
        {
            Paragraph newParagraph = new Paragraph(Document, new XElement(DocX.w + "p"), index);
            newParagraph.InsertText(0, text, trackChanges, formatting);

            Paragraph firstPar = HelperFunctions.GetFirstParagraphEffectedByInsert(Document, index);

            if (firstPar != null)
            {
                XElement[] splitParagraph = HelperFunctions.SplitParagraph(firstPar, index - firstPar.startIndex);

                firstPar.Xml.ReplaceWith
                (
                    splitParagraph[0],
                    newParagraph.Xml,
                    splitParagraph[1]
                );
            }

            else
                Xml.Add(newParagraph);

            GetParent(newParagraph);

            return newParagraph;
        }
Exemplo n.º 24
0
        private void AddHeader( Header header ) {
            var titleFormat = new Formatting();
            titleFormat.Size = 14D;
            titleFormat.Position = 1;
            titleFormat.Spacing = 5;
            titleFormat.Bold = true;

            var title = header.InsertParagraph();

            if( dokumentumTipus.Equals(DokumentumTipus.Eredmenylap.Verseny.MISZ) ) {
                title.Append( Feliratok.HeadLine.Eredmenylap );
                title.AppendLine( Feliratok.HeadLine.EredmenyLapMISZ );
            }
            else {
                title.Append( Feliratok.HeadLine.Eredmenylap );
                title.AppendLine( Feliratok.HeadLine.EredmenyLapTeljes );
            }

            title.Alignment = Alignment.center;

            titleFormat.Size = 10D;
            title.AppendLine( Feliratok.Tulajdonos );
            title.Bold( );
            titleFormat.Position = 12;
            title.AppendLine( );
        }
Exemplo n.º 25
0
 /// <summary>
 /// Insert a new Paragraph before this Paragraph.
 /// </summary>
 /// <param name="text">The initial text for this new Paragraph.</param>
 /// <param name="trackChanges">Should this insertion be tracked as a change?</param>
 /// <param name="formatting">The formatting to apply to this insertion.</param>
 /// <returns>A new Paragraph inserted before this Paragraph.</returns>
 /// <example>
 /// Insert a new paragraph before the first Paragraph in this document.
 /// <code>
 /// // Create a new document.
 /// using (DocX document = DocX.Create(@"Test.docx"))
 /// {
 ///     // Insert a Paragraph into this document.
 ///     Paragraph p = document.InsertParagraph("I am a Paragraph", false);
 ///
 ///     Formatting boldFormatting = new Formatting();
 ///     boldFormatting.Bold = true;
 ///
 ///     p.InsertParagraphBeforeSelf("I was inserted before the next Paragraph.", false, boldFormatting);
 ///
 ///     // Save all changes made to this new document.
 ///     document.Save();
 ///    }// Release this new document form memory.
 /// </code>
 /// </example>
 public override Paragraph InsertParagraphBeforeSelf(string text, bool trackChanges, Formatting formatting)
 {
     Paragraph p = base.InsertParagraphBeforeSelf(text, trackChanges, formatting);
     p.PackagePart = mainPart;
     return p;
 }
Exemplo n.º 26
0
        /// <summary>
        /// Replaces all occurrences of a specified System.String in this instance, with another specified System.String.
        /// </summary>
        /// <example>
        /// <code>
        /// // Load a document using a relative filename.
        /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
        /// {
        ///     // The formatting to match.
        ///     Formatting matchFormatting = new Formatting();
        ///     matchFormatting.Size = 10;
        ///     matchFormatting.Italic = true;
        ///     matchFormatting.FontFamily = new FontFamily("Times New Roman");
        ///
        ///     // The formatting to apply to the inserted text.
        ///     Formatting newFormatting = new Formatting();
        ///     newFormatting.Size = 22;
        ///     newFormatting.UnderlineStyle = UnderlineStyle.dotted;
        ///     newFormatting.Bold = true;
        ///
        ///     // Iterate through the paragraphs in this document.
        ///     foreach (Paragraph p in document.Paragraphs)
        ///     {
        ///         /* 
        ///          * Replace all instances of the string "wrong" with the string "right" and ignore case.
        ///          * Each inserted instance of "wrong" should use the Formatting newFormatting.
        ///          * Only replace an instance of "wrong" if it is Size 10, Italic and Times New Roman.
        ///          * SubsetMatch means that the formatting must contain all elements of the match formatting,
        ///          * but it can also contain additional formatting for example Color, UnderlineStyle, etc.
        ///          * ExactMatch means it must not contain additional formatting.
        ///          */
        ///         p.ReplaceText("wrong", "right", false, RegexOptions.IgnoreCase, newFormatting, matchFormatting, MatchFormattingOptions.SubsetMatch);
        ///     }
        ///
        ///     // Save all changes made to this document.
        ///     document.Save();
        /// }// Release this document from memory.
        /// </code>
        /// </example>
        /// <seealso cref="Paragraph.RemoveText(int, int, bool)"/>
        /// <seealso cref="Paragraph.RemoveText(int, bool)"/>
        /// <seealso cref="Paragraph.InsertText(string, bool)"/>
        /// <seealso cref="Paragraph.InsertText(int, string, bool)"/>
        /// <seealso cref="Paragraph.InsertText(int, string, bool, Formatting)"/>
        /// <seealso cref="Paragraph.InsertText(string, bool, Formatting)"/>
        /// <param name="newValue">A System.String to replace all occurances of oldValue.</param>
        /// <param name="oldValue">A System.String to be replaced.</param>
        /// <param name="options">A bitwise OR combination of RegexOption enumeration options.</param>
        /// <param name="trackChanges">Track changes</param>
        /// <param name="newFormatting">The formatting to apply to the text being inserted.</param>
        /// <param name="matchFormatting">The formatting that the text must match in order to be replaced.</param>
        /// <param name="fo">How should formatting be matched?</param>
        public void ReplaceText(string oldValue, string newValue, bool trackChanges = false, RegexOptions options = RegexOptions.None, Formatting newFormatting = null, Formatting matchFormatting = null, MatchFormattingOptions fo = MatchFormattingOptions.SubsetMatch)
        {
            MatchCollection mc = Regex.Matches(this.Text, Regex.Escape(oldValue), options);

            // Loop through the matches in reverse order
            foreach (Match m in mc.Cast<Match>().Reverse())
            {
                // Assume the formatting matches until proven otherwise.
                bool formattingMatch = true;

                // Does the user want to match formatting?
                if (matchFormatting != null)
                {
                    // The number of characters processed so far
                    int processed = 0;

                    do
                    {
                        // Get the next run effected
                        Run run = GetFirstRunEffectedByEdit(m.Index + processed);

                        // Get this runs properties
                        XElement rPr = run.Xml.Element(XName.Get("rPr", DocX.w.NamespaceName));

                        if (rPr == null)
                            rPr = new Formatting().Xml;

                        /* 
                         * Make sure that every formatting element in f.xml is also in this run,
                         * if this is not true, then their formatting does not match.
                         */
                        if (!ContainsEveryChildOf(matchFormatting.Xml, rPr, fo))
                        {
                            formattingMatch = false;
                            break;
                        }

                        // We have processed some characters, so update the counter.
                        processed += run.Value.Length;

                    } while (processed < m.Length);
                }

                // If the formatting matches, do the replace.
                if (formattingMatch)
                {
                    InsertText(m.Index + oldValue.Length, newValue, trackChanges, newFormatting);
                    RemoveText(m.Index, m.Length, trackChanges);
                }
            }
        }
Exemplo n.º 27
0
        public void Test_Paragraph_ReplaceTextInGivenFormat()
        {
            // Load a document.
            using (DocX document = DocX.Load(_directoryWithFiles + "VariousTextFormatting.docx"))
            {
                // Removing red text highlighted with yellow
                var formatting = new Formatting();
                formatting.FontColor = Color.Blue;
                // IMPORTANT: default constructor of Formatting sets up language property - set it to NULL to be language independent
                var desiredFormat = new Formatting() { Language = null, FontColor = Color.FromArgb(255, 0, 0), Highlight = Highlight.yellow };
                var replaced = string.Empty;
                foreach (var p in document.Paragraphs)
                {
                    if (p.Text == "Text highlighted with yellow")
                    {
                        p.ReplaceText("Text highlighted with yellow", "New text highlighted with yellow", false, RegexOptions.None, null, desiredFormat, MatchFormattingOptions.ExactMatch);
                        replaced += p.Text;
                    }
                }

                Assert.AreEqual("New text highlighted with yellow", replaced);

                // Removing red text with no other formatting (ExactMatch)
                desiredFormat = new Formatting() { Language = null, FontColor = Color.FromArgb(255, 0, 0) };
                var count = 0;
                foreach (var p in document.Paragraphs)
                {
                    p.ReplaceText("Text", "Replaced text", false, RegexOptions.None, null, desiredFormat, MatchFormattingOptions.ExactMatch);
                    if (p.Text.StartsWith("Replaced text"))
                    {
                        ++count;
                    }
                }

                Assert.AreEqual(1, count);

                // Removing just red text with any other formatting (SubsetMatch)
                desiredFormat = new Formatting() { Language = null, FontColor = Color.FromArgb(255, 0, 0) };
                count = 0;
                foreach (var p in document.Paragraphs)
                {
                    p.ReplaceText("Text", "Replaced text", false, RegexOptions.None, null, desiredFormat, MatchFormattingOptions.SubsetMatch);
                    if (p.Text.StartsWith("Replaced text"))
                    {
                        ++count;
                    }
                }

                Assert.AreEqual(2, count);
            }
        }
Exemplo n.º 28
0
        internal int RemoveTextWithFormatRecursive(XElement element, Formatting matchFormatting, MatchFormattingOptions fo)
        {
            var deletedCount = 0;
            foreach (var x in element.Elements())
            {
                if ("rPr".Equals(x.Name.LocalName))
                {
                    if (HelperFunctions.ContainsEveryChildOf(matchFormatting.Xml, x, fo))
                    {
                        x.Parent.Remove();
                        ++deletedCount;
                    }
                }

                deletedCount += RemoveTextWithFormatRecursive(x, matchFormatting, fo);
            }

            return deletedCount;
        }
Exemplo n.º 29
0
        public virtual void ReplaceText(string searchValue, string newValue, bool trackChanges = false, RegexOptions options = RegexOptions.None, Formatting newFormatting = null, Formatting matchFormatting = null, MatchFormattingOptions formattingOptions = MatchFormattingOptions.SubsetMatch, bool escapeRegEx = true, bool useRegExSubstitutions = false)
        {
            if (string.IsNullOrEmpty(searchValue))
                throw new ArgumentException("oldValue cannot be null or empty", "searchValue");

            if (newValue == null)
                throw new ArgumentException("newValue cannot be null or empty", "newValue");
            // ReplaceText in Headers of the document.
            var headerList = new List<Header> { Document.Headers.first, Document.Headers.even, Document.Headers.odd };
            foreach (var header in headerList)
                if (header != null)
                    foreach (var paragraph in header.Paragraphs)
                        paragraph.ReplaceText(searchValue, newValue, trackChanges, options, newFormatting, matchFormatting, formattingOptions, escapeRegEx, useRegExSubstitutions);

            // ReplaceText int main body of document.
            foreach (var paragraph in Paragraphs)
                paragraph.ReplaceText(searchValue, newValue, trackChanges, options, newFormatting, matchFormatting, formattingOptions, escapeRegEx, useRegExSubstitutions);

            // ReplaceText in Footers of the document.
            var footerList = new List<Footer> { Document.Footers.first, Document.Footers.even, Document.Footers.odd };
            foreach (var footer in footerList)
                if (footer != null)
                    foreach (var paragraph in footer.Paragraphs)
                        paragraph.ReplaceText(searchValue, newValue, trackChanges, options, newFormatting, matchFormatting, formattingOptions, escapeRegEx, useRegExSubstitutions);
        }
Exemplo n.º 30
0
        public int CompareTo(object obj)
        {
            Formatting other = (Formatting)obj;

            if (other.hidden != this.hidden)
            {
                return(-1);
            }

            if (other.bold != this.bold)
            {
                return(-1);
            }

            if (other.italic != this.italic)
            {
                return(-1);
            }

            if (other.strikethrough != this.strikethrough)
            {
                return(-1);
            }

            if (other.script != this.script)
            {
                return(-1);
            }

            if (other.highlight != this.highlight)
            {
                return(-1);
            }

            if (other.size != this.size)
            {
                return(-1);
            }

            if (other.fontColor != this.fontColor)
            {
                return(-1);
            }

            if (other.underlineColor != this.underlineColor)
            {
                return(-1);
            }

            if (other.underlineStyle != this.underlineStyle)
            {
                return(-1);
            }

            if (other.misc != this.misc)
            {
                return(-1);
            }

            if (other.capsStyle != this.capsStyle)
            {
                return(-1);
            }

            if (other.fontFamily != this.fontFamily)
            {
                return(-1);
            }

            if (other.percentageScale != this.percentageScale)
            {
                return(-1);
            }

            if (other.kerning != this.kerning)
            {
                return(-1);
            }

            if (other.position != this.position)
            {
                return(-1);
            }

            if (other.spacing != this.spacing)
            {
                return(-1);
            }

            if (!other.language.Equals(this.language))
            {
                return(-1);
            }

            return(0);
        }
Exemplo n.º 31
0
        public virtual Paragraph InsertParagraph(int index, string text, bool trackChanges, Formatting formatting)
        {
            Paragraph newParagraph = new Paragraph(Document, new XElement(DocX.w + "p"), index);

            newParagraph.InsertText(0, text, trackChanges, formatting);

            Paragraph firstPar = HelperFunctions.GetFirstParagraphEffectedByInsert(Document, index);

            if (firstPar != null)
            {
                var splitindex = index - firstPar.startIndex;
                if (splitindex <= 0)
                {
                    firstPar.Xml.ReplaceWith(newParagraph.Xml, firstPar.Xml);
                }
                else
                {
                    XElement[] splitParagraph = HelperFunctions.SplitParagraph(firstPar, splitindex);

                    firstPar.Xml.ReplaceWith
                    (
                        splitParagraph[0],
                        newParagraph.Xml,
                        splitParagraph[1]
                    );
                }
            }

            else
            {
                Xml.Add(newParagraph);
            }

            GetParent(newParagraph);

            return(newParagraph);
        }
Exemplo n.º 32
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="searchValue">Value to find</param>
        /// <param name="regexMatchHandler">A Func that accepts the matching regex search group value and passes it to this to return the replacement string</param>
        /// <param name="trackChanges">Enable trackchanges</param>
        /// <param name="options">Regex options</param>
        /// <param name="newFormatting"></param>
        /// <param name="matchFormatting"></param>
        /// <param name="formattingOptions"></param>
        /// <param name="removeEmptyParagraph">Remove empty paragraph</param>
        public virtual void ReplaceText(string searchValue, Func <string, string> regexMatchHandler, bool trackChanges = false, RegexOptions options = RegexOptions.None, Formatting newFormatting = null, Formatting matchFormatting = null, MatchFormattingOptions formattingOptions = MatchFormattingOptions.SubsetMatch, bool removeEmptyParagraph = true)
        {
            if (string.IsNullOrEmpty(searchValue))
            {
                throw new ArgumentException("oldValue cannot be null or empty", "searchValue");
            }

            if (regexMatchHandler == null)
            {
                throw new ArgumentException("regexMatchHandler cannot be null", "regexMatchHandler");
            }

            // ReplaceText in Headers/Footers of the document.
            var containerList = new List <IParagraphContainer> {
                Document.Headers.first, Document.Headers.even, Document.Headers.odd,
                Document.Footers.first, Document.Footers.even, Document.Footers.odd
            };

            foreach (var container in containerList)
            {
                if (container != null)
                {
                    foreach (var paragraph in container.Paragraphs)
                    {
                        paragraph.ReplaceText(searchValue, regexMatchHandler, trackChanges, options, newFormatting, matchFormatting, formattingOptions, removeEmptyParagraph);
                    }
                }
            }

            // ReplaceText int main body of document.
            foreach (var paragraph in Paragraphs)
            {
                paragraph.ReplaceText(searchValue, regexMatchHandler, trackChanges, options, newFormatting, matchFormatting, formattingOptions, removeEmptyParagraph);
            }
        }
Exemplo n.º 33
0
        public override Paragraph InsertParagraph(int index, string text, bool trackChanges, Formatting formatting)
        {
            Paragraph p = base.InsertParagraph(index, text, trackChanges, formatting);

            p.PackagePart = mainPart;
            return(p);
        }
Exemplo n.º 34
0
        public virtual void ReplaceText(string searchValue, string newValue, bool trackChanges = false, RegexOptions options = RegexOptions.None, Formatting newFormatting = null, Formatting matchFormatting = null, MatchFormattingOptions formattingOptions = MatchFormattingOptions.SubsetMatch, bool escapeRegEx = true, bool useRegExSubstitutions = false, bool removeEmptyParagraph = true)
        {
            if (string.IsNullOrEmpty(searchValue))
            {
                throw new ArgumentException("oldValue cannot be null or empty", "searchValue");
            }

            if (newValue == null)
            {
                throw new ArgumentException("newValue cannot be null or empty", "newValue");
            }
            // ReplaceText in Headers of the document.
            var headerList = new List <Header> {
                Document.Headers.first, Document.Headers.even, Document.Headers.odd
            };

            foreach (var header in headerList)
            {
                if (header != null)
                {
                    foreach (var paragraph in header.Paragraphs)
                    {
                        paragraph.ReplaceText(searchValue, newValue, trackChanges, options, newFormatting, matchFormatting, formattingOptions, escapeRegEx, useRegExSubstitutions, removeEmptyParagraph);
                    }
                }
            }

            // ReplaceText int main body of document.
            foreach (var paragraph in Paragraphs)
            {
                paragraph.ReplaceText(searchValue, newValue, trackChanges, options, newFormatting, matchFormatting, formattingOptions, escapeRegEx, useRegExSubstitutions, removeEmptyParagraph);
            }

            // ReplaceText in Footers of the document.
            var footerList = new List <Footer> {
                Document.Footers.first, Document.Footers.even, Document.Footers.odd
            };

            foreach (var footer in footerList)
            {
                if (footer != null)
                {
                    foreach (var paragraph in footer.Paragraphs)
                    {
                        paragraph.ReplaceText(searchValue, newValue, trackChanges, options, newFormatting, matchFormatting, formattingOptions, escapeRegEx, useRegExSubstitutions, removeEmptyParagraph);
                    }
                }
            }
        }
Exemplo n.º 35
0
        /// <summary>
        /// 生成一个表格
        /// </summary>
        /// <param name="fromPath">源文件</param>
        /// <param name="strXml">xml格式字符串</param>
        /// <param name="replaceFlag">替换标记,定位表格位置</param>
        /// <param name="bEmptyParagraph"></param>
        /// <param name="sPercent">各列所占表格的百分比,逗号隔开</param>
        /// <param name="sPagePercent">表格所占页面的百分比</param>
        /// <returns></returns>
        public Table GenerateTable(string fromPath, string strXml, string replaceFlag,
                                   bool bEmptyParagraph, string sPercent, string sPagePercent)
        {
            DocX      doc  = DocX.Load(fromPath);
            DataTable dt   = XMLDeserialize(strXml);
            int       nRow = dt.Rows.Count;
            int       nCol = dt.Columns.Count;
            Paragraph p    = GetParagraphByReplaceFlag(doc, replaceFlag, null);

            if (p == null)
            {
                return(null);
            }
            Table tbl = p.InsertTableBeforeSelf(nRow, nCol);

            int[] aRowNCol = new int[nRow];//每一行有多少列

            #region 数组:每行有多少列
            //目的是由于合并情况的出现会导致每行列数减少,但是合并单元格以后行不会减少
            for (int i = 0; i < aRowNCol.Length; i++)
            {
                aRowNCol[i] = nCol;
            }
            #endregion 数组:每行有多少列

            #region 合并单元格,从右下角往左上角扫
            int nLe;
            int nUp;

            for (int j = nCol - 1; j >= 0; j--)
            {
                for (int i = nRow - 1; i >= 0; i--)
                {
                    nUp = 0;
                    nLe = 0;
                    if (dt.Rows[i][j].ToString().ToUpper().Trim() == "UP" || dt.Rows[i][j].ToString().ToUpper().Trim() == "LE")
                    {
                        continue;
                    }
                    else
                    {
                        tbl.Rows[i].Cells[j].Paragraphs[0].Append(dt.Rows[i][j].ToString());
                    }

                    for (int n = i + 1; n < nRow; n++)
                    {
                        if (dt.Rows[n][j].ToString().ToUpper().Trim() == "UP")
                        {
                            aRowNCol[n] -= 1;
                            nUp++;
                        }
                        else
                        {
                            break;
                        }
                    }

                    for (int m = j + 1; m < aRowNCol[i]; m++)
                    {
                        if (dt.Rows[i][m].ToString().ToUpper().Trim() == "LE")
                        {
                            nLe++;
                        }
                        else
                        {
                            break;
                        }
                    }
                    #region 合并行
                    if (nUp > 0)
                    {
                        try
                        {
                            tbl.MergeCellsInColumn(j, i, i + nUp);
                        }
                        catch (System.ArgumentOutOfRangeException e)
                        {
                            classLims_NPOI.WriteLog(e, "");
                            continue;
                        }
                    }
                    #endregion 合并行
                    if (nLe > 0)
                    {
                        aRowNCol[i] -= nLe;
                        try
                        {
                            tbl.Rows[i].MergeCells(j, j + nLe);
                        }
                        catch (System.ArgumentOutOfRangeException e)
                        {
                            classLims_NPOI.WriteLog(e, "");
                            continue;
                        }

                        #region  除合并单元格中的多余回车
                        for (int z = 0; z < nLe; z++)
                        {
                            tbl.Rows[i].Cells[j].Paragraphs[tbl.Rows[i].Cells[j].Paragraphs.Count - 1].Remove(false);
                        }
                        #endregion  除合并单元格中的多余回车
                        if (nUp > 0)
                        {
                            for (int l = i + 1; l <= i + nUp; l++)
                            {
                                try
                                {
                                    tbl.Rows[l].MergeCells(j, j + nLe);
                                }
                                catch (System.ArgumentOutOfRangeException e)
                                {
                                    classLims_NPOI.WriteLog(e, "");
                                    continue;
                                }
                            }
                        }
                    }
                    #region 科学计数法 & 上下标
                    int nParagraphs = tbl.Rows[i].Cells[j].Paragraphs.Count;//看这个单元格有多少paragraphs
                    for (int iParagraphs = 0; iParagraphs < nParagraphs; iParagraphs++)
                    {
                        String sComment = tbl.Rows[i].Cells[j].Paragraphs[iParagraphs].Text.ToUpper();

                        if (sComment.IndexOf("E") > 0)
                        {
                            string sPre    = sComment.Substring(0, sComment.IndexOf("E"));
                            string sZhishu = sComment.Substring(sComment.IndexOf("E") + 1, sComment.Length - sComment.IndexOf("E") - 1);
                            if ((Regex.IsMatch(sPre, @"^\d+\.\d+$") || Regex.IsMatch(sPre, @"^\d+$") || Regex.IsMatch(sPre, @"^[-]+\d+$") || Regex.IsMatch(sPre, @"^[-]+\d+\.\d+$")) &&
                                (Regex.IsMatch(sZhishu, @"^\d+$") || Regex.IsMatch(sZhishu, @"^[-]+\d+$")))
                            {
                                tbl.Rows[i].Cells[j].Paragraphs[iParagraphs].RemoveText(0, sComment.Length);
                                tbl.Rows[i].Cells[j].Paragraphs[iParagraphs].InsertText(Convert.ToDecimal(sPre).ToString() + "×10{U|" + Int32.Parse(sZhishu).ToString() + "}");
                            }
                        }
                    }
                    for (int iParagraphs = 0; iParagraphs < nParagraphs; iParagraphs++)
                    {
                        #region  标
                        int iBeginUp = -1;
                        Novacode.Formatting formattingUp = new Novacode.Formatting();
                        formattingUp.Script = Script.superscript;

                        while (tbl.Rows[i].Cells[j].Paragraphs[iParagraphs].Text.ToUpper().IndexOf("{U|") > 0)
                        {
                            iBeginUp = tbl.Rows[i].Cells[j].Paragraphs[iParagraphs].Text.ToUpper().IndexOf("{U|");
                            int iEndUp = -1;
                            for (iEndUp = iBeginUp + 3; iEndUp < tbl.Rows[i].Cells[j].Paragraphs[iParagraphs].Text.Length; iEndUp++)
                            {
                                if (tbl.Rows[i].Cells[j].Paragraphs[iParagraphs].Text.Substring(iEndUp, 1) == "}")
                                {
                                    break;
                                }
                            }
                            if ((iBeginUp + 3) != iEndUp)
                            {
                                string strSub = tbl.Rows[i].Cells[j].Paragraphs[iParagraphs].Text.Substring(iBeginUp + 3, iEndUp - iBeginUp - 3);
                                tbl.Rows[i].Cells[j].Paragraphs[iParagraphs].RemoveText(iBeginUp, iEndUp - iBeginUp + 1);
                                tbl.Rows[i].Cells[j].Paragraphs[iParagraphs].InsertText(iBeginUp, strSub, false, formattingUp);
                            }
                        }
                        #endregion  标

                        #region  标
                        int iBeginDown = -1;
                        Novacode.Formatting formattingDown = new Novacode.Formatting();
                        formattingDown.Script = Script.subscript;

                        while (tbl.Rows[i].Cells[j].Paragraphs[iParagraphs].Text.ToUpper().IndexOf("{D|") > 0)
                        {
                            iBeginDown = tbl.Rows[i].Cells[j].Paragraphs[iParagraphs].Text.ToUpper().IndexOf("{D|");
                            int iEndDown = -1;
                            for (iEndDown = iBeginDown + 3; iEndDown < tbl.Rows[i].Cells[j].Paragraphs[iParagraphs].Text.Length; iEndDown++)
                            {
                                if (tbl.Rows[i].Cells[j].Paragraphs[iParagraphs].Text.Substring(iEndDown, 1) == "}")
                                {
                                    break;
                                }
                            }
                            if ((iBeginDown + 3) != iEndDown)
                            {
                                string strSub = tbl.Rows[i].Cells[j].Paragraphs[iParagraphs].Text.Substring(iBeginDown + 3, iEndDown - iBeginDown - 3);
                                tbl.Rows[i].Cells[j].Paragraphs[iParagraphs].RemoveText(iBeginDown, iEndDown - iBeginDown + 1);
                                tbl.Rows[i].Cells[j].Paragraphs[iParagraphs].InsertText(iBeginDown, strSub, false, formattingDown);
                            }
                        }
                        #endregion  标
                    }
                    #endregion   标
                }
            }


            #endregion 合并单元格,从右下角往左上角扫

            if (bEmptyParagraph)
            {
                Paragraph p1 = tbl.InsertParagraphAfterSelf("");
                //p1.Remove();
            }
            Paragraph rp = GetParagraphByReplaceFlag(doc, replaceFlag, "LEFT");
            rp.ReplaceText(replaceFlag, "");
            SetTableBorderLine(tbl, "BOTTOM");
            SetTableBorderLine(tbl, "TOP");
            SetTableBorderLine(tbl, "RIGHT");
            SetTableBorderLine(tbl, "LEFT");
            SetTableBorderLine(tbl, "INSIDEV");
            SetTableBorderLine(tbl, "INSIDEH");
            SetTableColWidth(fromPath, tbl, sPercent, sPagePercent);
            doc.Save();
            return(tbl);
        }
Exemplo n.º 36
0
        public virtual Paragraph InsertParagraph(string text, bool trackChanges, Formatting formatting)
        {
            XElement newParagraph = new XElement
            (
                XName.Get("p", DocX.w.NamespaceName), new XElement(XName.Get("pPr", DocX.w.NamespaceName)), HelperFunctions.FormatInput(text, formatting.Xml)
            );

            if (trackChanges)
                newParagraph = HelperFunctions.CreateEdit(EditType.ins, DateTime.Now, newParagraph);
            Xml.Add(newParagraph);
            var paragraphAdded = new Paragraph(Document, newParagraph, 0);
            if (this is Cell)
            {
                var cell = this as Cell;
                paragraphAdded.PackagePart = cell.mainPart;
            }
            else if (this is DocX)
            {
                paragraphAdded.PackagePart = Document.mainPart;
            }
            else if (this is Footer)
            {
                var f = this as Footer;
                paragraphAdded.mainPart = f.mainPart;
            }
            else if (this is Header)
            {
                var h = this as Header;
                paragraphAdded.mainPart = h.mainPart;
            }
            else
            {
                Console.WriteLine("No idea what we are {0}", this);
                paragraphAdded.PackagePart = Document.mainPart;
            }

            GetParent(paragraphAdded);

            return paragraphAdded;
        }
Exemplo n.º 37
0
        /// <summary>
        /// Removes all items with required formatting
        /// </summary>
        /// <returns>Numer of texts removed</returns>
        public int RemoveTextInGivenFormat(Formatting matchFormatting, MatchFormattingOptions fo = MatchFormattingOptions.SubsetMatch)
        {
            var deletedCount = 0;
            foreach (var x in Xml.Elements())
            {
                deletedCount += RemoveTextWithFormatRecursive(x, matchFormatting, fo);
            }

            return deletedCount;
        }
Exemplo n.º 38
0
        private void implementarPortada(DocX doc, Empresa empresa)
        {
            //Hacemos la portada
            string strTituloPortada = "Análisis de Recursos Valiosos";

            //string strLogoPortada = string.Concat(Environment.CurrentDirectory, "\\RBV\\RBV\\img\\Login\\2.png");
            string strLogoPortada  = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "img\\Login\\2.png");
            string strElaboradoPor = "Elaborado por: MyInnovation";
            // A formatting object for our headline:
            var headLineFormat = new Novacode.Formatting();

            headLineFormat.FontFamily = new System.Drawing.FontFamily("Calibri");
            headLineFormat.Size       = 26D;

            // Ciudad:
            var paraFormat = new Novacode.Formatting();

            paraFormat.FontFamily = new System.Drawing.FontFamily("Calibri");
            paraFormat.Size       = 18D;

            // Formato elaborado por:
            var elaboradoPorFormat = new Novacode.Formatting();

            elaboradoPorFormat.FontFamily = new System.Drawing.FontFamily("Calibri");
            elaboradoPorFormat.Size       = 10D;

            // Add an Image into this document.
            //Novacode.Image i = doc.AddImage(strLogoPortada);
            //// Create a Picture (Custom View) of this Image.
            //Picture p = i.CreatePicture();


            //Paragraph pImg = doc.InsertParagraph("").AppendPicture(p);
            //pImg.Alignment = Alignment.right;
            doc.InsertParagraph();
            doc.InsertParagraph();
            doc.InsertParagraph();
            Paragraph pTit = doc.InsertParagraph(strTituloPortada, false, headLineFormat);

            pTit.Alignment = Alignment.center;
            doc.InsertParagraph();
            doc.InsertParagraph();
            doc.InsertParagraph();
            doc.InsertParagraph();
            doc.InsertParagraph();
            doc.InsertParagraph();
            doc.InsertParagraph();
            doc.InsertParagraph();
            doc.InsertParagraph();
            doc.InsertParagraph();
            doc.InsertParagraph();
            doc.InsertParagraph();

            // Paragraph pEmp = doc.InsertParagraph("Milton Fredy González Díaz" , false, headLineFormat);
            //pEmp.Alignment = Alignment.center;
            //pEmp = doc.InsertParagraph("Diego León Pineda Montoya", false, headLineFormat);
            //pEmp.Alignment = Alignment.center;
            Paragraph pEmp = doc.InsertParagraph(empresa.NombreEmpresa, false, headLineFormat);

            pEmp.Alignment = Alignment.left;

            doc.InsertParagraph();

            //Paragraph pElp = doc.InsertParagraph(strElaboradoPor, false, elaboradoPorFormat);
            //pElp.Alignment = Alignment.right;


            //Paragraph pCiud = doc.InsertParagraph("Medellín", false, paraFormat);
            //pCiud.Alignment = Alignment.left;

            CultureInfo ci   = new CultureInfo("es-ES");
            Paragraph   pAno = doc.InsertParagraph(DateTime.Now.ToString("MMMM", ci) + " " + DateTime.Now.Year.ToString(), false, paraFormat);

            pAno.Alignment = Alignment.left;
        }
Exemplo n.º 39
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="searchValue">Value to find</param>
        /// <param name="regexMatchHandler">A Func that accepts the matching regex search group value and passes it to this to return the replacement string</param>
        /// <param name="trackChanges">Enable trackchanges</param>
        /// <param name="options">Regex options</param>
        /// <param name="newFormatting"></param>
        /// <param name="matchFormatting"></param>
        /// <param name="formattingOptions"></param>
        public virtual void ReplaceText(string searchValue, Func<string,string> regexMatchHandler, bool trackChanges = false, RegexOptions options = RegexOptions.None, Formatting newFormatting = null, Formatting matchFormatting = null, MatchFormattingOptions formattingOptions = MatchFormattingOptions.SubsetMatch)
        {
            if (string.IsNullOrEmpty(searchValue))
                throw new ArgumentException("oldValue cannot be null or empty", "searchValue");

            if (regexMatchHandler == null)
                throw new ArgumentException("regexMatchHandler cannot be null", "regexMatchHandler");

            // ReplaceText in Headers/Footers of the document.
            var containerList = new List<IParagraphContainer> {
                Document.Headers.first, Document.Headers.even, Document.Headers.odd,
                Document.Footers.first, Document.Footers.even, Document.Footers.odd };
            foreach (var container in containerList)
                if (container != null)
                    foreach (var paragraph in container.Paragraphs)
                        paragraph.ReplaceText(searchValue, regexMatchHandler, trackChanges, options, newFormatting, matchFormatting, formattingOptions);

            // ReplaceText int main body of document.
            foreach (var paragraph in Paragraphs)
                paragraph.ReplaceText(searchValue, regexMatchHandler, trackChanges, options, newFormatting, matchFormatting, formattingOptions);
        }
Exemplo n.º 40
0
        private void insertarGraficosTortas(DocX doc, Empresa empresa, string strDirectorio)
        {
            List <RBV_Clases.RecursoValioso>  recursosValiosos = new List <RBV_Clases.RecursoValioso>();
            List <Entidades.MatrizValoracion> MatrizValoracion = new List <RBV_Clases.MatrizValoracion>();
            decimal ValorTotal = 0;

            MatrizValoracion = RBV_Negocio.MatrizBO.ConsultarMatrizValoracion(empresa.IdEmpresa).OrderBy(p => p.IdCaracteristica).ThenBy(p => p.IdRecurso).ToList();

            if (MatrizValoracion.Count > 0)
            {
                recursosValiosos = RBV_Negocio.MatrizBO.CalcularResultadosMatriz(MatrizValoracion, empresa.IdEmpresa);
                ValorTotal       = recursosValiosos.Sum(p => p.Valor) / recursosValiosos.Count;
            }



            var RVFormat = new Novacode.Formatting();

            RVFormat.FontFamily = new System.Drawing.FontFamily("Calibri");
            RVFormat.Size       = 12D;
            RVFormat.Bold       = true;


            var RVParrafo = new Novacode.Formatting();

            RVParrafo.FontFamily = new System.Drawing.FontFamily("Calibri");
            RVParrafo.Size       = 12D;
            RVParrafo.Position   = 3;


            string strGraficoTortaRecursos              = CrearTortaRecursos(empresa, strDirectorio, recursosValiosos);
            string strGraficoTortaRecursosSobreTotal    = CrearTortaRecursosSobreTotal(empresa, strDirectorio, recursosValiosos, ValorTotal);
            string strGraficoTortaRecursosSobreValiosos = CrearTortaRecursosValiososSobreValiosos(empresa, strDirectorio, recursosValiosos, ValorTotal);
            string strGraficoBarrasHorinzotales         = CrearGraficoBarrasHorizontalesClasificacion(empresa, strDirectorio, MatrizValoracion, ValorTotal);

            //Torta de porcentajes
            Paragraph pTit = doc.InsertParagraph("Porcentajes de Recursos", false, RVFormat);

            pTit.Alignment = Alignment.left;
            Paragraph pParr = doc.InsertParagraph("Aquí va el análisis a la torta de porcentaje ", false, RVParrafo);

            pParr.Alignment = Alignment.left;

            Novacode.Image i    = doc.AddImage(strGraficoTortaRecursos);
            Picture        pic  = i.CreatePicture();
            Paragraph      pImg = doc.InsertParagraph("").AppendPicture(pic);

            pImg.Alignment = Alignment.center;

            //Torta de porcentajes sobre recursos total
            pTit            = doc.InsertParagraph("Porcentajes de Recursos valiosos sobre el total de los recursos", false, RVFormat);
            pTit.Alignment  = Alignment.left;
            pParr           = doc.InsertParagraph("Aquí va el análisis a la torta de porcentaje ", false, RVParrafo);
            pParr.Alignment = Alignment.left;

            i              = doc.AddImage(strGraficoTortaRecursosSobreTotal);
            pic            = i.CreatePicture();
            pImg           = doc.InsertParagraph("").AppendPicture(pic);
            pImg.Alignment = Alignment.center;

            //Torta de porcentajes sobre valiosos
            pTit            = doc.InsertParagraph("Porcentajes de Recursos valiosos sobre el total de los valiosos", false, RVFormat);
            pTit.Alignment  = Alignment.left;
            pParr           = doc.InsertParagraph("Aquí va el análisis a la torta de porcentaje", false, RVParrafo);
            pParr.Alignment = Alignment.left;

            i              = doc.AddImage(strGraficoTortaRecursosSobreValiosos);
            pic            = i.CreatePicture();
            pImg           = doc.InsertParagraph("").AppendPicture(pic);
            pImg.Alignment = Alignment.center;

            //Torta de barras horizonteles
            pTit            = doc.InsertParagraph("Recursos contra clasificación", false, RVFormat);
            pTit.Alignment  = Alignment.left;
            pParr           = doc.InsertParagraph("Aquí va el análisis de barras horizontales", false, RVParrafo);
            pParr.Alignment = Alignment.left;

            i              = doc.AddImage(strGraficoBarrasHorinzotales);
            pic            = i.CreatePicture();
            pImg           = doc.InsertParagraph("").AppendPicture(pic);
            pImg.Alignment = Alignment.center;
        }
Exemplo n.º 41
0
        public void Test_Document_RemoveTextInGivenFormat()
        {
            // Load a document.
            using (DocX document = DocX.Load(_directoryWithFiles + "VariousTextFormatting.docx"))
            {
                var formatting = new Formatting();
                formatting.FontColor = Color.Blue;
                // IMPORTANT: default constructor of Formatting sets up language property - set it to NULL to be language independent
                formatting.Language = null;
                var deletedCount = document.RemoveTextInGivenFormat(formatting);
                Assert.AreEqual(2, deletedCount);

                deletedCount = document.RemoveTextInGivenFormat(new Formatting() { Highlight = Highlight.yellow, Language = null });
                Assert.AreEqual(2, deletedCount);

                deletedCount = document.RemoveTextInGivenFormat(new Formatting() { Highlight = Highlight.blue, Language = null, FontColor = Color.FromArgb(0, 255, 0) });
                Assert.AreEqual(1, deletedCount);

                deletedCount = document.RemoveTextInGivenFormat(new Formatting() { Language = null, FontColor = Color.FromArgb(123, 123, 123) }, MatchFormattingOptions.ExactMatch);
                Assert.AreEqual(2, deletedCount);
            }
        }
Exemplo n.º 42
0
        public static Formatting Parse(XElement rPr)
        {
            Formatting formatting = new Formatting();

            // Build up the Formatting object.
            foreach (XElement option in rPr.Elements())
            {
                switch (option.Name.LocalName)
                {
                case "lang":
                    formatting.Language = new CultureInfo(
                        option.GetAttribute(XName.Get("val", DocX.w.NamespaceName), null) ??
                        option.GetAttribute(XName.Get("eastAsia", DocX.w.NamespaceName), null) ??
                        option.GetAttribute(XName.Get("bidi", DocX.w.NamespaceName)));
                    break;

                case "spacing":
                    formatting.Spacing = Double.Parse(
                        option.GetAttribute(XName.Get("val", DocX.w.NamespaceName))) / 20.0;
                    break;

                case "position":
                    formatting.Position = Int32.Parse(
                        option.GetAttribute(XName.Get("val", DocX.w.NamespaceName))) / 2;
                    break;

                case "kern":
                    formatting.Position = Int32.Parse(
                        option.GetAttribute(XName.Get("val", DocX.w.NamespaceName))) / 2;
                    break;

                case "w":
                    formatting.PercentageScale = Int32.Parse(
                        option.GetAttribute(XName.Get("val", DocX.w.NamespaceName)));
                    break;

                // <w:sz w:val="20"/><w:szCs w:val="20"/>
                case "sz":
                    formatting.Size = Int32.Parse(
                        option.GetAttribute(XName.Get("val", DocX.w.NamespaceName))) / 2;
                    break;


                case "rFonts":
                    formatting.FontFamily =
                        new FontFamily(
                            option.GetAttribute(XName.Get("cs", DocX.w.NamespaceName), null) ??
                            option.GetAttribute(XName.Get("ascii", DocX.w.NamespaceName), null) ??
                            option.GetAttribute(XName.Get("hAnsi", DocX.w.NamespaceName), null) ??
                            option.GetAttribute(XName.Get("eastAsia", DocX.w.NamespaceName)));
                    break;

                case "color":
                    try
                    {
                        string color = option.GetAttribute(XName.Get("val", DocX.w.NamespaceName));
                        formatting.FontColor = System.Drawing.ColorTranslator.FromHtml(string.Format("#{0}", color));
                    }
                    catch { }
                    break;

                case "vanish": formatting.hidden = true; break;

                case "b": formatting.Bold = true; break;

                case "i": formatting.Italic = true; break;

                case "u": formatting.UnderlineStyle = HelperFunctions.GetUnderlineStyle(option.GetAttribute(XName.Get("val", DocX.w.NamespaceName)));
                    break;

                default: break;
                }
            }


            return(formatting);
        }
Exemplo n.º 43
0
        public virtual Paragraph InsertParagraphBeforeSelf(string text, bool trackChanges, Formatting formatting)
        {
            XElement newParagraph = new XElement
            (
                XName.Get("p", DocX.w.NamespaceName), new XElement(XName.Get("pPr", DocX.w.NamespaceName)), HelperFunctions.FormatInput(text, formatting.Xml)
            );

            if (trackChanges)
                newParagraph = Paragraph.CreateEdit(EditType.ins, DateTime.Now, newParagraph);

            Xml.AddBeforeSelf(newParagraph);
            XElement newlyInserted = Xml.ElementsBeforeSelf().Last();

            Paragraph p = new Paragraph(Document, newlyInserted, -1);

            return p;
        }
Exemplo n.º 44
0
        public virtual void ReplaceText(string oldValue, string newValue, bool trackChanges = false, RegexOptions options = RegexOptions.None, Formatting newFormatting = null, Formatting matchFormatting = null, MatchFormattingOptions fo = MatchFormattingOptions.SubsetMatch)
        {
            if (oldValue == null || oldValue.Length == 0)
            {
                throw new ArgumentException("oldValue cannot be null or empty", "oldValue");
            }

            if (newValue == null)
            {
                throw new ArgumentException("newValue cannot be null or empty", "newValue");
            }
            // ReplaceText in Headers of the document.
            Headers       headers    = Document.Headers;
            List <Header> headerList = new List <Header> {
                headers.first, headers.even, headers.odd
            };

            foreach (Header h in headerList)
            {
                if (h != null)
                {
                    foreach (Paragraph p in h.Paragraphs)
                    {
                        p.ReplaceText(oldValue, newValue, trackChanges, options, newFormatting, matchFormatting, fo);
                    }
                }
            }

            // ReplaceText int main body of document.
            foreach (Paragraph p in Paragraphs)
            {
                p.ReplaceText(oldValue, newValue, trackChanges, options, newFormatting, matchFormatting, fo);
            }

            // ReplaceText in Footers of the document.
            Footers       footers    = Document.Footers;
            List <Footer> footerList = new List <Footer> {
                footers.first, footers.even, footers.odd
            };

            foreach (Footer f in footerList)
            {
                if (f != null)
                {
                    foreach (Paragraph p in f.Paragraphs)
                    {
                        p.ReplaceText(oldValue, newValue, trackChanges, options, newFormatting, matchFormatting, fo);
                    }
                }
            }
        }