Esempio n. 1
0
        /// <summary>
        /// Выполняет поиск стандартных элементов, представляющих флажки в документе,
        /// по значению параметра <paramref name="name"/> и заполняет их значением параметра <paramref name="value"/>.
        /// Если элементы не найдены, действие не выполняется.
        /// </summary>
        /// <param name="name">Имя целевого(ых) стандартных элементов.</param>
        /// <param name="value">Значение для вставки в стандартные элементы.</param>
        /// <exception cref="InvalidSdtElementException">
        /// Возникает если дерево дочерних элементов <see cref="SdtElement"/> содержит недопустимые элементы
        /// или отсутствует обязательный дочерний элемент.
        /// </exception>
        protected void FillSdtElement(string name, bool value)
        {
            name.ThrowIfNullOrWhiteSpace(nameof(name));

            try
            {
                foreach (var element in _elemetns.Where(element => element.SdtProperties.GetFirstChild <SdtAlias>()?.Val == name))
                {
                    if (element.SdtProperties.GetFirstChild <W14.SdtContentCheckBox>() is W14.SdtContentCheckBox contentCheckBox)
                    {
                        contentCheckBox.Checked = new W14.Checked()
                        {
                            Val = value ? W14.OnOffValues.One : W14.OnOffValues.Zero
                        };

                        var sdtContentBlock = new SdtContentBlock();
                        var run             = sdtContentBlock.AppendChild(new Run());

                        if (element.SdtProperties.GetFirstChild <RunProperties>() is RunProperties properties)
                        {
                            run.AppendChild(properties.CloneNode(true));
                        }

                        element.SdtProperties.RemoveAllChildren <SdtPlaceholder>();
                        run.AppendChild(new Text(contentCheckBox.Checked.Val == W14.OnOffValues.One ? "☒" : "☐"));
                        element.ReplaceChild(sdtContentBlock, element.LastChild);
                    }
                }
            }
            catch (InvalidOperationException)
            {
                throw new InvalidSdtElementException(name);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Выполняет поиск стандартных элементов, представляющих элемент даты и времени в документе,
        /// по значению параметра <paramref name="name"/> и заполняет их значением параметра <paramref name="value"/>.
        /// Если элементы не найдены, действие не выполняется.
        /// </summary>
        /// <param name="name">Имя целевого(ых) стандартных элементов.</param>
        /// <param name="value">Значение для вставки в стандартные элементы.</param>
        /// <exception cref="InvalidSdtElementException">
        /// Возникает если дерево дочерних элементов <see cref="SdtElement"/> содержит недопустимые элементы
        /// или отсутствует обязательный дочерний элемент.
        /// </exception>
        protected void FillSdtElement(string name, DateTime value)
        {
            name.ThrowIfNullOrWhiteSpace(nameof(name));

            try
            {
                foreach (var element in _elemetns.Where(element => element.SdtProperties.GetFirstChild <SdtAlias>()?.Val == name))
                {
                    if (element.SdtProperties.GetFirstChild <SdtContentDate>() is SdtContentDate contentDate)
                    {
                        contentDate.FullDate = new DateTimeValue(value);

                        var sdtContentBlock = new SdtContentBlock();
                        var run             = sdtContentBlock.AppendChild(new Run());

                        if (element.SdtProperties.GetFirstChild <RunProperties>() is RunProperties properties)
                        {
                            run.AppendChild(properties.CloneNode(true));
                        }

                        element.SdtProperties.RemoveAllChildren <SdtPlaceholder>();
                        run.AppendChild(new Text(contentDate.FullDate.Value.ToString(contentDate.DateFormat.Val)));
                        element.ReplaceChild(sdtContentBlock, element.LastChild);
                    }
                }
            }
            catch (InvalidOperationException)
            {
                throw new InvalidSdtElementException(name);
            }
        }
Esempio n. 3
0
        // ATTENTION : dont work with google doc use CreateParagraph_PageNumber()
        public static SdtBlock CreatePageNumberBlock(string styleId, string text)
        {
            // SdtBlock, <w:sdt>
            SdtBlock sdtBlock = new SdtBlock();

            // Structured Document Tag Properties, <w:sdtPr>
            SdtProperties sdtProperties = new SdtProperties();
            // SdtContentDocPartObject, <w:docPartObj>
            SdtContentDocPartObject docPartObject = new SdtContentDocPartObject();

            // Document Part Gallery Filter, <w:docPartGallery>
            docPartObject.AppendChild(new DocPartGallery {
                Val = "Page Numbers (Bottom of Page)"
            });
            docPartObject.AppendChild(new DocPartUnique());
            sdtProperties.AppendChild(docPartObject);
            sdtBlock.SdtProperties = sdtProperties;

            // Block-Level Structured Document Tag Content, <w:sdtContent>
            SdtContentBlock sdtContentBlock = new SdtContentBlock();
            Paragraph       paragraph       = new Paragraph();

            paragraph.ParagraphProperties = new ParagraphProperties {
                ParagraphStyleId = new ParagraphStyleId()
                {
                    Val = styleId
                }
            };
            Run run = paragraph.AppendChild(new Run());

            run.AppendChild(new TabStop());
            run.AppendChild(new DW.Text {
                Text = text
            });
            run.AppendChild(new TabStop());
            run.AppendChild(new DW.Text {
                Text = "page ", Space = SpaceProcessingModeValues.Preserve
            });
            // Complex Field Character, <w:fldChar>
            run.AppendChild(new FieldChar {
                FieldCharType = FieldCharValues.Begin
            });
            // Field Code, <w:instrText>
            // "PAGE   \\* MERGEFORMAT"  "PAGE"
            run.AppendChild(new FieldCode("PAGE   \\* MERGEFORMAT"));
            run.AppendChild(new FieldChar {
                FieldCharType = FieldCharValues.Separate
            });
            run.AppendChild(new DW.Text {
                Text = ""
            });
            run.AppendChild(new FieldChar {
                FieldCharType = FieldCharValues.End
            });
            sdtContentBlock.AppendChild(paragraph);
            sdtBlock.SdtContentBlock = sdtContentBlock;

            return(sdtBlock);
        }
Esempio n. 4
0
        /// <summary>
        /// FillDataObject
        /// </summary>
        /// <param name="dataInputObject"></param>
        /// <param name="stream"></param>
        public void FillDataObject(object dataInputObject, Stream stream)
        {
            if (dataInputObject != null)
            {
                if (stream != null && stream.CanRead && stream.CanWrite)
                {
                    // Use OpenXML to process
                    var dictionary = GetDictionaryFromObject(dataInputObject);
                    using (WordprocessingDocument word = WordprocessingDocument.Open(stream, true))
                    {
                        var part     = word.MainDocumentPart;
                        var elements = part.Document.Descendants <SdtElement>().ToList();
                        foreach (SdtElement element in elements)
                        {
                            SdtAlias alias = element.Descendants <SdtAlias>().FirstOrDefault();
                            if (alias != null)
                            {
                                // Get title of content control
                                var title = alias.Val.Value;
                                if (dictionary.ContainsKey(title))
                                {
                                    object value = dictionary[title];
                                    if (element.ToString().Equals("DocumentFormat.OpenXml.Wordprocessing.SdtRun"))
                                    {
                                        SdtRun run = element as SdtRun;
                                        if (run != null)
                                        {
                                            SdtContentRun contentRun = run.Descendants <SdtContentRun>().FirstOrDefault();
                                            Run           xRun       = contentRun.Descendants <Run>().FirstOrDefault();
                                            if (xRun == null)
                                            {
                                                contentRun.AppendChild(new Run());
                                                xRun = contentRun.Descendants <Run>().FirstOrDefault();
                                            }
                                            Text text = xRun.Descendants <Text>().FirstOrDefault();
                                            if (text == null)
                                            {
                                                xRun.AppendChild(new Text(value.ToString()));
                                                text = xRun.Descendants <Text>().FirstOrDefault();
                                            }
                                            text.Text = value.ToString();
                                        }
                                    }
                                    else if (element.ToString().Equals("DocumentFormat.OpenXml.Wordprocessing.SdtBlock"))
                                    {
                                        SdtBlock block = element as SdtBlock;
                                        if (block != null)
                                        {
                                            SdtContentBlock contentBlock = block.Descendants <SdtContentBlock>().FirstOrDefault();
                                            Run             xRun         = contentBlock.Descendants <Run>().FirstOrDefault();
                                            if (xRun == null)
                                            {
                                                contentBlock.AppendChild(new Run());
                                                xRun = contentBlock.Descendants <Run>().FirstOrDefault();
                                            }
                                            Text text = xRun.Descendants <Text>().FirstOrDefault();
                                            if (text == null)
                                            {
                                                xRun.AppendChild(new Text(value.ToString()));
                                                text = xRun.Descendants <Text>().FirstOrDefault();
                                            }
                                            text.Text = value.ToString();
                                        }
                                    }
                                }
                            }
                        }

                        part.Document.Save();
                    }
                }
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Fill data object into word file that has arrBytesSource data.
        /// </summary>
        /// <param name="dataInputObject"></param>
        /// <param name="arrBytesSource"></param>
        /// <returns>The MemoryStream object.</returns>
        public Stream FillDataObject(object dataInputObject, byte[] arrBytesSource)
        {
            MemoryStream memoryStream = null;

            try
            {
                if (dataInputObject != null)
                {
                    if (arrBytesSource != null && arrBytesSource.Length > 0)
                    {
                        #region Fix bug TFS #1971
                        //memoryStream = new MemoryStream(arrBytesSource, true);
                        memoryStream = new MemoryStream();
                        memoryStream.Write(arrBytesSource, 0, arrBytesSource.Length);
                        memoryStream.Position = 0;
                        #endregion

                        // Use OpenXML to process
                        var dictionary = GetDictionaryFromObject(dataInputObject);
                        using (WordprocessingDocument word = WordprocessingDocument.Open(memoryStream, true))
                        {
                            var part     = word.MainDocumentPart;
                            var elements = part.Document.Descendants <SdtElement>().ToList();
                            foreach (SdtElement element in elements)
                            {
                                SdtAlias alias = element.Descendants <SdtAlias>().FirstOrDefault();
                                if (alias != null)
                                {
                                    // Get title of content control
                                    var title = alias.Val.Value;
                                    if (dictionary.ContainsKey(title))
                                    {
                                        object value = dictionary[title];

                                        if (value != null)
                                        {
                                            if (element.ToString().Equals("DocumentFormat.OpenXml.Wordprocessing.SdtRun"))
                                            {
                                                SdtRun run = element as SdtRun;
                                                if (run != null)
                                                {
                                                    if (value is bool)
                                                    {
                                                        SdtContentCheckBox contentCheckBox = run.Descendants <SdtContentCheckBox>().FirstOrDefault();
                                                        if (contentCheckBox != null)
                                                        {
                                                            if (string.Compare(value.ToString(), Boolean.TrueString, true) == 0)
                                                            {
                                                                contentCheckBox.Checked.Val = string.Compare(value.ToString(), Boolean.TrueString, true) == 0 ? OnOffValues.One : OnOffValues.Zero;
                                                                SdtContentRun contentRun = run.Descendants <SdtContentRun>().FirstOrDefault();
                                                                if (contentRun != null)
                                                                {
                                                                    Run xRun = contentRun.Descendants <Run>().FirstOrDefault();
                                                                    if (xRun != null)
                                                                    {
                                                                        SymbolChar checkedSymbolChar = xRun.Descendants <SymbolChar>().FirstOrDefault();
                                                                        if (checkedSymbolChar != null)
                                                                        {
                                                                            checkedSymbolChar.Char = new HexBinaryValue(CheckedSymbolChar);
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        SdtContentRun contentRun = run.Descendants <SdtContentRun>().FirstOrDefault();
                                                        Run           xRun       = contentRun.Descendants <Run>().FirstOrDefault();
                                                        if (xRun == null)
                                                        {
                                                            contentRun.AppendChild(new Run());
                                                            xRun = contentRun.Descendants <Run>().FirstOrDefault();
                                                        }
                                                        Text text = xRun.Descendants <Text>().FirstOrDefault();
                                                        if (text == null)
                                                        {
                                                            xRun.AppendChild(new Text(value.ToString()));
                                                            text = xRun.Descendants <Text>().FirstOrDefault();
                                                        }
                                                        text.Text = value.ToString();
                                                    }
                                                }
                                            }
                                            else if (element.ToString().Equals("DocumentFormat.OpenXml.Wordprocessing.SdtBlock"))
                                            {
                                                SdtBlock block = element as SdtBlock;
                                                if (block != null)
                                                {
                                                    if (value is bool)
                                                    {
                                                        SdtContentCheckBox contentCheckBox = block.Descendants <SdtContentCheckBox>().FirstOrDefault();
                                                        if (contentCheckBox != null)
                                                        {
                                                            if (string.Compare(value.ToString(), Boolean.TrueString, true) == 0)
                                                            {
                                                                contentCheckBox.Checked.Val = string.Compare(value.ToString(), Boolean.TrueString, true) == 0 ? OnOffValues.One : OnOffValues.Zero;
                                                                SdtContentRun contentRun = block.Descendants <SdtContentRun>().FirstOrDefault();
                                                                if (contentRun != null)
                                                                {
                                                                    Run xRun = contentRun.Descendants <Run>().FirstOrDefault();
                                                                    if (xRun != null)
                                                                    {
                                                                        SymbolChar checkedSymbolChar = xRun.Descendants <SymbolChar>().FirstOrDefault();
                                                                        if (checkedSymbolChar != null)
                                                                        {
                                                                            checkedSymbolChar.Char = new HexBinaryValue(CheckedSymbolChar);
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        SdtContentBlock contentBlock = block.Descendants <SdtContentBlock>().FirstOrDefault();
                                                        Run             xRun         = contentBlock.Descendants <Run>().FirstOrDefault();
                                                        if (xRun == null)
                                                        {
                                                            contentBlock.AppendChild(new Run());
                                                            xRun = contentBlock.Descendants <Run>().FirstOrDefault();
                                                        }
                                                        Text text = xRun.Descendants <Text>().FirstOrDefault();
                                                        if (text == null)
                                                        {
                                                            xRun.AppendChild(new Text(value.ToString()));
                                                            text = xRun.Descendants <Text>().FirstOrDefault();
                                                        }
                                                        text.Text = value.ToString();
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            part.Document.Save();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ULSLogging.LogError(ex);
                throw ex;
            }

            return(memoryStream);
        }
Esempio n. 6
0
        // ATTENTION : dont work with google doc use CreateParagraph_PageNumber()
        public static SdtBlock CreatePageNumberBlock(string styleId, string text)
        {
            // SdtBlock, <w:sdt>
            SdtBlock sdtBlock = new SdtBlock();

            // Structured Document Tag Properties, <w:sdtPr>
            SdtProperties sdtProperties = new SdtProperties();
            // SdtContentDocPartObject, <w:docPartObj>
            SdtContentDocPartObject docPartObject = new SdtContentDocPartObject();
            // Document Part Gallery Filter, <w:docPartGallery>
            docPartObject.AppendChild(new DocPartGallery { Val = "Page Numbers (Bottom of Page)" });
            docPartObject.AppendChild(new DocPartUnique());
            sdtProperties.AppendChild(docPartObject);
            sdtBlock.SdtProperties = sdtProperties;

            // Block-Level Structured Document Tag Content, <w:sdtContent>
            SdtContentBlock sdtContentBlock = new SdtContentBlock();
            Paragraph paragraph = new Paragraph();
            paragraph.ParagraphProperties = new ParagraphProperties { ParagraphStyleId = new ParagraphStyleId() { Val = styleId } };
            Run run = paragraph.AppendChild(new Run());
            run.AppendChild(new TabStop());
            run.AppendChild(new DW.Text { Text = text });
            run.AppendChild(new TabStop());
            run.AppendChild(new DW.Text { Text = "page ", Space = SpaceProcessingModeValues.Preserve });
            // Complex Field Character, <w:fldChar>
            run.AppendChild(new FieldChar { FieldCharType = FieldCharValues.Begin });
            // Field Code, <w:instrText>
            // "PAGE   \\* MERGEFORMAT"  "PAGE"
            run.AppendChild(new FieldCode("PAGE   \\* MERGEFORMAT"));
            run.AppendChild(new FieldChar { FieldCharType = FieldCharValues.Separate });
            run.AppendChild(new DW.Text { Text = "" });
            run.AppendChild(new FieldChar { FieldCharType = FieldCharValues.End });
            sdtContentBlock.AppendChild(paragraph);
            sdtBlock.SdtContentBlock = sdtContentBlock;

            return sdtBlock;
        }
        public static void Fill(OpenXmlElement docNode, XmlElement macroListXml, WordprocessingDocument wdDoc)
        {
            /* Форматированный текст для встроенных элементов */
            IEnumerable <Paragraph> paragraphs = docNode.Elements <Paragraph>();

            foreach (Paragraph paragraph in paragraphs)
            {
                IEnumerable <SdtRun> sdtRuns = paragraph.Elements <SdtRun>();
                foreach (SdtRun sdtRun in sdtRuns)
                {
                    // Из SdtProperties взять Tag для идентификации Content Control
                    SdtProperties sdtProperties = sdtRun.GetFirstChild <SdtProperties>();
                    Tag           tag           = sdtProperties.GetFirstChild <Tag>();

                    // Найти в macroListXml Node макропеременной
                    String macroVarValue = FindMacroVar(macroListXml, tag.Val);

                    if (macroVarValue != null)
                    {
                        // Сохранить старый стиль Run
                        SdtContentRun  sdtContentRun = sdtRun.GetFirstChild <SdtContentRun>();
                        OpenXmlElement oldRunProps   = sdtContentRun.GetFirstChild <Run>().GetFirstChild <RunProperties>().CloneNode(true);

                        // Очистить Node Content Control
                        sdtContentRun.RemoveAllChildren();

                        // Создать новую Run Node
                        Run newRun = sdtContentRun.AppendChild(new Run());
                        // Вернуть старый стиль
                        newRun.AppendChild(oldRunProps);

                        // Вставить текст (без переносов строк!!!)
                        newRun.AppendChild(new Text(macroVarValue));
                    }
                }
            }

            /* Получить остальные Content Control */
            IEnumerable <SdtBlock> sdtBlocks = docNode.Elements <SdtBlock>();

            foreach (SdtBlock sdtBlock in sdtBlocks)
            {
                // Получить параметры(SdtProperties) Content Control
                SdtProperties sdtProperties = sdtBlock.GetFirstChild <SdtProperties>();

                // Получить Tag для идентификации Content Control
                Tag tag = sdtProperties.GetFirstChild <Tag>();

                // Получить значение макроперенной из macroListXml
                Console.WriteLine("Tag: " + tag.Val);
                String macroVarValue = FindMacroVar(macroListXml, tag.Val);

                // Если макропеременная есть в MacroListXml
                if (macroVarValue != null)
                {
                    Console.WriteLine("Value: " + macroVarValue);
                    // Получить блок содержимого Content Control
                    SdtContentBlock sdtContentBlock = sdtBlock.GetFirstChild <SdtContentBlock>();

                    /* Форматированный текст для абзацев */
                    if (sdtProperties.GetFirstChild <SdtPlaceholder>() != null && sdtContentBlock.GetFirstChild <Paragraph>() != null)
                    {
                        // Сохранить старый стиль параграфа
                        ParagraphProperties oldParagraphProperties = sdtContentBlock.GetFirstChild <Paragraph>().GetFirstChild <ParagraphProperties>().CloneNode(true) as ParagraphProperties;
                        String oldParagraphPropertiesXml           = oldParagraphProperties.InnerXml;

                        // Очистить ноду с контентом
                        sdtContentBlock.RemoveAllChildren();

                        InsertText(macroVarValue, oldParagraphPropertiesXml, sdtContentBlock);
                    }

                    /* Таблицы */
                    if (sdtProperties.GetFirstChild <SdtPlaceholder>() != null && sdtContentBlock.GetFirstChild <Table>() != null)
                    {
                        // Получить ноду таблицы
                        Table table = sdtContentBlock.GetFirstChild <Table>();

                        // Получить все строки таблицы
                        IEnumerable <TableRow> tableRows = table.Elements <TableRow>();

                        // Получить вторую строку из таблицы
                        TableRow tableRow     = tableRows.ElementAt(1) as TableRow;
                        Type     tableRowType = tableRow.GetType();

                        // Получить все стили столбцов
                        List <String> paragraphCellStyles       = new List <string>();
                        IEnumerable <OpenXmlElement> tableCells = tableRow.Elements <TableCell>();
                        foreach (OpenXmlElement tableCell in tableCells)
                        {
                            String paragraphCellStyleXml = tableCell.GetFirstChild <Paragraph>().GetFirstChild <ParagraphProperties>().InnerXml;
                            paragraphCellStyles.Add(paragraphCellStyleXml);
                        }

                        // Удалить все строки, после первой
                        while (tableRows.Count <TableRow>() > 1)
                        {
                            TableRow lastTableRows = tableRows.Last <TableRow>();
                            lastTableRows.Remove();
                        }

                        // Удалить последний элемент, если это не TableRow
                        OpenXmlElement lastNode = table.LastChild;
                        if (lastNode.GetType() != tableRowType)
                        {
                            lastNode.Remove();
                        }

                        string[] rowDelimiters    = new string[] { "|||" };
                        string[] columnDelimiters = new string[] { "^^^" };

                        // Получить массив строк из макропеременной
                        String[] rowsXml = macroVarValue.Split(rowDelimiters, StringSplitOptions.None);
                        int      i       = 0;
                        while (i < rowsXml.Length)
                        {
                            // Получить строку
                            String rowXml = rowsXml[i];

                            // Добавить ноду строки таблицы
                            TableRow newTableRow = table.AppendChild(new TableRow());

                            // Получить из строки массив ячеек
                            String[] cellsXml = rowXml.Split(columnDelimiters, StringSplitOptions.None);

                            int j = 0;
                            while (j < cellsXml.Length)
                            {
                                // Получить ячейку
                                String cellXml = cellsXml[j];

                                // Убрать символ CRLF в конце строки
                                cellXml = cellXml.TrimEnd(new char[] { '\n', '\r' });

                                // Добавить ноду ячейку в строку таблицы
                                TableCell newTableCell = newTableRow.AppendChild(new TableCell());

                                // Вставить текст
                                InsertText(cellXml, paragraphCellStyles[j], newTableCell);

                                j++;
                            }

                            i++;
                        }
                    }

                    /* Картинки */
                    if (sdtProperties.GetFirstChild <SdtContentPicture>() != null)
                    {
                        // Получить путь к файлу
                        String imageFilePath = macroVarValue;

                        // Получить расширение файла
                        String        extension = System.IO.Path.GetExtension(imageFilePath).ToLower();
                        ImagePartType imagePartType;
                        switch (extension)
                        {
                        case "jpeg":
                            imagePartType = ImagePartType.Jpeg;
                            break;

                        case "jpg":
                            imagePartType = ImagePartType.Jpeg;
                            break;

                        case "png":
                            imagePartType = ImagePartType.Png;
                            break;

                        case "bmp":
                            imagePartType = ImagePartType.Bmp;
                            break;

                        case "gif":
                            imagePartType = ImagePartType.Gif;
                            break;

                        default:
                            imagePartType = ImagePartType.Jpeg;
                            break;
                        }
                        ;

                        // Добавить ImagePart в документ
                        ImagePart imagePart = wdDoc.MainDocumentPart.AddImagePart(imagePartType);

                        // Получить картинку
                        using (FileStream stream = new FileStream(imageFilePath, FileMode.Open))
                        {
                            imagePart.FeedData(stream);
                        }

                        // Вычислить width и height
                        Bitmap    img         = new Bitmap(imageFilePath);
                        var       widthPx     = img.Width;
                        var       heightPx    = img.Height;
                        var       horzRezDpi  = img.HorizontalResolution;
                        var       vertRezDpi  = img.VerticalResolution;
                        const int emusPerInch = 914400;
                        const int emusPerCm   = 360000;
                        var       widthEmus   = (long)(widthPx / horzRezDpi * emusPerInch);
                        var       heightEmus  = (long)(heightPx / vertRezDpi * emusPerInch);

                        // Получить ID ImagePart
                        string relationShipId = wdDoc.MainDocumentPart.GetIdOfPart(imagePart);

                        Paragraph   paragraph   = sdtContentBlock.GetFirstChild <Paragraph>();
                        Run         run         = paragraph.GetFirstChild <Run>();
                        Drawing     drawing     = run.GetFirstChild <Drawing>();
                        Inline      inline      = drawing.GetFirstChild <Inline>();
                        Graphic     graphic     = inline.GetFirstChild <Graphic>();
                        GraphicData graphicData = graphic.GetFirstChild <GraphicData>();
                        Picture     pic         = graphicData.GetFirstChild <Picture>();
                        BlipFill    blipFill    = pic.GetFirstChild <BlipFill>();
                        Blip        blip        = blipFill.GetFirstChild <Blip>();

                        string prefix       = "r";
                        string localName    = "embed";
                        string namespaceUri = @"http://schemas.openxmlformats.org/officeDocument/2006/relationships";

                        OpenXmlAttribute oldEmbedAttribute = blip.GetAttribute("embed", namespaceUri);

                        IList <OpenXmlAttribute> attributes = blip.GetAttributes();

                        if (oldEmbedAttribute != null)
                        {
                            attributes.Remove(oldEmbedAttribute);
                        }

                        // Удалить хз что, выявлено практическим путем
                        blipFill.RemoveAllChildren <SourceRectangle>();

                        // Установить новую картинку
                        blip.SetAttribute(new OpenXmlAttribute(prefix, localName, namespaceUri, relationShipId));
                        blip.SetAttribute(new OpenXmlAttribute("cstate", "", "print"));

                        // Подогнать размеры
                        Extent extent = inline.GetFirstChild <Extent>();

                        OpenXmlAttribute oldCxExtent = extent.GetAttribute("cx", "");
                        if (oldCxExtent != null)
                        {
                            var maxWidthEmus = long.Parse(oldCxExtent.Value);
                            if (widthEmus > maxWidthEmus)
                            {
                                var ratio = (heightEmus * 1.0m) / widthEmus;
                                widthEmus  = maxWidthEmus;
                                heightEmus = (long)(widthEmus * ratio);
                            }

                            extent.GetAttributes().Remove(oldCxExtent);
                        }

                        OpenXmlAttribute oldCyExtent = extent.GetAttribute("cy", "");
                        if (oldCyExtent != null)
                        {
                            extent.GetAttributes().Remove(oldCyExtent);
                        }

                        extent.SetAttribute(new OpenXmlAttribute("cx", "", widthEmus.ToString()));
                        extent.SetAttribute(new OpenXmlAttribute("cy", "", heightEmus.ToString()));

                        ShapeProperties shapeProperties = pic.GetFirstChild <ShapeProperties>();
                        Transform2D     transform2D     = shapeProperties.GetFirstChild <Transform2D>();
                        Extents         extents         = transform2D.GetFirstChild <Extents>();

                        OpenXmlAttribute oldCxExtents = extents.GetAttribute("cx", "");
                        if (oldCxExtents != null)
                        {
                            extents.GetAttributes().Remove(oldCxExtents);
                        }

                        OpenXmlAttribute oldCyExtents = extents.GetAttribute("cy", "");
                        if (oldCyExtents != null)
                        {
                            extents.GetAttributes().Remove(oldCyExtents);
                        }

                        extents.SetAttribute(new OpenXmlAttribute("cx", "", widthEmus.ToString()));
                        extents.SetAttribute(new OpenXmlAttribute("cy", "", heightEmus.ToString()));

                        // Удалить placeholder
                        ShowingPlaceholder showingPlaceholder = sdtProperties.GetFirstChild <ShowingPlaceholder>();
                        if (showingPlaceholder != null)
                        {
                            sdtProperties.RemoveChild <ShowingPlaceholder>(showingPlaceholder);
                        }
                    }

                    /* Повторяющийся раздел */
                    if (sdtProperties.GetFirstChild <SdtRepeatedSection>() != null)
                    {
                        // Представить repeatedSection как новый xml документ (сделать корнем)
                        XmlDocument repeatedSectionXml = new XmlDocument();
                        repeatedSectionXml.LoadXml(macroVarValue);

                        // Получить корневой элемент repeatedSection
                        XmlElement rootRepeatedSectionXml = repeatedSectionXml.DocumentElement;

                        // Получить количество repeatedSectionItem
                        XmlNodeList repeatedSectionItems = rootRepeatedSectionXml.SelectNodes("repeatedSectionItem");
                        int         repeatedItemCount    = repeatedSectionItems.Count;

                        Console.WriteLine("Количество repeatedSectionItem: " + repeatedItemCount);

                        /* Блок клонирования ноды повтор. раздела до нужного количества */
                        for (int i = 0; i < repeatedItemCount; i++)
                        {
                            XmlElement macroListRepeatedSectionItem = rootRepeatedSectionXml.SelectSingleNode(String.Format(@"repeatedSectionItem[@id=""{0}""]", i)) as XmlElement;
                            Console.WriteLine("Item " + i + ": " + macroListRepeatedSectionItem.OuterXml);

                            SdtContentBlock sdtContentBlockRepeatedSectionItem = sdtContentBlock.Elements <SdtBlock>().Last <SdtBlock>().GetFirstChild <SdtContentBlock>();

                            Fill(sdtContentBlockRepeatedSectionItem, macroListRepeatedSectionItem, wdDoc);

                            if (i + 1 < repeatedItemCount)
                            {
                                SdtBlock clonedRepeatedSectionItem = sdtContentBlock.GetFirstChild <SdtBlock>().Clone() as SdtBlock;
                                sdtContentBlock.AppendChild <SdtBlock>(clonedRepeatedSectionItem);
                            }
                        }
                        /**/

                        //Fill(sdtContentBlock, macroListRepeatedSection, wdDoc);
                    }
                }

                Console.WriteLine();
            }
        }
Esempio n. 8
0
        public void Process(Body Body, OpenXmlElement Element)
        {
            string InnerText = Element.InnerText;

            if (VerifyCodeToken(ref InnerText))
            {
                Element.Remove();
                Scripting.Eval(InnerText);
                return;
            }

            if (Scripting.CaptureElement(Body, Element))
            {
                Element.Remove();
                return;
            }

            if (string.IsNullOrEmpty(InnerText))
            {
                return;
            }

            if (VerifyToken(ref InnerText, out TokenParameters TokenParams))
            {
                DataType DataType = Data.GetObject(InnerText, TokenParams, out object Obj);

                if (DataType == DataType.None)
                {
                    throw new Exception(string.Format("Could not find data for token '{0}'", InnerText));
                }

                if ((CurrentRun = Element.GetFirstChild <RunProperties>()) == null)
                {
                    SdtProperties SdtProps = Element.GetFirstChild <SdtProperties>();

                    if (SdtProps != null)
                    {
                        CurrentRun = SdtProps.GetFirstChild <RunProperties>();
                    }
                }


                if (Element is SdtContentBlock SdtContentBlock)
                {
                    OpenXmlElement NewContent = GenerateContent(Body, DataType, Obj, TokenParams);

                    // TODO: Non existant template token, do something?
                    if (NewContent == null)
                    {
                        throw new NotImplementedException();
                    }

                    if (NewContent is Run)
                    {
                        NewContent = new Paragraph(new ParagraphProperties(), NewContent);
                    }

                    if (DataType == DataType.PageBreak)
                    {
                        SdtContentBlock.Parent.Parent.ReplaceChild(NewContent, SdtContentBlock.Parent);
                    }
                    else
                    {
                        SdtContentBlock NewBlock = new SdtContentBlock();
                        NewBlock.AppendChild(NewContent);

                        SdtContentBlock.Parent.ReplaceChild(NewBlock, SdtContentBlock);
                    }
                    return;
                }
                else if (Element is SdtContentRun SdtContentRun)
                {
                    // if (SdtRun) seems to replace this part?
                    throw new NotImplementedException();
                }
                else if (Element is SdtRun SdtRun)
                {
                    OpenXmlElement NewContent = GenerateContent(Body, DataType, Obj, TokenParams);

                    // TODO: Non existant template token, do something?
                    if (NewContent == null)
                    {
                        throw new NotImplementedException();
                    }

                    if (NewContent is Table && ParentsAreElement <Paragraph>(SdtRun, out OpenXmlElement FoundParent))
                    {
                        FoundParent.Parent.ReplaceChild(NewContent, FoundParent);
                        return;
                    }

                    Element.Parent.ReplaceChild(NewContent, SdtRun);
                    return;
                }
            }

            // Array is used here because element children are dynamically changed, IEnumerable may have side effects
            OpenXmlElement[] Elements = Element.Elements().ToArray();
            for (int i = 0; i < Elements.Length; i++)
            {
                OpenXmlElement E = Elements[i];

                if (E is Table T)
                {
                    ProcessTable(Body, T);
                }
                else
                {
                    Process(Body, E);
                }
            }
        }