public static WordprocessingDocument InsertText(this WordprocessingDocument doc, string contentControlTag, string text, TraceWriter log, List <string> messages)
        {
            try
            {
                SdtElement element = doc.MainDocumentPart.Document.Body.Descendants <SdtElement>()
                                     .FirstOrDefault(sdt => sdt.SdtProperties.GetFirstChild <Tag>()?.Val == contentControlTag);

                if (element == null)
                {
                    string message = $"ContentControlTag \"{contentControlTag}\" doesn't exist.";
                    log.Info(message);
                    messages.Add(message);
                }
                else
                {
                    element.Descendants <Text>().First().Text = text;
                    element.Descendants <Text>().Skip(1).ToList().ForEach(t => t.Remove());
                }

                return(doc);
            }
            catch (Exception ex)
            {
                string message = $"An error occurred replacing Plain Text ContentControlTag \"{contentControlTag}\". Please ensure its a Plain Text COntent Control.";
                log.Info(message);
                messages.Add(message);
                return(doc);
            }
        }
Exemple #2
0
 public static void SetSdtText(this SdtElement element, string text)
 {
     if (element.Descendants <Text>().FirstOrDefault().Text != null)
     {
         element.Descendants <Text>().FirstOrDefault().Text = text;
     }
 }
        private void ReplaceTextInContentControlByTag(Body body, string contentControlTag, string text)
        {
            SdtElement element = body.Descendants <SdtElement>()
                                 .FirstOrDefault(sdt => sdt.SdtProperties.GetFirstChild <Tag>()?.Val == contentControlTag);

            if (element == null)
            {
                throw new ArgumentException($"ContentControlTag \"{contentControlTag}\" doesn't exist.");
            }

            element.Descendants <Text>().First().Text = text;
            element.Descendants <Text>().Skip(1).ToList().ForEach(t => t.Remove());
        }
Exemple #4
0
        public static void UpdateImageFromPath(this MainDocumentPart mainPart, SdtElement element, string imgPath)
        {
            var picture = element.Descendants<SdtContentPicture>().FirstOrDefault();

            if (picture != null)
            {

                var dr = element.Descendants<Drawing>().FirstOrDefault();
                if (dr != null)
                {
                    var blip = dr.Descendants<DocumentFormat.OpenXml.Drawing.Blip>().FirstOrDefault();
                    if (blip != null)
                    {
                        var embed = blip.Embed;
                        if (embed != null)
                        {

                            IdPartPair idpp = mainPart.Parts
                                .Where(pa => pa.RelationshipId == embed).FirstOrDefault();

                            ImagePart ip = (ImagePart)idpp.OpenXmlPart;

                            using (FileStream fileStream = File.Open(imgPath, FileMode.Open))
                                ip.FeedData(fileStream);
                        }
                        else
                        {
                            ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
                            blip.Embed = mainPart.GetIdOfPart(imagePart);
                            System.IO.Stream data = new System.IO.MemoryStream(File.ReadAllBytes(imgPath));
                            //  using (FileStream stream = new FileStream(imgPath, FileMode.Open))
                            {
                                imagePart.FeedData(data);
                                data.Close();
                            }
                            Console.WriteLine("test");

                            // element.InnerXml = "<w:rPr><w:noProof /></w:rPr><w:tag w:val=\"MyProvider:CoolImage\" /><w:id w:val=\"2083329445\" /><w:picture /></w:sdtPr><w:sdtEndPr xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" /><w:sdtContent xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"><w:p w:rsidR=\"00646939\" w:rsidP=\"00646939\" w:rsidRDefault=\"00646939\"><w:pPr><w:rPr><w:noProof /></w:rPr></w:pPr><w:r w:rsidRPr=\"00646939\"><w:rPr><w:noProof /></w:rPr><w:drawing><wp:inline distT=\"0\" distB=\"0\" distL=\"0\" distR=\"0\" wp14:anchorId=\"40D5DA71\" wp14:editId=\"48213C65\" xmlns:wp14=\"http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing\" xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\"><wp:extent cx=\"4605338\" cy=\"3673658\" /><wp:effectExtent l=\"0\" t=\"0\" r=\"5080\" b=\"3175\" /><wp:docPr id=\"2\" name=\"Picture 2\" /><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" noChangeAspect=\"1\" /></wp:cNvGraphicFramePr><a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\"><a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\"><pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\"><pic:nvPicPr><pic:cNvPr id=\"1\" name=\"\" /><pic:cNvPicPr /></pic:nvPicPr><pic:blipFill><a:blip r:embed=\"rId6\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" /><a:stretch><a:fillRect /></a:stretch></pic:blipFill><pic:spPr><a:xfrm><a:off x=\"0\" y=\"0\" /><a:ext cx=\"4613233\" cy=\"3679955\" /></a:xfrm><a:prstGeom prst=\"rect\"><a:avLst /></a:prstGeom></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p></w:sdtContent>";
                            // Console.WriteLine(element.InnerXml);
                            // element.Parent.Remove();
                            //  element.Remove();
                            //  mainPart.Document.AppendChild(element);

                        }
                    }
                }
            }
        }
