Exemplo n.º 1
0
        internal static void Italic(this Run run)
        {
            RunProperties runProperties = run.GetOrCreate <RunProperties>(true);
            Italic        prop          = runProperties.GetOrCreate <Italic>();

            prop.Val = OnOffValue.FromBoolean(true);
        }
Exemplo n.º 2
0
        static Texto TestComment(WordDoc wordDoc)
        {
            Comentario comentario = wordDoc.CreateComment();

            comentario.Append(
                "Descrição do comentário",
                new RunProperties()
            {
                Caps = new Caps()
                {
                    Val = OnOffValue.FromBoolean(true)
                }
            }
                );

            Texto texto = new Texto();

            texto.Append("Aqui vai começar um comentário, ");
            texto.StartComment(comentario.Id);
            texto.Append(
                "Texto de comentário, ",
                new RunProperties()
            {
                Bold = new Bold()
                {
                    Val = OnOffValue.FromBoolean(true)
                }
            }
                );
            texto.EndComment(comentario.Id);
            texto.Append("Texto fora do comentário,");

            return(texto);
        }
Exemplo n.º 3
0
        //Create paragraph that contain the text.
        private static Paragraph generateParagraph(string text, bool isHeader)
        {
            Paragraph paragraph     = new Paragraph();
            Run       run_paragraph = new Run();

            paragraph.Append(run_paragraph);
            //if isHeader=true style the text as header.
            if (isHeader)
            {
                RunProperties runProperties = run_paragraph.AppendChild(new RunProperties());
                Bold          bold          = new Bold();
                bold.Val = OnOffValue.FromBoolean(true);
                runProperties.AppendChild(bold);
                FontSize fontSize = new FontSize();
                fontSize.Val        = "26";
                runProperties.Color = new Color()
                {
                    Val = "0E6EB8"
                };
                runProperties.AppendChild(fontSize);
            }
            run_paragraph.AppendChild(new Text(text));
            if (!isHeader)
            {
                run_paragraph.AppendChild(new Break());
            }
            return(paragraph);
        }
Exemplo n.º 4
0
        private Paragraph CreateParagraph(string text, JustificationValues justification)
        {
            Paragraph paragraph = new Paragraph(
                new ParagraphProperties(
                    new ParagraphStyleId()
            {
                Val = "Bold"
            },
                    new Justification()
            {
                Val = justification
            },
                    new ParagraphMarkRunProperties()
                    ),
                new Run(
                    new RunProperties(new FontSize()
            {
                Val = "30"
            }, new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            }),
                    new Text(text)
            {
                Space = SpaceProcessingModeValues.Preserve
            }));

            return(paragraph);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Populates the processing document and gets its body element.
        /// </summary>
        /// <returns>Body of the document that will hold the dictionary.</returns>
        private Body GetDocumentBody(WordprocessingDocument processingDocument)
        {
            // Create a MainDocumentPart instance
            MainDocumentPart mainDocPart = processingDocument.AddMainDocumentPart();

            mainDocPart.Document = new Document();

            // Create a Document instance
            Document document = mainDocPart.Document;

            // Create a Body instance
            Body body = document.AppendChild(new Body());


            // Create 2 columns for page layout
            SectionProperties sectionProperties = new SectionProperties();
            Columns           columns           = new Columns()
            {
                ColumnCount = 2
            };

            columns.Separator = OnOffValue.FromBoolean(true);
            sectionProperties.Append(columns);

            body.Append(sectionProperties);

            return(body);
        }
Exemplo n.º 6
0
        private static Style CreateStyle(string fontcolor, string styleid, string stylename,
                                         string stylebasedon, string stylenextpara, string fontname, int fontsize, JustificationValues just, bool isBold, int spacing)
        {
            // we have to set the properties
            RunProperties rPr   = new RunProperties();
            Color         color = new Color()
            {
                Val = fontcolor
            };                                       // the color
            RunFonts rFont = new RunFonts();

            rFont.Ascii = fontname; // the font
            rPr.Append(color);
            rPr.Append(rFont);
            if (isBold)
            {
                rPr.Append(new Bold());
            }
            rPr.Append(new FontSize()
            {
                Val = fontsize.ToString()
            });                                                   //font size (in 1/72  of an inch)
            ParagraphProperties pPr = new ParagraphProperties();

            if (spacing > 0)
            {
                pPr.Append(new SpacingBetweenLines()
                {
                    Line              = spacing.ToString(),
                    LineRule          = LineSpacingRuleValues.Auto,
                    BeforeAutoSpacing = OnOffValue.FromBoolean(true)
                });
            }
            //creation of a style
            Style style = new Style();

            style.StyleId = styleid; //this is the ID of the style
            style.Append(new Name()
            {
                Val = stylename
            });                                       //this is name
            style.Append(new BasedOn()
            {
                Val = stylebasedon
            });                                             // our style based on ... style
            style.Append(new NextParagraphStyle()
            {
                Val = stylenextpara
            });                // the next paragraph is ... type
            style.Append(pPr); //we are adding properties previously defined
            style.Append(rPr); //we are adding properties previously defined
            //lets make it centered)
            style.Append(new ParagraphProperties(
                             new Justification()
            {
                Val = just
            }));
            return(style);
        }
Exemplo n.º 7
0
        /**public void getFooterWithPageNumber()
         * {
         *  foreach (Section wordSection in this.adoc.Sections)
         *  {
         *      Range footerRange = wordSection.Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
         *      footerRange.InlineShapes.AddHorizontalLineStandard();
         *      footerRange.Font.ColorIndex = WdColorIndex.wdDarkRed;
         *      footerRange.Font.Size = 10;
         *      footerRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
         *      adoc.Sections[1].Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].PageNumbers.Add();
         *  }
         * }**/

        public void generateCoverPage(string data)
        {
            body.Append(new Paragraph(new Run(new Break())));
            body.Append(new Paragraph(new Run(new Break())));
            body.Append(new Paragraph(new Run(new Break())));
            body.Append(new Paragraph(new Run(new Break())));

            //heading
            Paragraph           heading = new Paragraph();
            ParagraphProperties hp      = new ParagraphProperties();

            hp.Justification = new Justification()
            {
                Val = JustificationValues.Center
            };
            heading.Append(hp);
            Run           r             = new Run();
            RunProperties runProperties = r.AppendChild(new RunProperties());
            Bold          bold          = new Bold();

            bold.Val = OnOffValue.FromBoolean(true);
            FontSize size = new FontSize();

            size.Val = "60";
            runProperties.AppendChild(bold);
            runProperties.AppendChild(size);
            Text t = new Text(data);

            r.Append(t);
            heading.Append(r);
            body.Append(heading);

            //subheading
            Paragraph           subheading = new Paragraph();
            ParagraphProperties shp        = new ParagraphProperties();

            shp.Justification = new Justification()
            {
                Val = JustificationValues.Center
            };
            subheading.Append(shp);
            Run           rs           = new Run();
            RunProperties rhProperties = rs.AppendChild(new RunProperties());
            Bold          bs           = new Bold();

            bs.Val = OnOffValue.FromBoolean(true);
            FontSize sh = new FontSize();

            sh.Val = "40";
            rhProperties.AppendChild(bs);
            rhProperties.AppendChild(sh);
            Text subhead = new Text("BUSINESS PLAN");

            rs.Append(subhead);
            subheading.Append(rs);
            body.Append(subheading);
            addPageBreak();
        }
Exemplo n.º 8
0
        // Add the bold style at a Run object used by a Paragraph in order to insert text in a Document.
        public RunProperties getBold(Run run)
        {
            RunProperties runProperties = run.AppendChild(new RunProperties());
            var           bold          = new Bold();

            bold.Val = OnOffValue.FromBoolean(true);
            runProperties.AppendChild(bold);
            return(runProperties);
        }
Exemplo n.º 9
0
        private static RunProperties Bold()
        {
            RunProperties runProperties = new RunProperties();

            Bold bold = new Bold();

            bold.Val = OnOffValue.FromBoolean(true);
            return(runProperties);
        }
