Click here to Skip to main content
15,912,082 members
Home / Discussions / C#
   

C#

 
GeneralRe: Multi Page Application Pin
OriginalGriff5-May-15 1:06
mveOriginalGriff5-May-15 1:06 
GeneralRe: Multi Page Application Pin
Usmanaf5-May-15 1:33
Usmanaf5-May-15 1:33 
GeneralRe: Multi Page Application Pin
OriginalGriff5-May-15 2:21
mveOriginalGriff5-May-15 2:21 
GeneralRe: Multi Page Application Pin
Sascha Lefèvre5-May-15 1:43
professionalSascha Lefèvre5-May-15 1:43 
QuestionHow to use chrome webbrowser in C# .NET windows form application Pin
Member 116126623-May-15 23:22
Member 116126623-May-15 23:22 
AnswerRe: How to use chrome webbrowser in C# .NET windows form application Pin
Eddy Vluggen3-May-15 23:24
professionalEddy Vluggen3-May-15 23:24 
GeneralRe: How to use chrome webbrowser in C# .NET windows form application Pin
Member 116126624-May-15 16:09
Member 116126624-May-15 16:09 
QuestionHow to use "altChunk" to put HTML into a MS Word object that is embedded into a PowerPoint slide? Pin
pats2Kdynasty3-May-15 11:53
pats2Kdynasty3-May-15 11:53 
Ok so I saw the cast on "altChunk" (https://www.youtube.com/watch?v=couuEc6eEjE) and the blog (http://blogs.msdn.com/b/ericwhite/archive/2008/10/27/how-to-use-altchunk-for-document-assembly.aspx), especially the HTML section. I am very new to XML and it's tools and I have been struggling to put all the pieces together. 85% of code is from research and altered.

OBJECTIVE: I have a PowerPoint slide template that has a couple of text fields that I fill (id [uic], name, PreviousDate, CurrentDate, ...) then it has two embedded word objects representing Previous Notes and Current Notes respectively. These two embedded Word objects are what I am trying to put HTML in. The HTML comes from user input via the web and stores it in a DB field. So I am looping through my data rows-->creating a copy of the slide template-->filling the placeholders (id [uic], name, PreviousDate, CurrentDate) with the data from a row-->then I am trying to fill each embedded Word object with it's HTML data-->save the slide and start the process over for each row of data.

Here is what I have so far. I have gone down many rabbit trails but I have tried to clean the code up to show just current code. My current issue is that when the slide saves it disposes my object/connection/stream(?) so I can not fill the second object. Do I need to not save until I fill both Word objects? I see the "altChunkID" but I can not tell if it actually references anything. Do I need to declare an XNamespace for the altChunk relationship?

I think I am close, but I just missing a few pieces that tie it all together. Any assistance would be educational and greatly appreciated. Below is my code; starting with a call to renderPPT(). ...Thank you in advance. :

C#
using System;
using System.Globalization;
using System.Data;
using System.Data.Odbc;
using System.Drawing;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Configuration;
using System.Security.Principal;
using System.Text;
using System.Data.SqlClient;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml.Presentation;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Drawing;
using System.Xml;
using System.Xml.Linq;


namespace NotesFor.HtmlToOpenXml
{
    public partial class Data2PPT : System.Web.UI.Page
    {
        static int index = 1;
        XDocument mainDocX = new XDocument();


        public partial class Data2Powerpoint
        {
            public string strUIC;
            public string strANAME;
            public string strPrevUpdate;
            public HtmlAgilityPack.HtmlDocument htmlPrevNotes;
            public HtmlAgilityPack.HtmlDocument htmlCurrNotes;
            public string strCurrUpdate;


            public Data2Powerpoint()
            { }
        }


        public void renderPPT()
        {
            if (File.Exists(Server.MapPath("PowerPointTemplate/FAMBriefingNotes.pptx"))) //delete powerpoint file if it exits
            { File.Delete(Server.MapPath("PowerPointTemplate/FAMBriefingNotes.pptx")); }


            File.Copy(Server.MapPath("PowerPointTemplate/EmbedWordPPT.pptx"), Server.MapPath("PowerPointTemplate/FAMBriefingNotes.pptx"), true);


            using (PresentationDocument myPres = PresentationDocument.Open(Server.MapPath("PowerPointTemplate/FAMBriefingNotes.pptx"), true))
            {
                PresentationPart presPart = myPres.PresentationPart;  //Get presentation part


                if (presPart != null && presPart.Presentation != null) //verify that pres part and presentation exists
                {
                    Presentation pres = presPart.Presentation;  //get presentation object


                    if (pres.SlideIdList != null)  //verify that slideId list exists
                    {
                        var slideIDs = pres.SlideIdList.ChildElements;  //collection of slide IDs from slide list
                        string slidePartRelationshipID = (slideIDs[0] as SlideId).RelationshipId;  //get relationship id 
                        SlidePart sldPart = (SlidePart)presPart.GetPartById(slidePartRelationshipID);  //use relatioship id to get slide part


                        //SlidePart sectionSlidePart = (SlidePart)presPart.GetPartById("rId3");


                        if (Session["dtbl2ppt"] != null)  // is there a session variable
                        {
                            DataTable dt = (DataTable)Session["dtbl2ppt"];
                            if (dt.Rows.Count > 0)   //does the datatable have any rows  tblPPTNotes````````````````
                            {                               
                                for (int i = 0; i < dt.Rows.Count; i++)
                                {
                                    SlidePart newSldPart = CloneSlidePart(presPart, sldPart);
                                    //SwapPlaceholderText(newTablePart, "Section", "FAM Briefing Notes2");


                                    //Add style back in to innerHtml to give meaning to span class references
                                    string HTMLheader = @"<html> <p align='left'>
                                    <head>
                                        <style id='oboutEditorDefaultStyle'>
                                        .blueItalic    { color: #0000ff; font-style:italic;}
                                        body       {
                                                    color:#404040;background-color: #fff;
                                                    border-width: 0px;margin-top: 0px; margin-bottom: 0px;
                                                    margin-left: 0px; margin-right: 0px;
                                                    padding-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px;
                                                   }
                                        body,table td
                                                   {
                                                    font-family: verdana,sans-serif;font-size: 10pt;
                                                   }
                                        h1         {
                                                    font-size: 24pt;
                                                   }
                                        h2         {
                                                    font-size: 18pt;
                                                   }
                                        h3         {
                                                    font-size: 14pt;
                                                   }
                                        h4         {
                                                    font-size: 12pt;
                                                   }
                                        h5         {
                                                    font-size: 10pt;
                                                   }
                                        h6         {
                                                    font-size:  8pt;
                                                   }          
                                        </style>
                                        </head>
                                        <body>";


                                    string HTMLfooter = @"</p></body></html>"; 


                                    HtmlAgilityPack.HtmlDocument htmlPrevNotesDoc = new HtmlAgilityPack.HtmlDocument();
                                    htmlPrevNotesDoc.OptionOutputAsXml = true;
                                    htmlPrevNotesDoc.LoadHtml(HTMLheader + dt.Rows[i]["PrevUnitNotes"].ToString() + HTMLfooter);


                                    HtmlAgilityPack.HtmlDocument htmlCurrNotesDoc = new HtmlAgilityPack.HtmlDocument();
                                    htmlCurrNotesDoc.OptionOutputAsXml = true;
                                    htmlCurrNotesDoc.LoadHtml(HTMLheader + dt.Rows[i]["CurrUnitNotes"].ToString() + HTMLfooter);


                                    //format dates
                                    String strPrevDT = ""; String strCurrDT = "";
                                    if (dt.Rows[i]["PrevUpdate"] != null && dt.Rows[i]["PrevUpdate"].ToString().Length > 0)
                                    { strPrevDT=DateTime.Parse(dt.Rows[i]["PrevUpdate"].ToString()).ToString("yyyy-MMM-dd HH:MM"); }
                                    if (dt.Rows[i]["CurrUpdate"] != null && dt.Rows[i]["CurrUpdate"].ToString().Length > 0)
                                    { strCurrDT = DateTime.Parse(dt.Rows[i]["CurrUpdate"].ToString()).ToString("yyyy-MMM-dd HH:MM"); }


                                    SwapPlaceholderText(myPres, newSldPart, "UIC", dt.Rows[i]["UIC"].ToString(), false, i);
                                    SwapPlaceholderText(myPres, newSldPart, "ANAME", dt.Rows[i]["ANAME"].ToString(), false, i);
                                    SwapPlaceholderText(myPres, newSldPart, "PrevUpdate", strPrevDT, false, i);
                                    SwapPlaceholderText(myPres, newSldPart, "CurrUpdate", strCurrDT, false, i);
                                    SwapPlaceholderText(myPres, newSldPart, "PrevUnitNotes", htmlPrevNotesDoc.DocumentNode.InnerHtml, true, i);
                                    SwapPlaceholderText(myPres, newSldPart, "CurrUnitNotes", htmlCurrNotesDoc.DocumentNode.InnerHtml, true, i + 1);
                                   
                                    //try { var test = myPres.PresentationPart; }
                                    //catch (ObjectDisposedException)
                                    //{
                                    //    using (PresentationDocument myPres2 = PresentationDocument.Open(Server.MapPath("PowerPointTemplate/FAMBriefingNotes.pptx"), true))
                                    //    {
                                    //        SwapPlaceholderText(myPres2, current, "CurrUnitNotes", htmlCurrNotesDoc.DocumentNode.InnerHtml, true, i+1);
                                    //    }
                                    //}


                                    //Cleanup because ppt parses xml with or without tags in the same run for placeholders
                                    List<DocumentFormat.OpenXml.Drawing.Text> begTagList = newSldPart.Slide.Descendants<DocumentFormat.OpenXml.Drawing.Text>()
                                        .Where(t => t.Text.Contains("<#")).ToList();
                                    foreach (DocumentFormat.OpenXml.Drawing.Text text in begTagList)
                                        text.Text = "";
                                    List<DocumentFormat.OpenXml.Drawing.Text> endTagList = newSldPart.Slide.Descendants<DocumentFormat.OpenXml.Drawing.Text>()
                                        .Where(t => t.Text.Contains("#>")).ToList();
                                    foreach (DocumentFormat.OpenXml.Drawing.Text text in endTagList)
                                        text.Text = "";


                                }


                                //DeleteTemplateSlide(presPart, sectionSlidePart, "rId3");
                                //DeleteTemplateSlide(presPart, newSldPart, "tblPPTNotes");
                                DeleteTemplateSlide(presPart, sldPart, slidePartRelationshipID);  //delete template slide after records loop is done filling data
                            }
                        }
                    }
                    else
                    {
                        Response.Write("No rows found.");
                    }
                }
            }
        }


        static void SwapPlaceholderText(PresentationDocument pDoc, SlidePart slidePart, string placeholder, string value, bool outputXML, int cnt)
        {
            //bool blnThereIsNotes = false;


            //Slide slid = slidePart.Slide;
            //ShapeTree shpTree = slid
            //    .CommonSlideData
            //    .ShapeTree;


            //DocumentFormat.OpenXml.Presentation.GraphicFrame GF = shpTree.Elements<DocumentFormat.OpenXml.Presentation.GraphicFrame>().FirstOrDefault();
            //if (GF.NonVisualGraphicFrameProperties.OuterXml.Contains("PrevUnitNotes"))
            //{
            //     blnThereIsNotes = true; 
            //}


            if (!outputXML)
            {
                List<DocumentFormat.OpenXml.Drawing.Text> textList = slidePart.Slide.Descendants<DocumentFormat.OpenXml.Drawing.Text>()
                .Where(t => t.Text.Contains(placeholder)).ToList();


                foreach (DocumentFormat.OpenXml.Drawing.Text text in textList)
                    text.Text = value;
            }
            else if (placeholder == "PrevUnitNotes" ||  placeholder == "CurrUnitNotes")
            {
                using (pDoc)
                {
                    //var presAccess = pDoc.FileOpenAccess;
                Slide sld = slidePart.Slide;
                    
                var oleObject = sld.Descendants<OleObject>().FirstOrDefault();
                if (oleObject != null)
                {
                    var pp = pDoc.PresentationPart;
                    var sld1 = pp.Presentation.SlideIdList.ChildElements.OfType<SlideId>().FirstOrDefault();
                    var rid = sld1.RelationshipId.Value;
                    var sldPt = (SlidePart)pp.GetPartById(rid);


                    var oleRid = oleObject.Id.Value;
                    var embeddedPackagePart = (EmbeddedPackagePart)sldPt.GetPartById(oleRid);


                    XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
                    XNamespace r = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";


                    using(var stream = embeddedPackagePart.GetStream())
                    using (WordprocessingDocument wDoc = WordprocessingDocument.Open(stream, true))
                    {
                        var wpDocPart = wDoc.MainDocumentPart;
                        HtmlConverter converter = new HtmlConverter(wpDocPart);
                        Body bdy = wpDocPart.Document.Body;


                        string altChunkId = "AltChunkId" + cnt;
                        AlternativeFormatImportPart chunk = wpDocPart.AddAlternativeFormatImportPart("application/xhtml+xml", altChunkId);
                        using (Stream chunkStream = chunk.GetStream(FileMode.OpenOrCreate, FileAccess.ReadWrite))
                        using (StreamWriter stringStream = new StreamWriter(chunkStream))
                            stringStream.Write(value);
                        XElement altChunk = new XElement(w + "altChunk", new XAttribute(r + "id", altChunkId));
                        XDocument mainDocX = GetXDocument(wDoc);
                        mainDocX.Root
                            .Element(w + "body")
                            .Elements(w + "p")
                            .Last()
                            .AddAfterSelf(altChunk);


                        SaveXDocument(wDoc, mainDocX);
                    }
                }


                }
            }
        }


        private static void SaveXDocument(WordprocessingDocument myDoc, XDocument mainDocumentXDoc)
        {
            //Serialize the XDocument back into part
            using (Stream str = myDoc.MainDocumentPart.GetStream(FileMode.Create, FileAccess.Write))
            using (XmlWriter xw = XmlWriter.Create(str))
                mainDocumentXDoc.Save(xw);
        }


        private static XDocument GetXDocument(WordprocessingDocument myDoc)
        {
            //Load main Document part into an XDocument
            XDocument mainDocumentXDoc;
            using (Stream str = myDoc.MainDocumentPart.GetStream())
            using (XmlReader xr = XmlReader.Create(str))
                mainDocumentXDoc = XDocument.Load(xr);
            return mainDocumentXDoc;
        }


        static SlidePart CloneSlidePart(PresentationPart presentationPart, SlidePart slideTemplate)
        {
                SlidePart newSlidePart = presentationPart.AddNewPart<SlidePart>("newSlide" + index);
                index++;


                newSlidePart.FeedData(slideTemplate.GetStream(FileMode.Open));


                newSlidePart.AddPart(slideTemplate.SlideLayoutPart);


                SlideIdList slideIdList = presentationPart.Presentation.SlideIdList;


                uint maxSlideId = 1;
                SlideId prevSlideId = null;
                foreach (SlideId slideId in slideIdList.ChildElements)
                {
                    if (slideId.Id > maxSlideId)
                    {
                        maxSlideId = slideId.Id;
                        prevSlideId = slideId;
                    }
                }
                maxSlideId++;


                SlideId newSlideId = slideIdList.InsertAfter(new SlideId(), prevSlideId);


                newSlideId.Id = maxSlideId;
                newSlideId.RelationshipId = presentationPart.GetIdOfPart(newSlidePart);
                return newSlidePart;
        }


        static void DeleteTemplateSlide(PresentationPart presentationPart, SlidePart slideTemplate, string relId)
        {


            SlideIdList slideIdList = presentationPart.Presentation.SlideIdList;


            foreach (SlideId slideId in slideIdList.ChildElements)
            {
                if (slideId.RelationshipId.Value.Equals(relId))
                    slideIdList.RemoveChild(slideId);
            }


            presentationPart.DeletePart(slideTemplate);
        }


        static void CalculateImageEmus(Bitmap bitmap, out int widthInEmu, out int heightInEmu)
        {
            float verticalResolution = bitmap.VerticalResolution;
            float horizontalResolution = bitmap.HorizontalResolution;
            int width = bitmap.Size.Width;
            int height = bitmap.Size.Height;


            float widthInInches = (float)width / horizontalResolution;
            float heightInInches = (float)height / verticalResolution;


            widthInEmu = (int)(widthInInches * 914400);
            heightInEmu = (int)(heightInInches * 914400);
        }


    }
}

QuestionGoogle Speech Recognition Pin
Member 114365473-May-15 1:17
Member 114365473-May-15 1:17 
AnswerRe: Google Speech Recognition Pin
Richard MacCutchan3-May-15 2:14
mveRichard MacCutchan3-May-15 2:14 
GeneralRe: Google Speech Recognition Pin
Member 114365473-May-15 2:17
Member 114365473-May-15 2:17 
GeneralRe: Google Speech Recognition Pin
Richard MacCutchan3-May-15 2:24
mveRichard MacCutchan3-May-15 2:24 
GeneralRe: Google Speech Recognition Pin
Member 114365473-May-15 2:27
Member 114365473-May-15 2:27 
GeneralRe: Google Speech Recognition Pin
Sascha Lefèvre3-May-15 3:00
professionalSascha Lefèvre3-May-15 3:00 
GeneralRe: Google Speech Recognition Pin
Member 114365473-May-15 3:30
Member 114365473-May-15 3:30 
GeneralRe: Google Speech Recognition Pin
OriginalGriff3-May-15 3:53
mveOriginalGriff3-May-15 3:53 
GeneralRe: Google Speech Recognition Pin
Member 114365473-May-15 4:06
Member 114365473-May-15 4:06 
GeneralRe: Google Speech Recognition Pin
OriginalGriff3-May-15 4:17
mveOriginalGriff3-May-15 4:17 
GeneralRe: Google Speech Recognition Pin
Member 114365473-May-15 4:29
Member 114365473-May-15 4:29 
GeneralRe: Google Speech Recognition Pin
OriginalGriff3-May-15 4:46
mveOriginalGriff3-May-15 4:46 
GeneralRe: Google Speech Recognition Pin
Gerry Schmitz3-May-15 10:45
mveGerry Schmitz3-May-15 10:45 
Questioncode dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString() doesnt work Pin
aahamdan2-May-15 6:24
aahamdan2-May-15 6:24 
AnswerRe: code dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString() doesnt work Pin
OriginalGriff2-May-15 6:39
mveOriginalGriff2-May-15 6:39 
GeneralRe: code dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString() doesnt work Pin
aahamdan2-May-15 6:48
aahamdan2-May-15 6:48 
GeneralRe: code dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString() doesnt work Pin
OriginalGriff2-May-15 7:18
mveOriginalGriff2-May-15 7:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.