Exemple #5
0
    public static IEnumerable <OpenXmlElement> GetContent(this SdtElement Element)
    {
        var first_content_element = Element.Descendants().First(e => e.Parent !.LocalName == "sdtContent" && e is not SdtElement);
        var content_container     = first_content_element.Parent;

        return(content_container !.ChildElements);
    }
Exemple #6
0
    /// <summary>
    /// 複製範本Block,回傳List
    /// </summary>
    /// <param name="srcDocName">來源範本別名</param>
    public List <OpenXmlElement> CopyBlockList(string srcDocName, string blockName)
    {
        try {
            WordprocessingDocument srcDoc     = tplDoc[srcDocName];
            List <OpenXmlElement>  arrElement = new List <OpenXmlElement>();
            Tag elementTag = srcDoc.MainDocumentPart.RootElement.Descendants <Tag>()
                             .Where(
                element => element.Val.Value.ToLower() == blockName.ToLower()
                ).SingleOrDefault();

            if (elementTag != null)
            {
                SdtElement      block     = (SdtElement)elementTag.Parent.Parent;
                SdtContentBlock blockCont = block.Descendants <SdtContentBlock>().FirstOrDefault();
                if (blockCont != null)
                {
                    IEnumerable <OpenXmlElement> childs = blockCont.ChildElements;
                    foreach (var item in childs)
                    {
                        arrElement.Add(item.CloneNode(true));
                    }
                }
            }
            return(arrElement);
        }
        catch (Exception ex) {
            throw new Exception("複製範本Block!!(" + blockName + ")", ex);
        }
    }
Exemple #7
0
        void SetLogo(SdtElement element, byte[] image, WordprocessingDocument document)
        {
            try
            {
                // Assuming that the first image is the logo placeholder. This is a reasonable assumption.
                var blip = element.Descendants <Blip>().FirstOrDefault();

                string imgId = "LogoPicture";

                //assuming only one headerpart will have images
                var imagePart = document.MainDocumentPart.HeaderParts.First(p => p.ImageParts.Any())
                                .AddImagePart(ImagePartType.Png, imgId);

                using (var imageStream = new MemoryStream(image))
                {
                    imagePart.FeedData(imageStream);
                }
                if (blip != null)
                {
                    blip.Embed = imgId;
                }
            }
            catch (Exception e)
            {
                //do nothing - just image will not be replaced
            }
        }
        void SetLogo(SdtElement element, byte[] image, WordprocessingDocument document)
        {
            try
            {
                var blip = element.Descendants <Blip>().FirstOrDefault();

                var imgId = "LogoPicture";

                var existingImage = document.MainDocumentPart.GetPartById(blip.Embed);

                var imagePart = document.MainDocumentPart.HeaderParts.First(p => p.ImageParts.Any())
                                .AddImagePart(ImagePartType.Png, imgId);

                using (var imageStream = new MemoryStream(image))
                {
                    imagePart.FeedData(imageStream);
                }
                if (blip != null)
                {
                    blip.Embed = imgId;
                }
            }
            catch (Exception e)
            {
                //do nothing - just image will not be replaced
            }
        }
