public MemoryStream ReplaceTexts()
        {
            if (_rep.TextPlaceholders == null || _rep.TextPlaceholders.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>();
                var headerTexts   = doc.MainDocumentPart.HeaderParts.SelectMany(h => h.Header.Descendants <Text>());
                var footerTexts   = doc.MainDocumentPart.FooterParts.SelectMany(f => f.Footer.Descendants <Text>());

                foreach (var text in documentTexts.Concat(headerTexts).Concat(footerTexts)) // <<< Here
                {
                    foreach (var replace in _rep.TextPlaceholders)
                    {
                        if (text.Text.Contains(_rep.TextPlaceholderStartTag + replace.Key + _rep.TextPlaceholderEndTag))
                        {
                            if (!string.IsNullOrEmpty(replace.Value) && replace.Value.Contains(_rep.NewLineTag))//If we have line breaks present
                            {
                                string[] repArray = replace.Value.Split(new string[] { _rep.NewLineTag }, StringSplitOptions.None);

                                var   lastInsertedText = text;
                                Break lastInsertedBreak;

                                for (var i = 0; i < repArray.Length; i++)
                                {
                                    if (i == 0)//The text is only replaced with the first part of the replacement array
                                    {
                                        text.Text = text.Text.Replace(_rep.TextPlaceholderStartTag + replace.Key + _rep.TextPlaceholderEndTag, repArray[i]);
                                    }
                                    else
                                    {
                                        var tmpText  = new Text(repArray[i]);
                                        var tmpBreak = new Break();
                                        text.Parent.InsertAfter(tmpBreak, lastInsertedText);
                                        lastInsertedBreak = tmpBreak;
                                        text.Parent.InsertAfter(tmpText, lastInsertedBreak);
                                        lastInsertedText = tmpText;
                                    }
                                }
                            }
                            else
                            {
                                text.Text = text.Text.Replace(_rep.TextPlaceholderStartTag + replace.Key + _rep.TextPlaceholderEndTag, replace.Value ?? string.Empty);
                            }
                        }
                    }
                }
            }

            _docxMs.Position = 0;
            return(_docxMs);
        }
        public MemoryStream ReplaceTexts()
        {
            if (_rep.TextPlaceholders.Count == 0 || _rep.TextPlaceholders == null)
            {
                return(null);
            }
            using (WordprocessingDocument doc =
                       WordprocessingDocument.Open(_docxMs, true))
            {
                CleanMarkup(doc);

                var document = doc.MainDocumentPart.Document;

                foreach (var text in document.Descendants <Text>()) // <<< Here
                {
                    foreach (var replace in _rep.TextPlaceholders)
                    {
                        if (text.Text.Contains(_rep.TextPlaceholderStartTag + replace.Key + _rep.TextPlaceholderEndTag))
                        {
                            if (replace.Value.Contains(_rep.NewLineTag))//If we have line breaks present
                            {
                                string[] repArray = replace.Value.Split(new string[] { _rep.NewLineTag }, StringSplitOptions.None);

                                var lastInsertedText  = text;
                                var lastInsertedBreak = new Break();

                                for (var i = 0; i < repArray.Length; i++)
                                {
                                    if (i == 0)//The text is only replaced with the first part of the replacement array
                                    {
                                        text.Text = text.Text.Replace(_rep.TextPlaceholderStartTag + replace.Key + _rep.TextPlaceholderEndTag, repArray[i]);
                                    }
                                    else
                                    {
                                        var tmpText  = new Text(repArray[i]);
                                        var tmpBreak = new Break();
                                        text.Parent.InsertAfter(tmpBreak, lastInsertedText);
                                        lastInsertedBreak = tmpBreak;
                                        text.Parent.InsertAfter(tmpText, lastInsertedBreak);
                                        lastInsertedText = tmpText;
                                    }
                                }
                            }
                            else
                            {
                                text.Text = text.Text.Replace(_rep.TextPlaceholderStartTag + replace.Key + _rep.TextPlaceholderEndTag, replace.Value);
                            }
                        }
                    }
                }
            }

            _docxMs.Position = 0;
            return(_docxMs);
        }