Exemplo n.º 10
0
        internal static void ManageFooterRow(Models.Document document, Models.Table table, Table wordTable, TableLook tableLook, ContextModel context, OpenXmlPart documentPart, IFormatProvider formatProvider)
        {
            // add footer row
            if (table.FooterRow != null)
            {
                wordTable.AppendChild(table.FooterRow.Render(document, wordTable, context, documentPart, false, false, formatProvider));

                tableLook.LastRow = OnOffValue.FromBoolean(true);
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// This is the addParagraph method.
        /// It is used to create a paragraph and append to body with style
        /// and preference according to the given parameters.
        /// </summary>
        /// <param name="body">the location where the content push to</param>
        /// <param name="content">the content push to the body</param>
        /// <param name="bold">determine the paragraph is bold or not</param>
        /// <param name="spacing">spacing between lines</param>
        /// <param name="insertParagraphBefore">determine whether a blank paragraph before the content push</param>
        /// <param name="insertParagraphAfter">determine whether a blank paragraph after the content push</param>
        private void addParagraph(Body body, String content, Boolean bold, int spacing, bool insertParagraphBefore, bool insertParagraphAfter, bool entryTitle = false)
        {
            // insert a new paragraph before the body
            if (insertParagraphBefore)
            {
                body.Append(new Paragraph());
            }

            ParagraphProperties pPr       = new ParagraphProperties();
            Paragraph           paragraph = new Paragraph(pPr);

            if (spacing != 0)
            {
                paragraph.ParagraphProperties.Append(new SpacingBetweenLines()
                {
                    BeforeLines = spacing,
                    AfterLines  = spacing
                });
            }

            // make header style
            if (entryTitle)
            {
                pPr.ParagraphStyleId = new ParagraphStyleId()
                {
                    Val = "entry_heading"
                };
            }

            Run run = new Run(new RunProperties());

            if (bold)
            {
                run.RunProperties.Append(new Bold()
                {
                    Val = OnOffValue.FromBoolean(true)
                });
            }

            Text text = new Text(content);

            // set text of the paragraph and append it to the body
            run.Append(text);
            paragraph.Append(run);
            body.Append(paragraph);

            // insert a new paragraph after the body
            if (insertParagraphAfter)
            {
                body.Append(new Paragraph());
            }
        }
Exemplo n.º 12
0
        public void BeforeAfter_AutoSpacingTest()
        {
            _instance.Element = new SpacingBetweenLines()
            {
                Before            = "0",
                After             = "0",
                AfterAutoSpacing  = OnOffValue.FromBoolean(true),
                BeforeAutoSpacing = new OnOffValue()
            };

            Assert.IsNull(_instance.After);
            Assert.IsNull(_instance.Before);
        }
Exemplo n.º 13
0
        private static Run GetWordTextElement(
            string text,
            int fSize,
            bool isUnderlined  = false,
            bool isSuperscript = false)
        {
            Run           run           = new Run();
            RunProperties runProperties = run.AppendChild(new RunProperties());
            Italic        italic        = new Italic();

            italic.Val = OnOffValue.FromBoolean(true);
            FontSize fontSize = new FontSize()
            {
                Val = fSize.ToString()
            };

            runProperties.AppendChild(italic);
            runProperties.AppendChild(fontSize);
            RunFonts font = new RunFonts()
            {
                Ascii         = "GOST type B",
                HighAnsi      = "GOST type B",
                ComplexScript = "GOST type B"
            };

            runProperties.Append(font);
            if (isUnderlined)
            {
                Underline underline = new Underline()
                {
                    Val = UnderlineValues.Single,
                };
                runProperties.Append(underline);
            }
            if (isSuperscript)
            {
                VerticalTextAlignment vertAlign = new VerticalTextAlignment()
                {
                    Val = VerticalPositionValues.Superscript,
                };
                runProperties.Append(vertAlign);
            }
            run.AppendChild(new Text()
            {
                Text  = text,
                Space = SpaceProcessingModeValues.Preserve,
            });
            return(run);
        }
Exemplo n.º 14
0
        private static RunProperties FontTable()
        {
            RunProperties runProperties = new RunProperties(
                new RunFonts()
            {
                Ascii = "Times New Roman",
            });

            runProperties.FontSize = new FontSize()
            {
                Val = "26"
            };
            Bold bold = new Bold();

            bold.Val = OnOffValue.FromBoolean(true);
            return(runProperties);
        }
Exemplo n.º 15
0
        public static RunProperties GetRunProperties(ResumeFont resumeFont)
        {
            var runProperties = new RunProperties();

            if (resumeFont.FontWeight == ResumeFontWeight.Bold)
            {
                var bold = new Bold
                {
                    Val = OnOffValue.FromBoolean(true)
                };
                runProperties.AppendChild(bold);
            }

            runProperties.AppendChild(GetFontSize(resumeFont));


            return(runProperties);
        }
Exemplo n.º 16
0
        // Add properties with a stykle similar to Heading 3 style at a Run object used by a Paragraph in order to insert text in a Document.
        public RunProperties getHeading3(Run run)
        {
            RunProperties runProperties = run.AppendChild(new RunProperties());
            var           bold          = new Bold();

            bold.Val = OnOffValue.FromBoolean(true);
            var color = new Color {
                Val = "365F91", ThemeColor = ThemeColorValues.Accent1, ThemeShade = "BF"
            };
            var size = new FontSize {
                Val = new StringValue("25")
            };

            runProperties.AppendChild(bold);
            runProperties.AppendChild(color);
            runProperties.AppendChild(size);
            return(runProperties);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Makes a paragraph text italic
        /// </summary>
        /// <returns></returns>
        public Paragraph Italic()
        {
            if (Runs.Count() == 0)
            {
                var paragraphProperties        = paragraph.GetOrCreate <ParagraphProperties>();
                var paragraphMarkRunProperties = paragraphProperties.GetOrCreate <ParagraphMarkRunProperties>();

                Italic Italic = paragraphMarkRunProperties.GetOrCreate <Italic>();
                Italic.Val = OnOffValue.FromBoolean(true);
            }
            else
            {
                foreach (var run in Runs)
                {
                    run.Italic();
                }
            }

            return(this);
        }
        public static string ToPlainText(System.IO.Stream stream)
        {
            using WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(stream, false);
            var hideSpellingErrors = new HideSpellingErrors();

            hideSpellingErrors.Val = OnOffValue.FromBoolean(true);
            wordprocessingDocument.MainDocumentPart.Document.Append(hideSpellingErrors);

            var sb = new StringBuilder();

            foreach (var paragraph in wordprocessingDocument.MainDocumentPart.RootElement.Descendants <Paragraph>())
            {
                foreach (var run in paragraph.Elements <Run>())
                {
                    string text = run.Elements <Text>().Aggregate("", (s, t) => s + " " + t.Text);
                    run.RemoveAllChildren <Text>();
                    run.AppendChild(new Text(text));
                    sb.Append(run.InnerText);
                }
            }
            return(sb.ToString());
        }
Exemplo n.º 19
0
        private void addParagraph(Body body, String content, Boolean bold, int spacing, bool insertParagraphBefore, bool insertParagraphAfter)
        {
            if (insertParagraphBefore)
            {
                body.Append(new Paragraph());
            }

            Paragraph paragraph = new Paragraph(new ParagraphProperties());

            if (spacing != 0)
            {
                paragraph.ParagraphProperties.Append(new SpacingBetweenLines()
                {
                    BeforeLines = spacing,
                    AfterLines  = spacing
                });
            }

            Run run = new Run(new RunProperties());

            if (bold)
            {
                run.RunProperties.Append(new Bold()
                {
                    Val = OnOffValue.FromBoolean(true)
                });
            }

            Text text = new Text(content);

            run.Append(text);
            paragraph.Append(run);
            body.Append(paragraph);

            if (insertParagraphAfter)
            {
                body.Append(new Paragraph());
            }
        }
        public OpenXmlElement SectionTitlePart(int sectionNumber)
        {
            var paragraph = new Paragraph();

            var run = new Run();

            var runProperties = new RunProperties();
            var bold          = new Bold();

            bold.Val = OnOffValue.FromBoolean(true);
            runProperties.Append(bold);

            run.Append(runProperties);

            var text = new Text($"( {sectionNumber} ) {Section}");

            run.Append(text);

            paragraph.Append(run);

            return(paragraph);
        }
Exemplo n.º 21
0
        private void SetValues(string before, string after, string lines, bool?beforeAuto = null, bool?afterAuto = null)
        {
            OnOffValue beforeAutoOnOff = null;
            OnOffValue afterAutoOnOff  = null;

            if (beforeAuto.HasValue)
            {
                beforeAutoOnOff = OnOffValue.FromBoolean(beforeAuto.Value);
            }
            if (afterAuto.HasValue)
            {
                afterAutoOnOff = OnOffValue.FromBoolean(afterAuto.Value);
            }

            _instance.Element = new SpacingBetweenLines()
            {
                Before            = before,
                After             = after,
                Line              = lines,
                BeforeAutoSpacing = beforeAutoOnOff,
                AfterAutoSpacing  = afterAutoOnOff
            };
        }
        private void AppendList(
            WordprocessingDocument wordDoc,
            IEnumerable <MarkGeneralDataPoint> markGeneralDataPoints,
            MarkOperatingConditions markOperatingConditions)
        {
            NumberingDefinitionsPart numberingPart = wordDoc.MainDocumentPart.NumberingDefinitionsPart;

            if (numberingPart == null)
            {
                numberingPart = wordDoc.MainDocumentPart.AddNewPart <NumberingDefinitionsPart>(
                    "NumberingDefinitionsPart1");
                Numbering element = new Numbering();
                element.Save(numberingPart);
            }

            var abstractNumberId = numberingPart.Numbering.Elements <AbstractNum>().Count() + 1;
            var abstractLevel    = new Level(
                new NumberingFormat()
            {
                Val = NumberFormatValues.Decimal
            },
                new LevelText()
            {
                Val = "%1"
            },
                new StartNumberingValue()
            {
                Val = 1,
            },
                new RunProperties()
            {
                RunFonts = new RunFonts()
                {
                    Ascii         = "GOST type B",
                    HighAnsi      = "GOST type B",
                    ComplexScript = "GOST type B"
                },
                Italic = new Italic()
                {
                    Val = OnOffValue.FromBoolean(true)
                },
                FontSize = new FontSize()
                {
                    Val = 26.ToString(),
                }
            })
            {
                LevelIndex = 0
            };
            var abstractLevel2 = new Level(
                new NumberingFormat()
            {
                Val = NumberFormatValues.Decimal
            },
                new LevelText()
            {
                Val = "%1.%2"
            },
                new StartNumberingValue()
            {
                Val = 1,
            },
                new RunProperties()
            {
                RunFonts = new RunFonts()
                {
                    Ascii         = "GOST type B",
                    HighAnsi      = "GOST type B",
                    ComplexScript = "GOST type B"
                },
                Italic = new Italic()
                {
                    Val = OnOffValue.FromBoolean(true)
                },
                FontSize = new FontSize()
                {
                    Val = 26.ToString(),
                }
            })
            {
                LevelIndex = 1
            };
            var abstractLevel3 = new Level(
                new NumberingFormat()
            {
                Val = NumberFormatValues.Bullet
            },
                new LevelText()
            {
                Val = "–"
            },
                new RunProperties()
            {
                RunFonts = new RunFonts()
                {
                    Ascii         = "Calibri",
                    HighAnsi      = "Calibri",
                    ComplexScript = "Calibri"
                },
            })
            {
                LevelIndex = 2
            };
            var abstractLevel4 = new Level(
                new LevelSuffix()
            {
                Val = LevelSuffixValues.Space
            })
            {
                LevelIndex = 3
            };

            var abstractNum = new AbstractNum(
                abstractLevel, abstractLevel2, abstractLevel3, abstractLevel4)
            {
                AbstractNumberId = abstractNumberId
            };

            if (abstractNumberId == 1)
            {
                numberingPart.Numbering.Append(abstractNum);
            }
            else
            {
                AbstractNum lastAbstractNum = numberingPart.Numbering.Elements <AbstractNum>().Last();
                numberingPart.Numbering.InsertAfter(abstractNum, lastAbstractNum);
            }

            var numberId = numberingPart.Numbering.Elements <NumberingInstance>().Count() + 1;
            NumberingInstance numberingInstance = new NumberingInstance()
            {
                NumberID = numberId
            };
            AbstractNumId abstractNumId = new AbstractNumId()
            {
                Val = abstractNumberId
            };

            numberingInstance.Append(abstractNumId);

            if (numberId == 1)
            {
                numberingPart.Numbering.Append(numberingInstance);
            }
            else
            {
                var lastNumberingInstance = numberingPart.Numbering.Elements <NumberingInstance>().Last();
                numberingPart.Numbering.InsertAfter(numberingInstance, lastNumberingInstance);
            }

            Body body = wordDoc.MainDocumentPart.Document.Body;
            var  markGeneralDataPointsList = markGeneralDataPoints.ToList();

            for (var i = 0; i < markGeneralDataPoints.Count(); i++)
            {
                var item = markGeneralDataPointsList[i];
                var spacingBetweenLines = new SpacingBetweenLines()
                {
                    After = "120", Line = "240"
                };
                var indentation = new Indentation()
                {
                    Left = "360", Right = "360", FirstLine = "720"
                };

                NumberingProperties numberingProperties;
                var pointText = item.Text;
                if (item.OrderNum == 1)
                {
                    numberingProperties = new NumberingProperties(
                        new NumberingLevelReference()
                    {
                        Val = 0
                    }, new NumberingId()
                    {
                        Val = numberId
                    });
                }
                else if (item.Text[0] == '#' && item.Text[1] == ' ')
                {
                    numberingProperties = new NumberingProperties(
                        new NumberingLevelReference()
                    {
                        Val = 1
                    }, new NumberingId()
                    {
                        Val = numberId
                    });

                    pointText = pointText.Substring(2) + ".";
                }
                else if (item.Text[0] == '-' && item.Text[1] == ' ')
                {
                    numberingProperties = new NumberingProperties(
                        new NumberingLevelReference()
                    {
                        Val = 2
                    }, new NumberingId()
                    {
                        Val = numberId
                    });

                    if (i == 0)
                    {
                        pointText = pointText.Substring(2) + ".";
                    }
                    else if (markGeneralDataPointsList[i - 1].OrderNum == 1)
                    {
                        pointText = pointText.Substring(2) + ".";
                    }
                    else if (markGeneralDataPointsList[i - 1].Text[0] == '#' &&
                             markGeneralDataPointsList[i - 1].Text[1] == ' ')
                    {
                        pointText = pointText.Substring(2) + ".";
                    }
                    else
                    {
                        pointText = pointText.Substring(2) + ";";
                    }
                }
                else
                {
                    numberingProperties = new NumberingProperties(
                        new NumberingLevelReference()
                    {
                        Val = 3
                    }, new NumberingId()
                    {
                        Val = numberId
                    });
                    pointText   = pointText + ".";
                    indentation = new Indentation()
                    {
                        Left = "360", Right = "360", FirstLine = "640"
                    };
                }

                var paragraphProperties = new ParagraphProperties(
                    numberingProperties, spacingBetweenLines, indentation);
                var newPara = new Paragraph(paragraphProperties);

                if (item.Section.Id == 7)
                {
                    if (pointText.Contains("коэффициент надежности по ответственности"))
                    {
                        pointText = pointText.Replace("{}", markOperatingConditions.SafetyCoeff.ToString());
                    }
                    else if (pointText.Contains("степень агрессивного воздействия среды"))
                    {
                        pointText = pointText.Replace("{}", markOperatingConditions.EnvAggressiveness.Name);
                    }
                    else if (pointText.Contains("расчетная температура эксплуатации"))
                    {
                        pointText = pointText.Replace("{}",
                                                      $"{(markOperatingConditions.Temperature < 0 ? ("минус " + -markOperatingConditions.Temperature) : markOperatingConditions.Temperature)}");
                    }
                }

                if (pointText.Contains('^'))
                {
                    var split = pointText.Split('^');
                    if (split.Count() > 1)
                    {
                        for (int k = 0; k < split.Count(); k++)
                        {
                            if (k > 0)
                            {
                                newPara.AppendChild(Word.GetTextElement(split[k][0].ToString(), 26, false, true));
                            }
                            if (k == 0)
                            {
                                newPara.AppendChild(Word.GetTextElement(split[k], 26));
                            }
                            else
                            if (split[k].Length > 1)
                            {
                                newPara.AppendChild(Word.GetTextElement(split[k].Substring(1), 26));
                            }
                        }
                    }
                    else
                    {
                        newPara.AppendChild(Word.GetTextElement(pointText, 26));
                    }
                }
                else
                {
                    newPara.AppendChild(Word.GetTextElement(pointText, 26));
                }
                body.PrependChild(newPara);
            }
        }
Exemplo n.º 23
0
        /*
         * This is the addTable method.
         * It is used to append to the body of the word document from given table.
         */
        private void addTable(Body body, Dictionary <KeyValuePair <int, int>, String> t)
        {
            Table table = new Table();

            // Create a TableProperties object and specify its border information.
            TableProperties tblProp = new TableProperties(
                new TableBorders(
                    new TopBorder()
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 2
            },
                    new BottomBorder()
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 2
            },
                    new LeftBorder()
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 2
            },
                    new RightBorder()
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 2
            },
                    new InsideHorizontalBorder()
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 2
            },
                    new InsideVerticalBorder()
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 2
            }
                    )
                );

            // Append the TableProperties object to the empty table.
            table.AppendChild <TableProperties>(tblProp);

            for (int r = 1; r <= 6; r++)
            {
                // Create a row.
                TableRow tr = new TableRow();

                // Create two table cells.
                TableCell tc1 = new TableCell();
                TableCell tc2 = new TableCell();

                // Specify the width property of the table cell.
                tc1.Append(new TableCellProperties(
                               new TableCellWidth()
                {
                    Type  = TableWidthUnitValues.Dxa,
                    Width = "2400"
                }));
                tc2.Append(new TableCellProperties(
                               new TableCellWidth()
                {
                    Type  = TableWidthUnitValues.Dxa,
                    Width = "10000"
                }));

                // Specify the table cell content.
                tc1.Append(new Paragraph(new Run(new Text(t[new KeyValuePair <int, int>(r, 1)]))));

                String[] s = t[new KeyValuePair <int, int>(r, 2)].Split('\n');
                foreach (String tempString in s)
                {
                    tc2.Append(new Paragraph(new ParagraphProperties(
                                                 new SpacingBetweenLines()
                    {
                        Before            = "0",
                        After             = "0",
                        BeforeAutoSpacing = OnOffValue.FromBoolean(false),
                        AfterAutoSpacing  = OnOffValue.FromBoolean(false)
                    })
                    {
                    }, new Run(new RunProperties()
                    {
                    }, new Text(tempString))));
                }

                // Append the table cell to the table row.
                tr.Append(tc1);
                tr.Append(tc2);

                // Append the table row to the table.
                table.Append(tr);
            }

            body.Append(table);
        }
        /// <summary>
        /// There is a few attributes shared by a large number of tags. This method will check them for a limited
        /// number of tags (&lt;p&gt;, &lt;pre&gt;, &lt;div&gt;, &lt;span&gt; and &lt;body&gt;).
        /// </summary>
        /// <returns>Returns true if the processing of this tag should generate a new paragraph.</returns>
        public bool ProcessCommonAttributes(HtmlEnumerator en, IList <OpenXmlElement> styleAttributes)
        {
            if (en.Attributes.Count == 0)
            {
                return(false);
            }

            bool newParagraph = false;
            List <OpenXmlElement> containerStyleAttributes = new List <OpenXmlElement>();

            string attrValue = en.Attributes["lang"];

            if (attrValue != null && attrValue.Length > 0)
            {
                try
                {
                    var  ci  = System.Globalization.CultureInfo.GetCultureInfo(attrValue);
                    bool rtl = ci.TextInfo.IsRightToLeft;

                    Languages lang = new Languages()
                    {
                        Val = ci.TwoLetterISOLanguageName
                    };
                    if (rtl)
                    {
                        lang.Bidi = ci.Name;
                        styleAttributes.Add(new Languages()
                        {
                            Bidi = ci.Name
                        });

                        // notify table
                        documentStyle.Tables.BeginTag(en.CurrentTag, new TableJustification()
                        {
                            Val = TableRowAlignmentValues.Right
                        });
                    }

                    containerStyleAttributes.Add(new ParagraphMarkRunProperties(lang));
                    containerStyleAttributes.Add(new BiDi()
                    {
                        Val = OnOffValue.FromBoolean(rtl)
                    });
                }
                catch (ArgumentException)
                {
                    // lang not valid, ignore it
                }
            }


            attrValue = en.StyleAttributes["text-align"];
            if (attrValue != null && en.CurrentTag != "<font>")
            {
                JustificationValues?align = ConverterUtility.FormatParagraphAlign(attrValue);
                if (align.HasValue)
                {
                    containerStyleAttributes.Add(new Justification {
                        Val = align
                    });
                }
            }

            // according to w3c, dir should be used in conjonction with lang. But whatever happens, we'll apply the RTL layout
            attrValue = en.Attributes["dir"];
            if (attrValue != null)
            {
                if (attrValue.Equals("rtl", StringComparison.OrdinalIgnoreCase))
                {
                    styleAttributes.Add(new RightToLeftText());
                    containerStyleAttributes.Add(new Justification()
                    {
                        Val = JustificationValues.Right
                    });
                }
                else if (attrValue.Equals("ltr", StringComparison.OrdinalIgnoreCase))
                {
                    containerStyleAttributes.Add(new Justification()
                    {
                        Val = JustificationValues.Left
                    });
                }
            }

            // <span> and <font> are considered as semi-container attribute. When converted to OpenXml, there are Runs but not Paragraphs
            if (en.CurrentTag == "<p>" || en.CurrentTag == "<div>" || en.CurrentTag == "<pre>")
            {
                var border = en.StyleAttributes.GetAsBorder("border");
                if (!border.IsEmpty)
                {
                    ParagraphBorders borders = new ParagraphBorders();
                    if (border.Top.IsValid)
                    {
                        borders.Append(
                            new TopBorder()
                        {
                            Val = border.Top.Style, Color = border.Top.Color.ToHexString(), Size = (uint)border.Top.Width.ValueInPx * 4, Space = 1U
                        });
                    }
                    if (border.Left.IsValid)
                    {
                        borders.Append(
                            new LeftBorder()
                        {
                            Val = border.Left.Style, Color = border.Left.Color.ToHexString(), Size = (uint)border.Left.Width.ValueInPx * 4, Space = 1U
                        });
                    }
                    if (border.Bottom.IsValid)
                    {
                        borders.Append(
                            new BottomBorder()
                        {
                            Val = border.Bottom.Style, Color = border.Bottom.Color.ToHexString(), Size = (uint)border.Bottom.Width.ValueInPx * 4, Space = 1U
                        });
                    }
                    if (border.Right.IsValid)
                    {
                        borders.Append(
                            new RightBorder()
                        {
                            Val = border.Right.Style, Color = border.Right.Color.ToHexString(), Size = (uint)border.Right.Width.ValueInPx * 4, Space = 1U
                        });
                    }

                    containerStyleAttributes.Add(borders);
                    newParagraph = true;
                }
            }
            else if (en.CurrentTag == "<span>" || en.CurrentTag == "<font>")
            {
                // OpenXml limits the border to 4-side of the same color and style.
                SideBorder border = en.StyleAttributes.GetAsSideBorder("border");
                if (border.IsValid)
                {
                    styleAttributes.Add(new DocumentFormat.OpenXml.Wordprocessing.Border()
                    {
                        Val   = border.Style,
                        Color = border.Color.ToHexString(),
                        Size  = (uint)border.Width.ValueInPx * 4,
                        Space = 1U
                    });
                }
            }

            String[] classes = en.Attributes.GetAsClass();
            if (classes != null)
            {
                for (int i = 0; i < classes.Length; i++)
                {
                    string className = documentStyle.GetStyle(classes[i], StyleValues.Paragraph, ignoreCase: true);
                    if (className != null)
                    {
                        containerStyleAttributes.Add(new ParagraphStyleId()
                        {
                            Val = className
                        });
                        newParagraph = true;
                        break;
                    }
                }
            }

            Margin      margin      = en.StyleAttributes.GetAsMargin("margin");
            Indentation indentation = null;

            if (!margin.IsEmpty)
            {
                if (margin.Top.IsFixed || margin.Bottom.IsFixed)
                {
                    SpacingBetweenLines spacing = new SpacingBetweenLines();
                    if (margin.Top.IsFixed)
                    {
                        spacing.Before = margin.Top.ValueInDxa.ToString(CultureInfo.InvariantCulture);
                    }
                    if (margin.Bottom.IsFixed)
                    {
                        spacing.After = margin.Bottom.ValueInDxa.ToString(CultureInfo.InvariantCulture);
                    }
                    containerStyleAttributes.Add(spacing);
                }
                if (margin.Left.IsFixed || margin.Right.IsFixed)
                {
                    indentation = new Indentation();
                    if (margin.Left.IsFixed)
                    {
                        indentation.Left = margin.Left.ValueInDxa.ToString(CultureInfo.InvariantCulture);
                    }
                    if (margin.Right.IsFixed)
                    {
                        indentation.Right = margin.Right.ValueInDxa.ToString(CultureInfo.InvariantCulture);
                    }
                    containerStyleAttributes.Add(indentation);
                }
            }

            // implemented by giorand (feature #13787)
            Unit textIndent = en.StyleAttributes.GetAsUnit("text-indent");

            if (textIndent.IsValid && (en.CurrentTag == "<p>" || en.CurrentTag == "<div>"))
            {
                if (indentation == null)
                {
                    indentation = new Indentation();
                }
                indentation.FirstLine = textIndent.ValueInDxa.ToString(CultureInfo.InvariantCulture);
                containerStyleAttributes.Add(indentation);
            }

            this.BeginTag(en.CurrentTag, containerStyleAttributes);

            // Process general run styles
            documentStyle.Runs.ProcessCommonAttributes(en, styleAttributes);

            return(newParagraph);
        }