Exemple #9
0
        /// <summary>
        /// Gets the text from content control.
        /// </summary>
        /// <param name="contentControl">The content control.</param>
        /// <returns></returns>
        public string GetTextFromContentControl(SdtElement contentControl)
        {
            string result = null;

            if (contentControl != null)
            {
                if (contentControl is SdtRun)
                {
                    if (IsContentControlMultiline(contentControl))
                    {
                        var runs = contentControl.Descendants <SdtContentRun>().First().Elements()
                                   .Where(elem => elem is Run || elem is InsertedRun);

                        List <string> runTexts = new List <string>();

                        if (runs != null)
                        {
                            foreach (var run in runs)
                            {
                                foreach (var runChild in run.Elements())
                                {
                                    Text  runText  = runChild as Text;
                                    Break runBreak = runChild as Break;

                                    if (runText != null)
                                    {
                                        runTexts.Add(runText.Text);
                                    }
                                    else if (runBreak != null)
                                    {
                                        runTexts.Add(Environment.NewLine);
                                    }
                                }
                            }
                        }

                        StringBuilder stringBuilder = new StringBuilder();

                        foreach (string item in runTexts)
                        {
                            stringBuilder.Append(item);
                        }

                        result = stringBuilder.ToString();
                    }
                    else
                    {
                        result = contentControl.InnerText;
                    }
                }
                else
                {
                    result = contentControl.InnerText;
                }
            }

            return(result);
        }
Exemple #10
0
        private static bool ReplaceSdtContent(SdtElement element, JToken json, string tag)
        {
            Text text = element.Descendants <Text>().Where(r => r.Text == tag).FirstOrDefault();

            if (text != null)
            {
                text.Text = json.Value <string>();
                return(true);
            }

            return(false);
        }
Exemple #11
0
        public override Task UpdateElement(MainDocumentPart mainPart, SdtElement element, TemplateReplacement tag)
        {
            if (tag is TemplateImageReplacement image)
            {
                mainPart.UpdateImageFromPath(element, "../../../../../data/Hello-Im-Awesome.jpg");
            }
            else
            {
                if (tag.TagName == $"{nameof(MyProvider)}:Table")
                {
                    element.WriteJsonTable("../../../tablejson.json", mainPart);

                    //   InsertAPicture(mainPart, "../../../../../data/Hello-Im-Awesome.jpg",element);
                }
                else
                {
                    element.Descendants <Text>().First().Text = "Hello World";
                    element.Descendants <Text>().Skip(1).ToList().ForEach(t => t.Remove());
                }
            }

            return(base.UpdateElement(mainPart, element, tag));
        }
        protected List <string> image_urls;   // Store url to show pictures (if there are any)

        /// <summary>
        /// Constructor that find and initialize the first table found in the content control
        /// </summary>
        /// <param name="content_control)">SdtElement instance represent the content control</param>
        public Helper_WordTable_Columns(SdtElement content_control)
        {
            image_urls = new List <string>();
            if (!Init(content_control))
            {
                return;
            }

            //Get the first Table instance found in the content control
            table = content_control.Descendants <Table>().First();

            if (table == null)
            {
                StaticValues.logs += "[Error]Can't get table in the content control" + Environment.NewLine;
            }
        }
        private static WordprocessingDocument ReplaceTable(WordprocessingDocument localDocxFile, TableReplacementParameters tableParm, TraceWriter log, List <string> messages)
        {
            try
            {
                MainDocumentPart mainPart = localDocxFile.MainDocumentPart;
                var        stuff          = mainPart.Document.Body.Descendants <SdtElement>();
                SdtElement ccWithTable    = localDocxFile.MainDocumentPart.Document.Body.Descendants <SdtElement>()
                                            .FirstOrDefault(sdt => sdt.SdtProperties.GetFirstChild <Tag>()?.Val == tableParm.token);

                //                SdtElement ccWithTable = mainPart.Document.Body.Descendants<SdtElement>().Where
                //               (r => r.SdtProperties.GetFirstChild<Tag>().Val == tableParm.token).Single();

                // This should return only one table.
                Table theTable = ccWithTable.Descendants <Table>().Single();

                // Get the last row in the table. Table should have one tow with titles and an empty data row.
                TableRow theRow = theTable.Elements <TableRow>().Last();
                foreach (var tblParmRow in tableParm.rows)
                {
                    TableRow rowCopy = (TableRow)theRow.CloneNode(true);
                    int      colidx  = 0;
                    foreach (var tblParmCol in tblParmRow.columns)
                    {
                        Console.WriteLine(tblParmCol.value);
                        rowCopy.Descendants <TableCell>().ElementAt(colidx).Append(new Paragraph
                                                                                       (new Run(new Text(tblParmCol.value))));
                        colidx++;
                    }
                    theTable.AppendChild(rowCopy);
                }
                // Remove the empty placeholder row from the table.
                theTable.RemoveChild(theRow);

                // Save the changes to the table back into the document.
                mainPart.Document.Save();

                return(localDocxFile);
            }
            catch (Exception ex)
            {
                string message = $"An error occurred replacing the table in Plain Text Content Control Tag \"{tableParm.token}\". Please ensure its a Plain Text COntent Control that contains a table, and the number of columns in that table is equal to the number of columns in the JSON array.";
                log.Info(message);
                messages.Add(message);
                return(localDocxFile);
            }
        }