Ejemplo n.º 3
0
        private static IEnumerable <LineElement> CreateParagraphElements(
            this Word.Run run,
            IImageAccessor imageAccessor,
            IStyleFactory styleAccessor)
        {
            var textStyle = styleAccessor.EffectiveTextStyle(run.RunProperties);

            var elements = run
                           .ChildElements
                           .Where(c => c is Word.Text || c is Word.TabChar || c is Word.Drawing || c is Word.Break || c is Word.CarriageReturn)
                           .SelectMany(c => {
                return(c switch
                {
                    Word.Text t => t.SplitTextToElements(textStyle),
                    Word.TabChar t => new LineElement[] { new TabElement(textStyle) },
                    Word.Drawing d => d.CreateInlineDrawing(imageAccessor),
                    Word.CarriageReturn _ => new LineElement[] { new NewLineElement(textStyle) },
                    Word.Break b => b.CreateBreakElement(textStyle),
                    _ => throw new RendererException("unprocessed child")
                });
            })
Ejemplo n.º 4
0
        public static void Insert(string fullPathToDocument, string fullPathToImageFile)
        {
            List <KeyValuePair <string, string> > keyValuePairs = new List <KeyValuePair <string, string> >();

            keyValuePairs.Add(new KeyValuePair <string, string>("Deponi", "Picture 1"));
            keyValuePairs.Add(new KeyValuePair <string, string>("Deponi", "Picture 2"));
            keyValuePairs.Add(new KeyValuePair <string, string>("Deponi", "Picture 3"));
            keyValuePairs.Add(new KeyValuePair <string, string>("Have", "Picture 4"));
            keyValuePairs.Add(new KeyValuePair <string, string>("Metal", "Picture 5"));
            keyValuePairs.Add(new KeyValuePair <string, string>("Metal", "Picture 6"));
            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(fullPathToDocument, true))
            {
                string currentHeader = "";

                foreach (var keyValuePair in keyValuePairs)
                {
                    if (currentHeader != keyValuePair.Key)
                    {
                        if (!string.IsNullOrEmpty(currentHeader))
                        {
                            // insert pakebreak
                            Body body = wordDoc.MainDocumentPart.Document.Body;

                            Paragraph para      = body.AppendChild(new Paragraph());
                            Run       run       = para.AppendChild(new Run());
                            Break     pageBreak = run.AppendChild(new Break());
                            pageBreak.Type = BreakValues.Page;
                        }
                        InsertHeader(keyValuePair.Key, wordDoc, currentHeader);
                        currentHeader = keyValuePair.Key;
                    }

                    InsertPicture(keyValuePair.Value, wordDoc);
                }
            }
        }