Exemplo n.º 25
0
        protected void btnIspisi_Click(object sender, EventArgs e)
        {
            Body      body;
            Paragraph par;
            Run       run;

            DocumentFormat.OpenXml.Wordprocessing.TableRow  tr;
            DocumentFormat.OpenXml.Wordprocessing.TableCell tc;
            TableCellProperties tcp;
            RunProperties       rp;

            WordprocessingDocument package = WordprocessingDocument.Create(HttpRuntime.AppDomainAppPath + "\\izleti.docx", WordprocessingDocumentType.Document);

            package.AddMainDocumentPart();

            Document document = new Document();

            package.MainDocumentPart.Document = document;
            body = document.AppendChild(new Body());
            SectionProperties sectionProps = body.AppendChild(new SectionProperties());

            sectionProps.Append(new PageMargin()
            {
                Top = 720, Right = 720, Bottom = 720, Left = 720, Header = 0, Footer = 0, Gutter = 0
            });                                                                                                                             // 1440 = 1", 720 = 0.5";

            par = body.AppendChild(new Paragraph());
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.AppendChild(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            rp.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.FontSize()
            {
                Val = "32"
            });
            run.AppendChild(new Text("Izleti"));

            DocumentFormat.OpenXml.Wordprocessing.Table table = new DocumentFormat.OpenXml.Wordprocessing.Table();
            TableProperties props = new TableProperties
                                    (
                new TableBorders
                (
                    new TableWidth {
                Width = "5000", Type = TableWidthUnitValues.Pct
            },                                                                                  // 100%
                    new TopBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.None),
                Size = 6
            },
                    new BottomBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 6
            },
                    new LeftBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.None),
                Size = 6
            },
                    new RightBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.None),
                Size = 6
            },
                    new InsideHorizontalBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.Single),
                Size = 6
            },
                    new InsideVerticalBorder
            {
                Val  = new EnumValue <BorderValues>(BorderValues.None),
                Size = 6
            }
                )
                                    );

            table.AppendChild <TableProperties>(props);

            // red
            tr = table.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableRow());
            // ćelija
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black"
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Color()
            {
                Val = "ffffff"
            });
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            run.Append(new Text("Datum"));
            // ćelija
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black"
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Color()
            {
                Val = "ffffff"
            });
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            run.Append(new Text("Naziv"));
            // ćelija
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black"
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Color()
            {
                Val = "ffffff"
            });
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            run.Append(new Text("Glavni vodič"));
            // ćelija
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black"
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Color()
            {
                Val = "ffffff"
            });
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            run.Append(new Text("Pomoćni vodič"));
            // ćelija
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black"
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Color()
            {
                Val = "ffffff"
            });
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            run.Append(new Text("Udruga"));
            // ćelija
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black"
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Color()
            {
                Val = "ffffff"
            });
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            run.Append(new Text("Odredište"));
            // ćelija
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black"
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Color()
            {
                Val = "ffffff"
            });
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            run.Append(new Text("Trajanje"));
            // ćelija
            tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
            tcp = tc.AppendChild(new TableCellProperties());
            tcp.Append(new Shading()
            {
                Val = ShadingPatternValues.Clear, Color = "auto", Fill = "black"
            });
            par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
            {
                Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
            })));
            run = par.AppendChild(new Run());
            rp  = run.AppendChild(new RunProperties());
            rp.Append(new Color()
            {
                Val = "ffffff"
            });
            rp.Append(new Bold()
            {
                Val = OnOffValue.FromBoolean(true)
            });
            run.Append(new Text("Broj sudionika"));

            string          query = "select izleti.datum, izleti.naziv, vodicig.prezime + ', ' + vodicig.ime as glavnivodic, vodicip.prezime + ', ' + vodicip.ime as pomocnivodic, udruge.naziv as udruga, izleti.odrediste, izleti.trajanje, izleti.brojsudionika from ((izleti left join vodici as vodicig on izleti.glavni_vod_id = vodicig.id) left join vodici as vodicip on izleti.pomocni_vod_id = vodicip.id) left join udruge on izleti.udr_id = udruge.id where 1 = 1 " + ViewState["filter"] + " order by datum desc";
            OleDbConnection con   = new OleDbConnection(ConfigurationManager.ConnectionStrings["connstr"].ConnectionString);
            OleDbCommand    cmd   = new OleDbCommand();

            cmd.CommandText = query;
            cmd.CommandType = CommandType.Text;
            cmd.Connection  = con;
            con.Open();
            OleDbDataReader dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                tr  = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
                tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
                tcp = tc.AppendChild(new TableCellProperties());
                par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
                {
                    Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
                })));
                run = par.AppendChild(new Run());
                rp  = run.AppendChild(new RunProperties());
                run.Append(new Text(Convert.ToDateTime(dr["datum"]).ToString("dd.MM.yyyy.")));

                tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
                tcp = tc.AppendChild(new TableCellProperties());
                par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
                {
                    Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
                })));
                run = par.AppendChild(new Run());
                rp  = run.AppendChild(new RunProperties());
                run.Append(new Text(dr["naziv"] as string));

                tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
                tcp = tc.AppendChild(new TableCellProperties());
                par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
                {
                    Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
                })));
                run = par.AppendChild(new Run());
                rp  = run.AppendChild(new RunProperties());
                run.Append(new Text(dr["glavnivodic"] as string));

                tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
                tcp = tc.AppendChild(new TableCellProperties());
                par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
                {
                    Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
                })));
                run = par.AppendChild(new Run());
                rp  = run.AppendChild(new RunProperties());
                run.Append(new Text(dr["pomocnivodic"] as string));

                tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
                tcp = tc.AppendChild(new TableCellProperties());
                par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
                {
                    Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
                })));
                run = par.AppendChild(new Run());
                rp  = run.AppendChild(new RunProperties());
                run.Append(new Text(dr["udruga"] as string));

                tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
                tcp = tc.AppendChild(new TableCellProperties());
                par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
                {
                    Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
                })));
                run = par.AppendChild(new Run());
                rp  = run.AppendChild(new RunProperties());
                run.Append(new Text(dr["odrediste"] as string));

                tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
                tcp = tc.AppendChild(new TableCellProperties());
                par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
                {
                    Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
                })));
                run = par.AppendChild(new Run());
                rp  = run.AppendChild(new RunProperties());
                run.Append(new Text(dr["trajanje"].ToString()));

                tc  = tr.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.TableCell());
                tcp = tc.AppendChild(new TableCellProperties());
                par = tc.AppendChild(new Paragraph(new ParagraphProperties(new SpacingBetweenLines()
                {
                    Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0"
                })));
                run = par.AppendChild(new Run());
                rp  = run.AppendChild(new RunProperties());
                run.Append(new Text(dr["brojsudionika"].ToString()));

                table.Append(tr);
            }
            document.Body.Append(table);
            document.Save();
            package.Close();

            con.Close();

            Response.ContentType = "Application/docx";
            Response.AppendHeader("Content-Disposition", "attachment; filename=izleti.docx");
            Response.TransmitFile(HttpRuntime.AppDomainAppPath + "\\izleti.docx");
            Response.End();
        }