Exemple #14
0
        /// <summary>
        /// Get the data in a content control
        /// </summary>
        /// <param name="content_control">The SdtElement instance represent the content control</param>
        /// <returns> The content of the content control in string</returns>
        public static string GetContentControlContents(SdtElement content_control)
        {
            string result = "";

            try
            {
                foreach (Text t in content_control.Descendants <Text>())
                {
                    result += t.Text;
                }
            }
            catch (Exception ex)
            {
                StaticValues.logs += ex.Message + Environment.NewLine;
                result             = null;
            }
            return(result);
        }
Exemple #15
0
        public static void SetSdtTextColor(this SdtElement element, string color)
        {
            var runProperties = element.Descendants <RunProperties>().ToList();

            foreach (var rp in runProperties)
            {
                try
                {
                    rp.Color = new Color()
                    {
                        Val = color
                    };
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("Не удалось установить цвет текста в Structured Document Tag элементе.", ex.InnerException);
                }
            }
        }
Exemple #16
0
        private static Paragraph[] copyTag4(WordprocessingDocument doc, string tagName)
        {
            List <Paragraph> arrElement = new List <Paragraph>();
            Tag elementTag = doc.MainDocumentPart.RootElement.Descendants <Tag>()
                             .Where(
                element => element.Val.Value.ToLower() == tagName.ToLower()
                ).SingleOrDefault();

            //Console.WriteLine("start find " + tagName + "..");
            if (elementTag != null)
            {
                Console.WriteLine("find " + tagName + "!!");

                SdtElement block = (SdtElement)elementTag.Parent.Parent;
                IEnumerable <Paragraph> tagRuns = block.Descendants <Paragraph>();
                foreach (Paragraph tagRun in tagRuns)
                {
                    arrElement.Add(new Paragraph(new Run(new Text(tagRun.InnerText))));
                }
            }
            return(arrElement.ToArray());
        }
Exemple #17
0
        private static OpenXmlElement copyTag(WordprocessingDocument doc, WordprocessingDocument outdoc, string tagName)
        {
            Body body       = outdoc.MainDocumentPart.Document.Body;
            Tag  elementTag = doc.MainDocumentPart.RootElement.Descendants <Tag>()
                              .Where(
                element => element.Val == tagName
                ).SingleOrDefault();

            Console.WriteLine("start find " + tagName + "..");
            if (elementTag != null)
            {
                Console.WriteLine("find " + tagName + "!!");

                SdtElement block = (SdtElement)elementTag.Parent.Parent;
                IEnumerable <Paragraph> tagRuns = block.Descendants <Paragraph>();
                foreach (Paragraph tagRun in tagRuns)
                {
                    body.AppendChild(tagRun.CloneNode(true));
                    //return tagRun.CloneNode(true);
                }
            }
            return(new Text());
        }