Ejemplo n.º 5
0
        public static OpenXmlElement GenerateBreak(Break _break)
        {
            var b = new W.Break();

            if (_break.Type.HasValue)
            {
                switch (_break.Type.Value)
                {
                case BreakType.Column:
                    b.Type = W.BreakValues.Column;
                    break;

                case BreakType.Page:
                    b.Type = W.BreakValues.Page;
                    break;

                case BreakType.TextWrapping:
                    b.Type = W.BreakValues.TextWrapping;
                    break;
                }
            }

            return(new W.Run(b));
        }
        public MemoryStream ReplaceTableRows()
        {
            if (_rep.TablePlaceholders.Count == 0 || _rep.TablePlaceholders == null)
            {
                return(null);
            }

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

                var document = doc.MainDocumentPart.Document;

                foreach (var trDict in _rep.TablePlaceholders) //Take a Row (one Dictionary) at a time
                {
                    var trCol0 = trDict.First();
                    // Find the first text element matching the search string
                    // where the text is inside a table cell --> this is the row we are searching for.
                    var textElement = document.Body.Descendants <Text>()
                                      .FirstOrDefault(t =>
                                                      t.Text == _rep.TablePlaceholderStartTag + trCol0.Key + _rep.TablePlaceholderEndTag &&
                                                      t.Ancestors <DocumentFormat.OpenXml.Wordprocessing.TableCell>().Any());
                    if (textElement != null)
                    {
                        var newTableRows = new List <TableRow>();
                        var tableRow     = textElement.Ancestors <TableRow>().First();


                        for (var j = 0; j < trCol0.Value.Length; j++) //Lets create row by row and replace placeholders
                        {
                            newTableRows.Add((TableRow)tableRow.CloneNode(true));
                            var tableRowCopy = newTableRows[newTableRows.Count - 1];

                            foreach (var text in tableRow.Descendants <Text>()
                                     ) //Cycle through the cells of the row to replace from the Dictionary value ( string array)
                            {
                                for (var index = 0;
                                     index < trDict.Count;
                                     index++) //Now cycle through the "columns" (keys) of the Dictionary and replace item by item
                                {
                                    var item = trDict.ElementAt(index);

                                    if (text.Text.Contains(_rep.TablePlaceholderStartTag + item.Key +
                                                           _rep.TablePlaceholderEndTag))
                                    {
                                        if (item.Value[j].Contains(_rep.NewLineTag)) //If we have line breaks present
                                        {
                                            string[] repArray = item.Value[j].Split(new string[] { _rep.NewLineTag },
                                                                                    StringSplitOptions.None);

                                            var lastInsertedText  = text;
                                            var lastInsertedBreak = new Break();

                                            for (var i = 0; i < repArray.Length; i++)
                                            {
                                                if (i == 0
                                                    ) //The text is only replaced with the first part of the replacement array
                                                {
                                                    text.Text = text.Text.Replace(
                                                        _rep.TablePlaceholderStartTag + item.Key +
                                                        _rep.TablePlaceholderEndTag, repArray[i]);
                                                }
                                                else
                                                {
                                                    var tmpText  = new Text(repArray[i]);
                                                    var tmpBreak = new Break();
                                                    text.Parent.InsertAfter(tmpBreak, lastInsertedText);
                                                    lastInsertedBreak = tmpBreak;
                                                    text.Parent.InsertAfter(tmpText, lastInsertedBreak);
                                                    lastInsertedText = tmpText;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            text.Text = text.Text.Replace(
                                                _rep.TablePlaceholderStartTag + item.Key + _rep.TablePlaceholderEndTag,
                                                item.Value[j]);
                                        }

                                        break;
                                    }
                                }
                            }

                            if (j < trCol0.Value.Length - 1)
                            {
                                tableRow.Parent.InsertAfter(tableRowCopy, tableRow);
                                tableRow = tableRowCopy;
                            }
                        }
                    }
                }
            }
            _docxMs.Position = 0;
            return(_docxMs);
        }
Ejemplo n.º 7
0
        public void ReplaceString(OpenXmlElement element, string val)
        {
            var text = element.Descendants <Word.Text>().FirstOrDefault();
            var run  = text == null?element.Descendants <Word.Run>().FirstOrDefault() : FindParent <Word.Run>(text);

            var runp      = run.Parent;
            var paragraph = FindParent <Word.Paragraph>(runp);

            run.RsidRunProperties = null;
            run.RemoveAllChildren <Word.Text>();
            run.RemoveAllChildren <Word.RunProperties>();
            runp.RemoveAllChildren <Word.Run>();
            runp.RemoveAllChildren <Word.Break>();

            if (paragraph.ParagraphProperties?.ParagraphMarkRunProperties != null)
            {
                run.RunProperties = new Word.RunProperties();
                foreach (var item in paragraph.ParagraphProperties.ParagraphMarkRunProperties)
                {
                    run.RunProperties.AppendChild(item.CloneNode(true));
                }
            }
            if (text == null)
            {
                text = new Word.Text();
            }
            else if (text.Parent != null)
            {
                text.Remove();
            }
            string[] pagesplit = val.TrimEnd("\r\n".ToCharArray()).Split("\f".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            for (int p = 0; p < pagesplit.Length; p++)
            {
                var lineSpit = pagesplit[p].Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
                if (lineSpit.Length > 0)
                {
                    for (int i = 0; i < lineSpit.Length; i++)
                    {
                        if (p == 0 && i == 0)
                        {
                            text.Text  = lineSpit[0];
                            text.Space = SpaceProcessingModeValues.Preserve;
                            run.Append(text);
                            runp.Append(run);
                            continue;
                        }
                        Word.Run r = run.Clone() as Word.Run;
                        r.RemoveAllChildren <Word.Text>();
                        r.Append(new Word.Text(lineSpit[i])
                        {
                            Space = SpaceProcessingModeValues.Preserve
                        });

                        Word.Paragraph pr = (Word.Paragraph)paragraph.Clone();
                        pr.RemoveAllChildren <Word.Run>();
                        pr.RemoveAllChildren <Word.Break>();
                        pr.RemoveAllChildren <Word.SdtBlock>();
                        pr.RemoveAllChildren <Word.SdtRun>();

                        pr.Append(r);

                        paragraph.Parent.InsertAfter <Word.Paragraph>(pr, paragraph);
                        paragraph = pr;
                    }
                }
                if (p < pagesplit.Length - 1)
                {
                    var bp = new Word.Break()
                    {
                        Type = Word.BreakValues.Page
                    };
                    paragraph.AppendChild(bp);
                }
            }
        }
Ejemplo n.º 8
0
        public Wordprocessing.Body insertinform()
        {
            Wordprocessing.Body body = new Wordprocessing.Body();
            //Параграф1
            Wordprocessing.Paragraph paragraph1 = new Wordprocessing.Paragraph();
            Wordprocessing.ParagraphProperties paragraphProperties1 = new Wordprocessing.ParagraphProperties();
            Wordprocessing.SpacingBetweenLines spacingBetweenLines1 = new Wordprocessing.SpacingBetweenLines() { After = "0" };
            Wordprocessing.Justification justification1 = new Wordprocessing.Justification() { Val = Wordprocessing.JustificationValues.Center };
            paragraphProperties1.Append(spacingBetweenLines1);
            paragraphProperties1.Append(justification1);
            Wordprocessing.Run run1 = new Wordprocessing.Run();
            Wordprocessing.RunProperties runProperties1 = new Wordprocessing.RunProperties();
            Wordprocessing.RunFonts runFonts2 = new Wordprocessing.RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" };
            Wordprocessing.Bold bold2 = new Wordprocessing.Bold();
            Wordprocessing.FontSize fontSize2 = new Wordprocessing.FontSize() { Val = "24" };
            runProperties1.Append(runFonts2);
            runProperties1.Append(bold2);
            runProperties1.Append(fontSize2);
            Wordprocessing.Text text1 = new Wordprocessing.Text();
            text1.Text = "ФГБОУВПО \"ПЕРМСКИЙ ГОСУДАРСТВЕННЫЙ НАЦИОНАЛЬНЫЙ ИССЛЕДОВАТЕЛЬСКИЙ УНИВЕРСИТЕТ\"";
            run1.Append(runProperties1);
            run1.Append(text1);
            paragraph1.Append(paragraphProperties1);
            paragraph1.Append(run1);

            //Параграф2
            Wordprocessing.Paragraph paragraph2 = new Wordprocessing.Paragraph();

            Wordprocessing.ParagraphProperties paragraphProperties2 = new Wordprocessing.ParagraphProperties();
            Wordprocessing.SpacingBetweenLines spacingBetweenLines2 = new Wordprocessing.SpacingBetweenLines() { After = "0" };
            Wordprocessing.Justification justification2 = new Wordprocessing.Justification() { Val = Wordprocessing.JustificationValues.Center };
            paragraphProperties2.Append(spacingBetweenLines2);
            paragraphProperties2.Append(justification2);
            Wordprocessing.Run run2 = new Wordprocessing.Run();

            Wordprocessing.RunProperties runProperties2 = new Wordprocessing.RunProperties();
            Wordprocessing.RunFonts runFonts4 = new Wordprocessing.RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" };
            Wordprocessing.FontSize fontSize4 = new Wordprocessing.FontSize() { Val = "24" };

            runProperties2.Append(runFonts4);
            runProperties2.Append(fontSize4);
            Wordprocessing.Text text2 = new Wordprocessing.Text();
            text2.Text = "Механико-математический факультет ";

            run2.Append(runProperties2);
            run2.Append(text2);

            Wordprocessing.Run run3 = new Wordprocessing.Run();

            Wordprocessing.RunProperties runProperties3 = new Wordprocessing.RunProperties();
            Wordprocessing.RunFonts runFonts5 = new Wordprocessing.RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" };
            Wordprocessing.FontSize fontSize5 = new Wordprocessing.FontSize() { Val = "24" };
            runProperties3.Append(runFonts5);
            runProperties3.Append(fontSize5);
            Wordprocessing.Break break1 = new Wordprocessing.Break();
            Wordprocessing.Text text3 = new Wordprocessing.Text();
            text3.Text = "очная форма обучения";

            run3.Append(runProperties3);
            run3.Append(break1);
            run3.Append(text3);

            paragraph2.Append(paragraphProperties2);
            paragraph2.Append(run2);
            paragraph2.Append(run3);

            //Параграф2
            Wordprocessing.Paragraph paragraph3 = new Wordprocessing.Paragraph() { RsidParagraphAddition = "004D49E1", RsidParagraphProperties = "004D49E1", RsidRunAdditionDefault = "004D49E1" };

            Wordprocessing.ParagraphProperties paragraphProperties3 = new Wordprocessing.ParagraphProperties();
            Wordprocessing.SpacingBetweenLines spacingBetweenLines3 = new Wordprocessing.SpacingBetweenLines() { After = "0" };
            Wordprocessing.Justification justification3 = new Wordprocessing.Justification() { Val = Wordprocessing.JustificationValues.Center };
            paragraphProperties3.Append(spacingBetweenLines3);
            paragraphProperties3.Append(justification3);
            Wordprocessing.Run run4 = new Wordprocessing.Run();

            Wordprocessing.RunProperties runProperties4 = new Wordprocessing.RunProperties();
            Wordprocessing.RunFonts runFonts7 = new Wordprocessing.RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" };
            Wordprocessing.Bold bold4 = new Wordprocessing.Bold();

            runProperties4.Append(runFonts7);
            runProperties4.Append(bold4);
            Wordprocessing.Text text4 = new Wordprocessing.Text();
            text4.Text = "ЭКЗАМЕНАЦИОННАЯ ВЕДОМОСТЬ";
            run4.Append(runProperties4);
            run4.Append(text4);

            Wordprocessing.Run run5 = new Wordprocessing.Run();
            Wordprocessing.Break break2 = new Wordprocessing.Break();
            run5.Append(break2);

            paragraph3.Append(paragraphProperties3);
            paragraph3.Append(run4);
            paragraph3.Append(run5);

            body.Append(paragraph1);
            body.Append(paragraph2);
            body.Append(paragraph3);
            return body;
        }