Exemplo n.º 26
0
        private static void AddStyles(MainDocumentPart mainPart)
        {
            var part = mainPart.StyleDefinitionsPart;

            if (part == null)
            {
                part = mainPart.AddNewPart <StyleDefinitionsPart>();
                new Styles().Save(part);
            }

            var latent = new LatentStyles(
                new LatentStyleExceptionInfo
            {
                Name = "Normal", UiPriority = 0, PrimaryStyle = OnOffValue.FromBoolean(true)
            },
                new LatentStyleExceptionInfo
            {
                Name           = "No List", SemiHidden = OnOffValue.FromBoolean(true),
                UnhideWhenUsed = OnOffValue.FromBoolean(true)
            },
                new LatentStyleExceptionInfo
            {
                Name = "List Paragraph", UiPriority = 34, PrimaryStyle = OnOffValue.FromBoolean(true)
            })
            {
                DefaultLockedState    = OnOffValue.FromBoolean(false),
                DefaultUiPriority     = 99,
                DefaultSemiHidden     = OnOffValue.FromBoolean(false),
                DefaultUnhideWhenUsed = OnOffValue.FromBoolean(false),
                DefaultPrimaryStyle   = OnOffValue.FromBoolean(false)
            };

            var normalStyle = new Style(
                new PrimaryStyle()
                )
            {
                StyleId   = "Normal",
                StyleName = new StyleName {
                    Val = "Normal"
                }
            };

            var numbering = new Style(
                new StyleName {
                Val = "No List"
            },
                new UIPriority {
                Val = 99
            },
                new SemiHidden(),
                new UnhideWhenUsed()
                )
            {
                Type    = StyleValues.Numbering,
                Default = OnOffValue.FromBoolean(true),
                StyleId = "NoList"
            };


            var listParagraphStyle = new Style(
                new PrimaryStyle(),
                new ParagraphProperties(
                    new Indentation {
                Left = new Unit(0.25, UnitType.inch)
            },
                    new ContextualSpacing()
                    ))
            {
                Type      = StyleValues.Paragraph,
                StyleId   = "ListParagraph",
                StyleName = new StyleName {
                    Val = "List Paragraph"
                },
                BasedOn = new BasedOn {
                    Val = "Normal"
                },
                UIPriority = new UIPriority {
                    Val = 34
                }
            };

            part.Styles.Append(latent, numbering, normalStyle, listParagraphStyle);

            part.Styles.Save();
        }