Exemple #18
0
    public void CopyTable(string srcDocName, string blockName)
    {
        try {
            WordprocessingDocument srcDoc     = tplDoc[srcDocName];
            List <OpenXmlElement>  arrElement = new List <OpenXmlElement>();
            Tag elementTag = srcDoc.MainDocumentPart.RootElement.Descendants <Tag>()
                             .Where(
                element => element.Val.Value.ToLower() == blockName.ToLower()
                ).SingleOrDefault();

            if (elementTag != null)
            {
                SdtElement      block     = (SdtElement)elementTag.Parent.Parent;
                SdtContentBlock blockCont = block.Descendants <SdtContentBlock>().FirstOrDefault();
                if (blockCont != null)
                {
                    tmpTable = blockCont.Descendants <Table>().FirstOrDefault();
                }
            }
        }
        catch (Exception ex) {
            throw new Exception("複製Table錯誤!!(" + blockName + ")", ex);
        }
    }
        /// <summary>
        /// Determine the type of content control and take neccessary actions
        /// </summary>
        /// <param name="content_control">A SdteElement instance represent a content control</param>
        /// <param name="condional">A DataRow instance contains required values for conditional (used in repeat content control)</param>
        protected void ProcessBasedOnContentControl(SdtElement content_control, DataRow conditional)
        {
            SdtAlias alias = content_control.Descendants <SdtAlias>().FirstOrDefault();

            if (alias.Val.ToString().ToLower() == StaticValues.repeat_cc_name)
            {
                Helper_WordRepeat repeat_helper = new Helper_WordRepeat(content_control);
                repeat_helper.Execute();
            }
            else if (alias.Val.ToString().ToLower() == StaticValues.columntable_cc_name)
            {
                Helper_WordTable_Columns table_helper = new Helper_WordTable_Columns(content_control);
                table_helper.AddConditionToSQLQuery(conditional);
                table_helper.AddDataToTable();
            }
            else if (alias.Val.ToString().ToLower() == StaticValues.rowtable_cc_name)
            {
                Helper_WordTable_Rows table_helper = new Helper_WordTable_Rows(content_control);
                table_helper.AddConditionToSQLQuery(conditional);
                table_helper.AddDataToTable();
            }
            else if (alias.Val.ToString().ToLower() == StaticValues.hybridtable_cc_name)
            {
                Helper_WordTable_Hybrid table_helper = new Helper_WordTable_Hybrid(content_control);
                table_helper.AddConditionToSQLQuery(conditional);
                table_helper.AddDataToTable();
            }
            else if (alias.Val.ToString().ToLower() == StaticValues.barchart_cc_name)
            {
                Helper_WordBarChart chart_helper = new Helper_WordBarChart(content_control);
                chart_helper.AddConditionToSQLQuery(conditional);
                chart_helper.UpdateChartFromSQL();
            }
            else if (alias.Val.ToString().ToLower() == StaticValues.piechart_cc_name)
            {
                Helper_WordPieChart chart_helper = new Helper_WordPieChart(content_control);
                chart_helper.AddConditionToSQLQuery(conditional);
                chart_helper.UpdateChartFromSQL();
            }
            else if (alias.Val.ToString().ToLower() == StaticValues.linechart_cc_name)
            {
                Helper_WordLineChart chart_helper = new Helper_WordLineChart(content_control);
                chart_helper.AddConditionToSQLQuery(conditional);
                chart_helper.UpdateChartFromSQL();
            }
            else if (alias.Val.ToString().ToLower() == StaticValues.val_cc_name)
            {
                Helper_WordBase helper = new Helper_WordBase();
                helper.Init(content_control);
                helper.AddConditionToSQLQuery(conditional);
                string content = helper.GetDataFromDatabaseUsingSQL().Rows[0][0].ToString();

                if (Helper_WordPicture.IsUrl(content) && Helper_WordPicture.IsImageUrl(content))
                {
                    // It is picture
                    SdtElement         image_cc   = content_control.Descendants <SdtElement>().Where(s => s.Descendants <SdtAlias>().FirstOrDefault().Val.ToString().ToLower() == StaticValues.image_cc_name).FirstOrDefault();
                    Helper_WordPicture pic_helper = new Helper_WordPicture(image_cc, content);
                    pic_helper.AddPictureFromUri();
                }
                else // Just normal text
                {
                    Helper_WordBase.ReplaceContentsInContentControl(content_control, content);
                }
            }
        }