Exemplo n.º 27
0
        internal static Styles DefaultStyle()
        {
            var element =
                new Styles(
                    //Create the normal style
                    new Style(
                        new StyleName()
            {
                Val = "Normal"
            },
                        new PrimaryStyle()
                        )
            {
                Type = StyleValues.Paragraph, StyleId = "Normal", Default = OnOffValue.FromBoolean(true)
            },
                    //Create the style for heading 1
                    new Style(
                        new StyleName()
            {
                Val = "heading 1"
            },
                        new BasedOn()
            {
                Val = "Normal"
            },
                        new NextParagraphStyle()
            {
                Val = "Normal"
            },
                        new UIPriority()
            {
                Val = 9
            },
                        new PrimaryStyle(),
                        new Rsid()
            {
                Val = new HexBinaryValue()
                {
                    Value = "00596592"
                }
            },
                        new StyleParagraphProperties(
                            new KeepNext(),
                            new KeepLines(),
                            new SpacingBetweenLines()
            {
                Before = "480", After = "0"
            },
                            new OutlineLevel()
            {
                Val = 0
            }),
                        new StyleRunProperties(
                            new RunFonts()
            {
                AsciiTheme = ThemeFontValues.MajorHighAnsi, HighAnsiTheme = ThemeFontValues.MajorHighAnsi, EastAsiaTheme = ThemeFontValues.MajorEastAsia, ComplexScriptTheme = ThemeFontValues.MajorBidi
            },
                            new Bold(),
                            new BoldComplexScript(),
                            new Color()
            {
                Val = "365F91", ThemeColor = ThemeColorValues.Accent1, ThemeShade = "BF"
            },
                            new FontSize()
            {
                Val = "28"
            },
                            new FontSizeComplexScript()
            {
                Val = "28"
            })
                        )
            {
                Type = StyleValues.Paragraph, StyleId = "Heading1"
            },
                    //Create the style for heading 2
                    new Style(
                        new StyleName()
            {
                Val = "heading 2"
            },
                        new BasedOn()
            {
                Val = "Normal"
            },
                        new NextParagraphStyle()
            {
                Val = "Normal"
            },
                        new LinkedStyle()
            {
                Val = "Heading2Char"
            },
                        new UIPriority()
            {
                Val = 9
            },
                        new UnhideWhenUsed(),
                        new PrimaryStyle(),
                        new Rsid()
            {
                Val = new HexBinaryValue()
                {
                    Value = "00CC42C0"
                }
            },
                        new StyleParagraphProperties(
                            new KeepNext(),
                            new KeepLines(),
                            new SpacingBetweenLines()
            {
                Before = "200", After = "0"
            },
                            new OutlineLevel()
            {
                Val = 1
            }),
                        new StyleRunProperties(
                            new RunFonts()
            {
                AsciiTheme = ThemeFontValues.MajorHighAnsi, HighAnsiTheme = ThemeFontValues.MajorHighAnsi, EastAsiaTheme = ThemeFontValues.MajorEastAsia, ComplexScriptTheme = ThemeFontValues.MajorBidi
            },
                            new Bold(),
                            new BoldComplexScript(),
                            new Color()
            {
                Val = "4F81BD", ThemeColor = ThemeColorValues.Accent1
            },
                            new FontSize()
            {
                Val = "26"
            },
                            new FontSizeComplexScript()
            {
                Val = "26"
            })
                        )
            {
                Type = StyleValues.Paragraph, StyleId = "Heading2"
            },
                    //Create the style for heading 3
                    new Style(
                        new StyleName()
            {
                Val = "heading 3"
            },
                        new BasedOn()
            {
                Val = "Normal"
            },
                        new NextParagraphStyle()
            {
                Val = "Normal"
            },
                        new LinkedStyle()
            {
                Val = "Heading3Char"
            },
                        new UIPriority()
            {
                Val = 9
            },
                        new UnhideWhenUsed(),
                        new PrimaryStyle(),
                        new Rsid()
            {
                Val = new HexBinaryValue()
                {
                    Value = "00CC42C0"
                }
            },
                        new StyleParagraphProperties(
                            new KeepNext(),
                            new KeepLines(),
                            new SpacingBetweenLines()
            {
                Before = "200", After = "0"
            },
                            new OutlineLevel()
            {
                Val = 2
            }),
                        new StyleRunProperties(
                            new RunFonts()
            {
                AsciiTheme = ThemeFontValues.MajorHighAnsi, HighAnsiTheme = ThemeFontValues.MajorHighAnsi, EastAsiaTheme = ThemeFontValues.MajorEastAsia, ComplexScriptTheme = ThemeFontValues.MajorBidi
            },
                            new Bold(),
                            new BoldComplexScript(),
                            new Color()
            {
                Val = "4F81BD", ThemeColor = ThemeColorValues.Accent1
            })
                        )
            {
                Type = StyleValues.Paragraph, StyleId = "Heading3"
            },
                    //Create a bullet list style
                    new Style(
                        new StyleName()
            {
                Val = "List Paragraph"
            },
                        new BasedOn()
            {
                Val = "Normal"
            },
                        new UIPriority()
            {
                Val = 34
            },
                        new PrimaryStyle(),
                        new Rsid()
            {
                Val = new HexBinaryValue()
                {
                    Value = "00C87658"
                }
            },
                        new StyleParagraphProperties(
                            new Indentation()
            {
                Left = "720"
            },
                            new ContextualSpacing())
                        )
            {
                Type = StyleValues.Paragraph, StyleId = "ListParagraph"
            }
                    );

            return(element);
        }
Exemplo n.º 28
0
        public static void AppendList(
            WordprocessingDocument wordDoc, IEnumerable <MarkGeneralDataPoint> markGeneralDataPoints)
        {
            NumberingDefinitionsPart numberingPart = wordDoc.MainDocumentPart.NumberingDefinitionsPart;

            if (numberingPart == null)
            {
                numberingPart = wordDoc.MainDocumentPart.AddNewPart <NumberingDefinitionsPart>(
                    "NumberingDefinitionsPart1");
                Numbering element = new Numbering();
                element.Save(numberingPart);
            }

            var abstractNumberId = numberingPart.Numbering.Elements <AbstractNum>().Count() + 1;
            var abstractLevel    = new Level(
                new NumberingFormat()
            {
                Val = NumberFormatValues.Decimal
            },
                new LevelText()
            {
                Val = "%1"
            },
                new StartNumberingValue()
            {
                Val = 1,
            },
                new RunProperties()
            {
                RunFonts = new RunFonts()
                {
                    Ascii         = "GOST type B",
                    HighAnsi      = "GOST type B",
                    ComplexScript = "GOST type B"
                },
                Italic = new Italic()
                {
                    Val = OnOffValue.FromBoolean(true)
                },
                FontSize = new FontSize()
                {
                    Val = 26.ToString(),
                }
            })
            {
                LevelIndex = 0
            };
            var abstractLevel2 = new Level(
                new NumberingFormat()
            {
                Val = NumberFormatValues.Decimal
            },
                new LevelText()
            {
                Val = "%1.%2"
            },
                new StartNumberingValue()
            {
                Val = 1,
            },
                new RunProperties()
            {
                RunFonts = new RunFonts()
                {
                    Ascii         = "GOST type B",
                    HighAnsi      = "GOST type B",
                    ComplexScript = "GOST type B"
                },
                Italic = new Italic()
                {
                    Val = OnOffValue.FromBoolean(true)
                },
                FontSize = new FontSize()
                {
                    Val = 26.ToString(),
                }
            })
            {
                LevelIndex = 1
            };
            var abstractLevel3 = new Level(
                new NumberingFormat()
            {
                Val = NumberFormatValues.Bullet
            },
                new LevelText()
            {
                Val = "–"
            },
                new RunProperties()
            {
                RunFonts = new RunFonts()
                {
                    Ascii         = "Calibri",
                    HighAnsi      = "Calibri",
                    ComplexScript = "Calibri"
                },
            })
            {
                LevelIndex = 2
            };
            var abstractLevel4 = new Level(
                new LevelSuffix()
            {
                Val = LevelSuffixValues.Space
            })
            {
                LevelIndex = 3
            };

            var abstractNum = new AbstractNum(
                abstractLevel, abstractLevel2, abstractLevel3, abstractLevel4)
            {
                AbstractNumberId = abstractNumberId
            };

            if (abstractNumberId == 1)
            {
                numberingPart.Numbering.Append(abstractNum);
            }
            else
            {
                AbstractNum lastAbstractNum = numberingPart.Numbering.Elements <AbstractNum>().Last();
                numberingPart.Numbering.InsertAfter(abstractNum, lastAbstractNum);
            }

            var numberId = numberingPart.Numbering.Elements <NumberingInstance>().Count() + 1;
            NumberingInstance numberingInstance = new NumberingInstance()
            {
                NumberID = numberId
            };
            AbstractNumId abstractNumId = new AbstractNumId()
            {
                Val = abstractNumberId
            };

            numberingInstance.Append(abstractNumId);

            if (numberId == 1)
            {
                numberingPart.Numbering.Append(numberingInstance);
            }
            else
            {
                var lastNumberingInstance = numberingPart.Numbering.Elements <NumberingInstance>().Last();
                numberingPart.Numbering.InsertAfter(numberingInstance, lastNumberingInstance);
            }

            Body body = wordDoc.MainDocumentPart.Document.Body;
            var  markGeneralDataPointsList = markGeneralDataPoints.ToList();

            for (var i = 0; i < markGeneralDataPoints.Count(); i++)
            {
                var item = markGeneralDataPointsList[i];
                var spacingBetweenLines = new SpacingBetweenLines()
                {
                    After = "120", Line = "240"
                };
                var indentation = new Indentation()
                {
                    Left = "360", Right = "360", FirstLine = "720"
                };

                NumberingProperties numberingProperties;
                var pointText = item.Text;
                if (item.OrderNum == 1)
                {
                    numberingProperties = new NumberingProperties(
                        new NumberingLevelReference()
                    {
                        Val = 0
                    }, new NumberingId()
                    {
                        Val = numberId
                    });
                }
                else if (item.Text[0] == '#' && item.Text[1] == ' ')
                {
                    numberingProperties = new NumberingProperties(
                        new NumberingLevelReference()
                    {
                        Val = 1
                    }, new NumberingId()
                    {
                        Val = numberId
                    });

                    pointText = pointText.Substring(2) + ".";
                }
                else if (item.Text[0] == '-' && item.Text[1] == ' ')
                {
                    numberingProperties = new NumberingProperties(
                        new NumberingLevelReference()
                    {
                        Val = 2
                    }, new NumberingId()
                    {
                        Val = numberId
                    });

                    if (i == 0)
                    {
                        pointText = pointText.Substring(2) + ".";
                    }
                    else if (markGeneralDataPointsList[i - 1].OrderNum == 1)
                    {
                        pointText = pointText.Substring(2) + ".";
                    }
                    else if (markGeneralDataPointsList[i - 1].Text[0] == '#' &&
                             markGeneralDataPointsList[i - 1].Text[1] == ' ')
                    {
                        pointText = pointText.Substring(2) + ".";
                    }
                    else
                    {
                        pointText = pointText.Substring(2) + ";";
                    }
                }
                else
                {
                    numberingProperties = new NumberingProperties(
                        new NumberingLevelReference()
                    {
                        Val = 3
                    }, new NumberingId()
                    {
                        Val = numberId
                    });
                    pointText   = pointText + ".";
                    indentation = new Indentation()
                    {
                        Left = "360", Right = "360", FirstLine = "640"
                    };
                }

                var paragraphProperties = new ParagraphProperties(
                    numberingProperties, spacingBetweenLines, indentation);
                var newPara = new Paragraph(paragraphProperties);

                if (pointText.Contains('^'))
                {
                    var split = pointText.Split('^');
                    if (split.Count() > 1)
                    {
                        for (int k = 0; k < split.Count(); k++)
                        {
                            if (k > 0)
                            {
                                newPara.AppendChild(GetWordTextElement(split[k][0].ToString(), 26, false, true));
                            }
                            if (k == 0)
                            {
                                newPara.AppendChild(GetWordTextElement(split[k], 26));
                            }
                            else
                            if (split[k].Length > 1)
                            {
                                newPara.AppendChild(GetWordTextElement(split[k].Substring(1), 26));
                            }
                        }
                    }
                    else
                    {
                        newPara.AppendChild(GetWordTextElement(pointText, 26));
                    }
                }
                else
                {
                    newPara.AppendChild(GetWordTextElement(pointText, 26));
                }
                // if (pointText.Contains('^'))
                // {
                //     var split = pointText.Split("^2");
                //     if (split.Count() > 1)
                //     {
                //         for (int k = 0; k < split.Count(); k++)
                //         {
                //             if (k > 0)
                //             {
                //                 newPara.AppendChild(GetWordTextElement("2", 26, false, true));
                //             }
                //             newPara.AppendChild(GetWordTextElement(split[k], 26));
                //         }
                //         // var split2 = s.Split("^3");
                //         // if (s.Count() > 1)
                //         // {

                //         // }
                //     }
                //     else
                //     {
                //         split = pointText.Split("^3");
                //         if (split.Count() > 1)
                //         {
                //             for (int k = 0; k < split.Count(); k++)
                //             {
                //                 if (k > 0)
                //                 {
                //                     newPara.AppendChild(GetWordTextElement("3", 26, false, true));
                //                 }
                //                 newPara.AppendChild(GetWordTextElement(split[k], 26));
                //             }
                //         }
                //         else
                //             newPara.AppendChild(GetWordTextElement(pointText, 26));
                //     }
                // }
                // else
                //     newPara.AppendChild(GetWordTextElement(pointText, 26));
                body.PrependChild(newPara);
            }
        }