Exemple #20
0
        private void buttonTRY_Click_1(object sender, EventArgs e)
        {
            richTextBox1.LoadFile("template_vkr_bachelor.rtf");
            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open("template_vkr_bachelor.docx", true))
            {
                foreach (var item in wordDoc.MainDocumentPart.Document.Body)
                {
                    var oo = item.Descendants <SdtProperties>();
                    foreach (var f1 in oo)
                    {
                        Tag    tag  = f1.Elements <Tag>().FirstOrDefault();
                        string _tag = "";

                        if (tag != null)
                        {
                            _tag = tag.Val;
                        }

                        if (_tag.Contains("_institute")) // #1
                        {
                            SdtElement element = wordDoc.MainDocumentPart.Document.Body.Descendants <SdtElement>().FirstOrDefault(sdt => sdt.SdtProperties.GetFirstChild <Tag>() != null ? sdt.SdtProperties.GetFirstChild <Tag>().Val == _tag : false);
                            if (comboBox1.SelectedIndex != -1)
                            {
                                element.Descendants <Text>().First().Text = comboBox1.SelectedItem.ToString();
                            }
                        }
                        if (_tag.Contains("_department")) // #2
                        {
                            SdtElement element = wordDoc.MainDocumentPart.Document.Body.Descendants <SdtElement>().FirstOrDefault(sdt => sdt.SdtProperties.GetFirstChild <Tag>() != null ? sdt.SdtProperties.GetFirstChild <Tag>().Val == _tag : false);
                            if (comboBox1.SelectedIndex != -1)
                            {
                                element.Descendants <Text>().First().Text = comboBox2.SelectedItem.ToString();
                            }
                        }
                        if (_tag.Contains("_theme")) // #3
                        {
                            SdtElement element = wordDoc.MainDocumentPart.Document.Body.Descendants <SdtElement>().FirstOrDefault(sdt => sdt.SdtProperties.GetFirstChild <Tag>() != null ? sdt.SdtProperties.GetFirstChild <Tag>().Val == _tag : false);
                            if (comboBox1.SelectedIndex != -1)
                            {
                                element.Descendants <Text>().First().Text = comboBox3.SelectedItem.ToString();
                            }
                        }
                        if (_tag.Contains("_code")) // #4
                        {
                            SdtElement element = wordDoc.MainDocumentPart.Document.Body.Descendants <SdtElement>().FirstOrDefault(sdt => sdt.SdtProperties.GetFirstChild <Tag>() != null ? sdt.SdtProperties.GetFirstChild <Tag>().Val == _tag : false);
                            if (comboBox1.SelectedIndex != -1)
                            {
                                element.Descendants <Text>().First().Text = comboBox4.SelectedItem.ToString();
                            }
                        }
                        if (_tag.Contains("_specialization")) // #5
                        {
                            SdtElement element = wordDoc.MainDocumentPart.Document.Body.Descendants <SdtElement>().FirstOrDefault(sdt => sdt.SdtProperties.GetFirstChild <Tag>() != null ? sdt.SdtProperties.GetFirstChild <Tag>().Val == _tag : false);
                            if (comboBox1.SelectedIndex != -1)
                            {
                                element.Descendants <Text>().First().Text = comboBox5.SelectedItem.ToString();
                            }
                        }
                        if (_tag.Contains("_section")) // #6
                        {
                            SdtElement element = wordDoc.MainDocumentPart.Document.Body.Descendants <SdtElement>().FirstOrDefault(sdt => sdt.SdtProperties.GetFirstChild <Tag>() != null ? sdt.SdtProperties.GetFirstChild <Tag>().Val == _tag : false);
                            if (comboBox1.SelectedIndex != -1)
                            {
                                element.Descendants <Text>().First().Text = comboBox6.SelectedItem.ToString();
                            }
                        }
                        if (_tag.Contains("_student")) // #7
                        {
                            SdtElement element = wordDoc.MainDocumentPart.Document.Body.Descendants <SdtElement>().FirstOrDefault(sdt => sdt.SdtProperties.GetFirstChild <Tag>() != null ? sdt.SdtProperties.GetFirstChild <Tag>().Val == _tag : false);
                            if (comboBox1.SelectedIndex != -1)
                            {
                                element.Descendants <Text>().First().Text = comboBox7.SelectedItem.ToString();
                            }
                        }
                        if (_tag.Contains("_head_dep_name")) // #8
                        {
                            SdtElement element = wordDoc.MainDocumentPart.Document.Body.Descendants <SdtElement>().FirstOrDefault(sdt => sdt.SdtProperties.GetFirstChild <Tag>() != null ? sdt.SdtProperties.GetFirstChild <Tag>().Val == _tag : false);
                            if (comboBox1.SelectedIndex != -1)
                            {
                                element.Descendants <Text>().First().Text = comboBox8.SelectedItem.ToString();
                            }
                        }
                        if (_tag.Contains("_head_dep_degree")) // #9
                        {
                            SdtElement element = wordDoc.MainDocumentPart.Document.Body.Descendants <SdtElement>().FirstOrDefault(sdt => sdt.SdtProperties.GetFirstChild <Tag>() != null ? sdt.SdtProperties.GetFirstChild <Tag>().Val == _tag : false);
                            if (comboBox1.SelectedIndex != -1)
                            {
                                element.Descendants <Text>().First().Text = comboBox9.SelectedItem.ToString();
                            }
                        }
                        if (_tag.Contains("_adviser_name")) // #10
                        {
                            SdtElement element = wordDoc.MainDocumentPart.Document.Body.Descendants <SdtElement>().FirstOrDefault(sdt => sdt.SdtProperties.GetFirstChild <Tag>() != null ? sdt.SdtProperties.GetFirstChild <Tag>().Val == _tag : false);
                            if (comboBox1.SelectedIndex != -1)
                            {
                                element.Descendants <Text>().First().Text = comboBox10.SelectedItem.ToString();
                            }
                        }
                        if (_tag.Contains("_adviser_degree")) // #11
                        {
                            SdtElement element = wordDoc.MainDocumentPart.Document.Body.Descendants <SdtElement>().FirstOrDefault(sdt => sdt.SdtProperties.GetFirstChild <Tag>() != null ? sdt.SdtProperties.GetFirstChild <Tag>().Val == _tag : false);
                            if (comboBox1.SelectedIndex != -1)
                            {
                                element.Descendants <Text>().First().Text = comboBox11.SelectedItem.ToString();
                            }
                        }
                        if (_tag.Contains("_year")) // #12
                        {
                            SdtElement element = wordDoc.MainDocumentPart.Document.Body.Descendants <SdtElement>().FirstOrDefault(sdt => sdt.SdtProperties.GetFirstChild <Tag>() != null ? sdt.SdtProperties.GetFirstChild <Tag>().Val == _tag : false);
                            if (comboBox1.SelectedIndex != -1)
                            {
                                element.Descendants <Text>().First().Text = textBox13.Text;
                            }
                        }
                    }
                }
                wordDoc.Close();
            }
        }
        public static WordprocessingDocument InsertImages(this WordprocessingDocument doc, ClientContext clientContext, string contentControlTag, string attachementServerRelativeUrl, TraceWriter log, List <string> messages)
        {
            try
            {
                SdtElement cc = doc.MainDocumentPart.Document.Body.Descendants <SdtElement>().FirstOrDefault(c =>
                {
                    SdtProperties p = c.Elements <SdtProperties>().FirstOrDefault();
                    if (p != null)
                    {
                        // Is it a picture content control?
                        SdtContentPicture pict = p.Elements <SdtContentPicture>().FirstOrDefault();
                        // Get the alias.
                        SdtAlias a = p.Elements <SdtAlias>().FirstOrDefault();

                        if (pict != null && a.Val == contentControlTag)
                        {
                            return(true);
                        }
                    }
                    return(false);
                });
                string embed = null;
                if (cc != null)
                {
                    Drawing dr = cc.Descendants <Drawing>().FirstOrDefault();
                    if (dr != null)
                    {
                        DocumentFormat.OpenXml.Drawing.Blip blip = dr.Descendants <DocumentFormat.OpenXml.Drawing.Blip>().FirstOrDefault();
                        if (blip != null)
                        {
                            embed = blip.Embed;
                        }
                    }
                }
                if (embed != null)
                {
                    IdPartPair idpp = doc.MainDocumentPart.Parts
                                      .Where(pa => pa.RelationshipId == embed).FirstOrDefault();
                    if (idpp != null)
                    {
                        ImagePart ip             = (ImagePart)idpp.OpenXmlPart;
                        var       attachmentFile = clientContext.Site.RootWeb.GetFileByServerRelativeUrl(attachementServerRelativeUrl);
                        clientContext.Load(attachmentFile);
                        clientContext.ExecuteQueryRetry();
                        if (attachmentFile != null)
                        {
                            // Returns required result
                            ClientResult <Stream> attachmentStream = attachmentFile.OpenBinaryStream();
                            clientContext.ExecuteQueryRetry();
                            ip.FeedData(attachmentStream.Value);
                        }
                    }
                }
                return(doc);
            }
            catch (Exception ex)
            {
                string message = $"An error occurred replacing Image Content Control Tag \"{contentControlTag}\". Please ensure its an Image Content Control, and the value is the server relative url of an image file that you have access to";
                log.Info(message);
                messages.Add(message);
                return(doc);
            }
        }
Exemple #22
0
        public static void SetContentOfContentControl(SdtElement contentControl, string content)
        {
            if (contentControl == null)
            {
                throw new ArgumentNullException("contentControl");
            }

            content = string.IsNullOrEmpty(content) ? string.Empty : content;
            var isCombobox = contentControl.SdtProperties.Descendants <SdtContentDropDownList>().FirstOrDefault() != null;
            var isImage    = contentControl.SdtProperties.Descendants <SdtContentPicture>().FirstOrDefault() != null;
            var prop       = contentControl.Elements <SdtProperties>().FirstOrDefault();

            if (isCombobox)
            {
                var openXmlCompositeElement = GetSdtContentOfContentControl(contentControl);
                var run = CreateRun(openXmlCompositeElement, content);
                SetSdtContentKeepingPermissionElements(openXmlCompositeElement, run);
            }

            if (isImage)
            {
                string  embed = null;
                Drawing dr    = contentControl.Descendants <Drawing>().FirstOrDefault();
                if (dr != null)
                {
                    DocumentFormat.OpenXml.Drawing.Blip blip = dr.Descendants <DocumentFormat.OpenXml.Drawing.Blip>().FirstOrDefault();
                    if (blip != null)
                    {
                        embed = blip.Embed;
                    }
                }

                if (embed != null)
                {
                    var        document = (Document)prop.Ancestors <Body>().FirstOrDefault().Parent;
                    IdPartPair idpp     = document.MainDocumentPart.Parts.Where(pa => pa.RelationshipId == embed).FirstOrDefault();
                    if (idpp != null)
                    {
                        ImagePart     ip = (ImagePart)idpp.OpenXmlPart;
                        DirectoryInfo di = new DirectoryInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);
                        using (FileStream fileStream = File.Open(Path.Combine(di.Parent.FullName, content), FileMode.Open))
                        {
                            ip.FeedData(fileStream);
                        }
                    }
                }
            }
            else
            {
                var openXmlCompositeElement = GetSdtContentOfContentControl(contentControl);
                contentControl.SdtProperties.RemoveAllChildren <ShowingPlaceholder>();
                var runs = new List <Run>();

                if (IsContentControlMultiline(contentControl))
                {
                    var textSplitted = content.Split(Environment.NewLine.ToCharArray()).ToList();
                    var addBreak     = false;

                    foreach (var textSplit in textSplitted)
                    {
                        var run = CreateRun(openXmlCompositeElement, textSplit);

                        if (addBreak)
                        {
                            run.AppendChild(new Break());
                        }

                        if (!addBreak)
                        {
                            addBreak = true;
                        }

                        runs.Add(run);
                    }
                }
                else
                {
                    runs.Add(CreateRun(openXmlCompositeElement, content));
                }

                SdtContentCell aopenXmlCompositeElement = openXmlCompositeElement as SdtContentCell;
                if (aopenXmlCompositeElement != null)
                {
                    AddRunsToSdtContentCell(aopenXmlCompositeElement, runs);
                }
                else if (openXmlCompositeElement is SdtContentBlock)
                {
                    var para = CreateParagraph(openXmlCompositeElement, runs);
                    SetSdtContentKeepingPermissionElements(openXmlCompositeElement, para);
                }
                else
                {
                    SetSdtContentKeepingPermissionElements(openXmlCompositeElement, runs);
                }
            }
        }
Exemple #23
0
 /// <summary>
 /// Add text to content control
 /// </summary>
 /// <param name="content_control">The content control where we want to input text</param>
 /// <param name="append_text">The text we want to append</param>
 public static void ReplaceContentsInContentControl(SdtElement content_control, string append_text)
 {
     content_control.Descendants <Text>().First().Text = append_text;
     content_control.Descendants <Text>().Skip(1).ToList().ForEach(t => t.Remove());
 }
 private static string GetTagValue(SdtElement sdt) => sdt
 .Descendants <Tag>()
 .Select(tag => tag.Val.Value)
 .FirstOrDefault();