Exemplo n.º 29
0
        public void OpenXmlSimpleTypeConverterTest()
        {
            // 1. Base64BinaryValue
            Base64BinaryValue base64 = new Base64BinaryValue();

            base64 = "AA3322";
            Assert.True(base64 == "AA3322");
            Assert.Equal("AA3322", base64.Value);
            base64 = Base64BinaryValue.FromString("1234");
            Assert.Equal("1234", base64.ToString());
            Assert.Equal("1234", Base64BinaryValue.ToString(base64));

            // 2. BooleanValue
            BooleanValue booleanValue = new BooleanValue();

            booleanValue = true;
            Assert.True(booleanValue);
            Assert.True(booleanValue.Value);
            booleanValue = BooleanValue.FromBoolean(false);
            Assert.False(booleanValue);
            Assert.False(BooleanValue.ToBoolean(booleanValue));

            // 3. ByteValue
            ByteValue byteValue = new ByteValue();
            byte      bt        = 1;

            byteValue = bt;
            Assert.True(bt == byteValue);
            Assert.Equal(bt, byteValue.Value);
            bt        = 2;
            byteValue = ByteValue.FromByte(bt);
            Assert.Equal(bt, ByteValue.ToByte(byteValue));

            // 4. DateTimeValue
            DateTimeValue dtValue = new DateTimeValue();
            DateTime      dt      = DateTime.Now;

            dtValue = dt;
            Assert.True(dt == dtValue);
            dt      = DateTime.Now.AddDays(1);
            dtValue = DateTimeValue.FromDateTime(dt);
            Assert.Equal(dt, dtValue.Value);
            Assert.Equal(dt, DateTimeValue.ToDateTime(dt));

            // 5. DecimalValue
            DecimalValue decimalValue = new DecimalValue();
            decimal      dcm          = 10;

            decimalValue = dcm;
            Assert.True(dcm == decimalValue);
            decimalValue = DecimalValue.FromDecimal(20);
            Assert.Equal(20, decimalValue.Value);
            Assert.Equal(20, DecimalValue.ToDecimal(decimalValue));

            // 6. DoubleValue
            DoubleValue doubleValue = new DoubleValue();
            double      dbl         = 1.1;

            doubleValue = dbl;
            Assert.True(dbl == doubleValue);
            doubleValue = DoubleValue.FromDouble(2.2);
            Assert.Equal(2.2, doubleValue.Value);
            Assert.Equal(2.2, DoubleValue.ToDouble(doubleValue));

            // 7. HexBinaryValue
            HexBinaryValue hexBinaryValue = new HexBinaryValue();
            string         hex            = "0X99CCFF";

            hexBinaryValue = hex;
            Assert.True(hex == hexBinaryValue);
            hex            = "111111";
            hexBinaryValue = HexBinaryValue.FromString(hex);
            Assert.Equal(hex, hexBinaryValue.Value);
            Assert.Equal(hex, HexBinaryValue.ToString(hexBinaryValue));

            // 8. Int16
            Int16Value int16Value = new Int16Value();
            short      int16      = 16;

            int16Value = int16;
            Assert.True(int16 == int16Value);
            int16      = 17;
            int16Value = Int16Value.FromInt16(int16);
            Assert.Equal(int16, int16Value.Value);
            Assert.Equal(int16, Int16Value.ToInt16(int16Value));

            // 9. Int32
            Int32Value int32Value = new Int32Value();
            int        int32      = 32;

            int32Value = int32;
            Assert.True(int32 == int32Value);
            int32      = 33;
            int32Value = Int32Value.FromInt32(int32);
            Assert.Equal(int32, int32Value.Value);
            Assert.Equal(int32, Int32Value.ToInt32(int32Value));

            // 10. Int64
            Int64Value int64Value = new Int64Value();
            long       int64      = 64;

            int64Value = int64;
            Assert.True(int64 == int64Value);
            int64      = 17;
            int64Value = Int64Value.FromInt64(int64);
            Assert.Equal(int64, int64Value.Value);
            Assert.Equal(int64, Int64Value.ToInt64(int64Value));

            // 11. IntegerValue
            IntegerValue integerValue = new IntegerValue();
            int          integer      = 64;

            integerValue = integer;
            Assert.True(integer == integerValue);
            integer      = 17;
            integerValue = IntegerValue.FromInt64(integer);
            Assert.Equal(integer, integerValue.Value);
            Assert.Equal(integer, IntegerValue.ToInt64(integerValue));

            // 12. OnOffValue
            OnOffValue onOffValue = new OnOffValue();

            onOffValue = true;
            Assert.True(onOffValue);
            onOffValue = OnOffValue.FromBoolean(false);
            Assert.False(onOffValue.Value);
            Assert.False(OnOffValue.ToBoolean(onOffValue));

            // 13. SByteValue
            SByteValue sbyteValue = new SByteValue();
            sbyte      sbt        = sbyte.MaxValue;

            sbyteValue = sbt;
            Assert.True(sbt == sbyteValue);
            sbt        = sbyte.MinValue;
            sbyteValue = SByteValue.FromSByte(sbt);
            Assert.Equal(sbt, sbyteValue.Value);
            Assert.Equal(sbt, SByteValue.ToSByte(sbt));

            // 14. SingleValue
            SingleValue singleValue = new SingleValue();
            float       single      = float.MaxValue;

            singleValue = single;
            Assert.True(single == singleValue);
            single      = float.NaN;
            singleValue = SingleValue.FromSingle(single);
            Assert.Equal(single, singleValue.Value);
            Assert.Equal(single, SingleValue.ToSingle(singleValue));

            // 15. StringValue
            StringValue stringValue = new StringValue();
            string      str         = "Ethan";

            stringValue = str;
            Assert.True(str == stringValue);
            str         = "Yin";
            stringValue = StringValue.FromString(str);
            Assert.Equal(str, stringValue.Value);
            Assert.Equal(str, stringValue.ToString());
            Assert.Equal(str, StringValue.ToString(stringValue));

            // 16. TrueFalseBlankValue
            TrueFalseBlankValue tfbValue = new TrueFalseBlankValue();

            tfbValue = true;
            Assert.True(tfbValue);
            tfbValue = TrueFalseBlankValue.FromBoolean(false);
            Assert.False(tfbValue.Value);
            Assert.False(TrueFalseBlankValue.ToBoolean(tfbValue));

            // 17. TrueFalseValue
            TrueFalseValue tfValue = new TrueFalseValue();

            tfValue = true;
            Assert.True(tfValue);
            tfValue = TrueFalseValue.FromBoolean(false);
            Assert.False(tfValue.Value);
            Assert.False(TrueFalseValue.ToBoolean(tfValue));

            // 18. UInt16Value
            UInt16Value uint16Value = new UInt16Value();
            ushort      uint16      = ushort.MaxValue;

            uint16Value = uint16;
            Assert.True(uint16 == uint16Value);
            uint16      = ushort.MinValue;
            uint16Value = UInt16Value.FromUInt16(uint16);
            Assert.Equal(uint16, uint16Value.Value);
            Assert.Equal(uint16, UInt16Value.ToUInt16(uint16Value));

            // 19. UInt32Value
            UInt32Value uint32Value = new UInt32Value();
            uint        uint32      = uint.MaxValue;

            uint32Value = uint32;
            Assert.True(uint32 == uint32Value);
            uint32      = uint.MinValue;
            uint32Value = UInt32Value.FromUInt32(uint32);
            Assert.Equal(uint32, uint32Value.Value);
            Assert.Equal(uint32, UInt32Value.ToUInt32(uint32Value));

            // 20. UInt64Value
            UInt64Value uint64Value = new UInt64Value();
            ulong       uint64      = ulong.MaxValue;

            uint64Value = uint64;
            Assert.True(uint64 == uint64Value);
            uint64      = ulong.MinValue;
            uint64Value = UInt64Value.FromUInt64(uint64);
            Assert.Equal(uint64, uint64Value.Value);
            Assert.Equal(uint64, UInt64Value.ToUInt64(uint64Value));
        }
        public MemoryStream ReplaceHyperlinks()
        {
            if (_rep.HyperlinkPlaceholders == null || _rep.HyperlinkPlaceholders.Count == 0)
            {
                return(null);
            }

            using (var doc = WordprocessingDocument.Open(_docxMs, true))
            {
                CleanMarkup(doc);

                // Search in body, headers and footers
                var documentTexts = doc.MainDocumentPart.Document.Descendants <Text>();

                foreach (var text in documentTexts)
                {
                    foreach (var replace in _rep.HyperlinkPlaceholders)
                    {
                        var pl = _rep.HyperlinkPlaceholderStartTag + replace.Key + _rep.HyperlinkPlaceholderEndTag;
                        if (text.Text.Contains(pl))
                        {
                            var run = text.Ancestors <Run>().First();

                            if (text.Text.StartsWith(pl))
                            {
                                var    newAfterRun     = (Run)run.Clone();
                                string afterText       = text.Text.Substring(pl.Length, text.Text.Length - pl.Length);
                                Text   newAfterRunText = newAfterRun.GetFirstChild <Text>();
                                newAfterRunText.Space = SpaceProcessingModeValues.Preserve;
                                newAfterRunText.Text  = afterText;

                                run.Parent.InsertAfter(newAfterRun, run);
                            }
                            else if (text.Text.EndsWith(pl))
                            {
                                var    newBeforeRun     = (Run)run.Clone();
                                string beforeText       = text.Text.Substring(0, text.Text.Length - pl.Length);
                                Text   newBeforeRunText = newBeforeRun.GetFirstChild <Text>();
                                newBeforeRunText.Space = SpaceProcessingModeValues.Preserve;
                                newBeforeRunText.Text  = beforeText;

                                run.Parent.InsertBefore(newBeforeRun, run);
                            }
                            else
                            {
                                //Break the texts into the part before and after image. Then create separate runs for them
                                var pos = text.Text.IndexOf(pl, StringComparison.CurrentCulture);

                                var    newBeforeRun     = (Run)run.Clone();
                                string beforeText       = text.Text.Substring(0, pos);
                                Text   newBeforeRunText = newBeforeRun.GetFirstChild <Text>();
                                newBeforeRunText.Space = SpaceProcessingModeValues.Preserve;
                                newBeforeRunText.Text  = beforeText;
                                run.Parent.InsertBefore(newBeforeRun, run);

                                var    newAfterRun     = (Run)run.Clone();
                                string afterText       = text.Text.Substring(pos + pl.Length, text.Text.Length - pos - pl.Length);
                                Text   newAfterRunText = newAfterRun.GetFirstChild <Text>();
                                newAfterRunText.Space = SpaceProcessingModeValues.Preserve;
                                newAfterRunText.Text  = afterText;
                                run.Parent.InsertAfter(newAfterRun, run);
                            }

                            var    relation   = doc.MainDocumentPart.AddHyperlinkRelationship(new Uri(replace.Value.Link, UriKind.RelativeOrAbsolute), true);
                            string relationid = relation.Id;
                            var    linkText   = string.IsNullOrEmpty(replace.Value.Text) ? replace.Value.Link : replace.Value.Text;
                            var    hyper      =
                                new Hyperlink(
                                    new Run(
                                        new RunProperties(new RunStyle()
                            {
                                Val = "Hyperlink"
                            }),
                                        new Text(linkText)))
                            {
                                Id      = relationid,
                                History = OnOffValue.FromBoolean(true)
                            };

                            run.Parent.InsertBefore(hyper, run);
                            run.Remove();
                        }
                    }
                }
            }

            _docxMs.Position = 0;
            return(_docxMs);
        }