Quantcast
Channel: WordprocessingML - Recent Threads
Viewing all 1417 articles
Browse latest View live

How to convert the track changes into custom xml tags using word 2007 open xml.

$
0
0

I need to convert the each track changes into custom xml tags(like insert, delete tags), without opening the document.

 

could you help in this regards.

 

Regards,

Kavin.


How to find tables and add data to them in open xml ?

$
0
0

Hi all. 

I am new to open XML, and looking for some tips, and found this site. I am currently working on a SharePoint project where we will generate documents using Open XML. I have stumbled on 2 issues which I am hoping to get some help with:

1. When text with multiple lines is inserted inside content controls  in the generated .docx - document, it is inserted with HTML - formatting, i.e <p>some text</p><p>More text</p>. Can text like this somehow get cast to something open XML documents will understand ? 

2. In the generated documents we are using tables. We are going to retrieve data from lists in SharePoint and present the data in tables in the generated document . I found this link doing something like we want to do, http://ericwhite.com/blog/2011/03/27/replacing-a-picture-in-a-picture-content-control-in-an-open-xml-wordprocessingml-document/, but this is an old post and the code looks awfully long and complex. Is there an easier way to find tables and insert data in them ? 

Thanks. 

After inserting an image in a .docx file, the docx file ask for being repaired

$
0
0

I integrated a script for the find and replace function, with the microsoft script for inserting an image, the problem is that i get an error when i load the file with microsoft word, after i repair the document the document looks with all the images in the right places, bit i need to remove the error message.

this is the code that i'm using:

 

 public static void openxml_replace_text_with_image(string document, string oldText, string imageUrl)//version 2
          {
            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
                {
                Console.WriteLine("Loaded: " + document);
                OpenXmlElement BODY = wordDoc.MainDocumentPart.Document.Body;
                /// image added to the collection <---------------------------------------------------------------------------


               
            // this is a quite smart and simple algorithm by Shimon Doodkin
            // the idea is to concat all texts and search it as string.
            // then replace text by positions step by step
            string to = "  ";
            StringBuilder innertext = new StringBuilder(); foreach (Text eltext in BODY.Descendants<Text>()) { innertext.Append(eltext.Text); } // maybe to add space if previous element had no space at the end and this element has no space at beggining or add new line...no... but this problem is only with tables..
            string innertextstr = innertext.ToString();
            List<int> foundat = AllIndexesOf(innertextstr, oldText);
            List<int> foundatend = new List<int>();
            for (int z = 0; z < foundat.Count; z++)
            {
                foundatend.Add(foundat[z] + oldText.Length - 1);
            }
            List<Text> tofixnewlines = new List<Text>();
            List<Text> todeleteempty = new List<Text>();
            List<string> tofixnewlines_str = new List<string>();
            int currenttext_from = 0, currenttext_to = -1;
            int innertextpos = 0;
            Boolean trovato = false;
            OpenXmlElement parentRUN=null;
            if (foundat.Count != 0)
            {
                foreach (Text eltext in BODY.Descendants<Text>())
                {

                    currenttext_from = currenttext_to + 1;
                    currenttext_to += eltext.Text.Length;
                    //Console.WriteLine("currenttext_from: " + currenttext_from + " currenttext_to: " + currenttext_to);
                    if (foundat.Count == 0) break;
                    if (foundat.First() <= currenttext_from && currenttext_from <= foundatend.First() // the beggining of this block is inside a found
                         || foundat.First() <= currenttext_to && currenttext_to <= foundatend.First() // the end of this block is inside a found
                         || currenttext_to <= foundat.First() && foundatend.First() <= currenttext_to // found is inside block
                        )
                    {
                        //Console.WriteLine("#"+eltext.OuterXml);
                        StringBuilder newtext = new StringBuilder();
                        //is innertextpos in a match?
                        innertextpos = currenttext_from;
                        for (int curchar = 0; curchar < eltext.Text.Length; curchar++)
                        {
                            if (foundat.Count == 0) break;
                            if (innertextpos == foundat.First())
                            {
                                ////////////////////////////////////////////////////////////////////////////////////////////////////TROVATO
                                newtext.Append(to);
                                Console.WriteLine("eltext.Parent è un :" + eltext.Parent.ToString()) ;
                                Console.WriteLine(eltext.Parent.InnerXml);
                                trovato = true;
                                parentRUN = eltext.Parent;
                            }
                            else if (innertextpos >= foundat.First() && innertextpos <= foundatend.First())
                            {
                                int replacewithcharat = innertextpos - foundat.First();
                                //newtext.Append(to[replacewithcharat]);
                                if (innertextpos == foundatend.First())
                                {
                                    //if (replacewithcharat < to.Length)
                                    //{
                                    //newtext.Append(to.Substring(replacewithcharat + 1));
                                    //}
                                    //append add rest;
                                    foundat.RemoveAt(0);
                                    foundatend.RemoveAt(0);
                                }
                            }
                            else
                                newtext.Append(eltext.Text[curchar]);
                            innertextpos++;
                        }
                        string newtextstr = newtext.ToString();

                        if (newtextstr.IndexOf('\n') == -1)
                            eltext.Text = newtextstr;
                        else
                        {
                            eltext.Text = "to be replaced";
                            tofixnewlines.Add(eltext);
                            tofixnewlines_str.Add(newtextstr);
                        }

                        if (newtextstr.Length == 0)
                        {
                            todeleteempty.Add(eltext);
                        }
                       
                    }
                   
                }
                for (int i = 0; i < tofixnewlines.Count; i++)
                {
                    string[] lines = tofixnewlines_str[i].Replace("\r", "").Split('\n');
                    Text last_el = tofixnewlines[i];
                    OpenXmlElement newline_el;
                    OpenXmlElement copy_el;
                    last_el.Text = lines[0];
                    Text next_el;
                    for (int j = 1; j < lines.Length; j++)
                    {
                        //create nextline text
                        copy_el = last_el.Parent.CloneNode(true);
                        next_el = copy_el.Descendants<Text>().First();
                        next_el.Text = lines[j];

                        //create newline  //"<w:r><w:rPr><w:rFonts w:hint="cs" /><w:rtl /></w:rPr><w:br /></w:r>"
                        newline_el = last_el.Parent.CloneNode(true);
                        IEnumerable<OpenXmlElement> se = newline_el.ChildElements.Where(e => e.LocalName != "rPr");
                        foreach (OpenXmlElement item in se) item.Remove();
                        newline_el.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Break());//<w:br />


                        last_el.Parent.InsertAfterSelf(copy_el);
                        last_el.Parent.InsertAfterSelf(newline_el);//add a newline after the last_el.Parent(the add order is switched,i always add after the first element but in reverse order)

                        last_el = next_el;

                    }
                }

                for (int i = 0; i < todeleteempty.Count; i++)
                {
                    Text eltext = todeleteempty[i];
                    //if (eltext.Parent.ChildElements.Count <= 2 && newtextstr.Length == 0)// run.childern<=2 means Run countains the only w:rPr and w:t or just w:t
                    //  {
                    eltext.Parent.Remove();//remove empty run,not sure if this is good, i dont know mybe run could countain other elements besides text like images.
                    // }
                }
                if (trovato)
                {
                    /// insert image in the database <--------------------

                    string imageID = oldText.Replace("{", "_").Replace("}", "_");
                    MainDocumentPart mainPart = wordDoc.MainDocumentPart; 
                    ///%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                    ///%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                    Uri imageUri = new Uri("/word/media/" +System.IO.Path.GetFileName(imageUrl), UriKind.Relative);
                    PackagePart packageImagePart = wordDoc.Package.CreatePart(imageUri, "Image/jpeg");

                    // Feed data.
                    byte[] imageBytes = File.ReadAllBytes(imageUrl);
                    packageImagePart.GetStream().Write(imageBytes, 0, imageBytes.Length);

                    PackagePart documentPackagePart =
                      mainPart.OpenXmlPackage.Package.GetPart(new Uri("/word/document.xml", UriKind.Relative));

                    Console.Out.WriteLine(documentPackagePart.Uri);

                    // URI to the image is relative to releationship document.
                    PackageRelationship imageReleationshipPart = documentPackagePart.CreateRelationship(
                          new Uri("media/" + System.IO.Path.GetFileName(imageUrl), UriKind.Relative),
                          TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image");
                    ///%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                    ///%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                            UInt32Value contatore=Convert.ToUInt32( mainPart.GetPartsCountOfType<ImagePart>());
                             contatore++;
                             /*         ImagePart imagePart1 = mainPart.AddImagePart(ImagePartType.Jpeg, imageID);
                                      using (FileStream stream = new FileStream(imageUrl, FileMode.Open))
                                      {
                                          imagePart1.FeedData(stream);
                                      }
                                      AddImageToBody(parentRUN, imageID, contatore);
                              //*/
                             AddImageToBody(parentRUN, imageReleationshipPart.Id, contatore);

                            
                    //
                    //(new Run(imageXml));


                }
            }
        }
}

    

        private static void AddImageToBody(OpenXmlElement EL, string imageID, UInt32Value contatore)
        {
            // Define the reference of the image.
            var element =
                 new Drawing(
                     new DW.Inline(
                         new DW.Extent() { Cx = 990000L, Cy = 792000L },
                         new DW.EffectExtent()
                         {
                             LeftEdge = 0L,
                             TopEdge = 0L,
                             RightEdge = 0L,
                             BottomEdge = 0L
                         },
                         new DW.DocProperties()
                         {
                             Id = contatore,
                             Name = "picture"
                         },
                         new DW.NonVisualGraphicFrameDrawingProperties(
                             new A.GraphicFrameLocks() { NoChangeAspect = false }),
                         new A.Graphic(
                             new A.GraphicData(
                                 new PIC.Picture(
                                     new PIC.NonVisualPictureProperties(
                                         new PIC.NonVisualDrawingProperties()
                                         {
                                             Id = (UInt32Value)0U,
                                             Name = "New Bitmap Image.jpg"
                                         },
                                         new PIC.NonVisualPictureDrawingProperties()),
                                     new PIC.BlipFill(
                                         new A.Blip(
                                             new A.BlipExtensionList(
                                                 new A.BlipExtension()
                                                 {
                                                     Uri ="{28A0092B-C50C-407E-A947-70E740481C1C}"
                                                 })
                                         )
                                         {
                                             Embed = imageID,
                                             CompressionState =
                                             A.BlipCompressionValues.Print
                                         },
                                         new A.Stretch(
                                             new A.FillRectangle())),
                                     new PIC.ShapeProperties(
                                         new A.Transform2D(
                                             new A.Offset() { X = 0L, Y = 0L },
                                             new A.Extents() { Cx = 990000L, Cy = 792000L }),
                                         new A.PresetGeometry(
                                             new A.AdjustValueList()
                                         ) { Preset = A.ShapeTypeValues.Rectangle }))
                             ) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
                     )
                     {
                         DistanceFromTop = (UInt32Value)0U,
                         DistanceFromBottom = (UInt32Value)0U,
                         DistanceFromLeft = (UInt32Value)0U,
                         DistanceFromRight = (UInt32Value)0U,
                         EditId = "50D07946"
                     });

            // Append the reference to body, the element should be in a Run.
           // text =new Paragraph(new Run(element));
            Console.WriteLine("");
            Console.WriteLine(EL.ToString());
            Console.WriteLine("");

            EL.AppendChild(element);
            
        }
   
        //------------------------------------------------------------------------------------------------------

        
        public static List<int> AllIndexesOf(string str, string substr, bool ignoreCase = false) // modified of http://stackoverflow.com/a/14308894/466363
        {
            var indexes = new List<int>();
            if (string.IsNullOrWhiteSpace(str) ||
                string.IsNullOrWhiteSpace(substr))
            {
                return indexes;
            }


            int index = 0;

            while ((index = str.IndexOf(substr, index, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) != -1)
            {
                indexes.Add(index++);
            }

            return indexes;
        }

        public static void openxml_replace_text(OpenXmlElement el, string from, string to)//version 2
        {
            // this is a quite smart and simple algorithm by Shimon Doodkin
            // the idea is to concat all texts and search it as string.
            // then replace text by positions step by step

            StringBuilder innertext = new StringBuilder(); foreach (Text eltext in el.Descendants<Text>()) { innertext.Append(eltext.Text); } // maybe to add space if previous element had no space at the end and this element has no space at beggining or add new line...no... but this problem is only with tables..
            string innertextstr = innertext.ToString();
            List<int> foundat = AllIndexesOf(innertextstr, from);
            List<int> foundatend = new List<int>();
            for (int z = 0; z < foundat.Count; z++)
            {
                foundatend.Add(foundat[z] + from.Length - 1);
            }
            List<Text> tofixnewlines = new List<Text>();
            List<Text> todeleteempty = new List<Text>();
            List<string> tofixnewlines_str = new List<string>();
            int currenttext_from = 0, currenttext_to = -1;
            int innertextpos = 0;
            if (foundat.Count != 0)
            {
                foreach (Text eltext in el.Descendants<Text>())
                {

                    currenttext_from = currenttext_to + 1;
                    currenttext_to += eltext.Text.Length;
                    //Console.WriteLine("currenttext_from: " + currenttext_from + " currenttext_to: " + currenttext_to);
                    if (foundat.Count == 0) break;
                    if (foundat.First() <= currenttext_from && currenttext_from <= foundatend.First() // the beggining of this block is inside a found
                         || foundat.First() <= currenttext_to && currenttext_to <= foundatend.First() // the end of this block is inside a found
                         || currenttext_to <= foundat.First() && foundatend.First() <= currenttext_to // found is inside block
                        )
                    {
                        //Console.WriteLine("#"+eltext.OuterXml);
                        StringBuilder newtext = new StringBuilder();
                        //is innertextpos in a match?
                        innertextpos = currenttext_from;
                        for (int curchar = 0; curchar < eltext.Text.Length; curchar++)
                        {
                            if (foundat.Count == 0) break;
                            if (innertextpos == foundat.First())
                            {
                                newtext.Append(to);
                            }
                            else if (innertextpos >= foundat.First() && innertextpos <= foundatend.First())
                            {
                                int replacewithcharat = innertextpos - foundat.First();
                                //newtext.Append(to[replacewithcharat]);
                                if (innertextpos == foundatend.First())
                                {
                                    //if (replacewithcharat < to.Length)
                                    //{
                                    //newtext.Append(to.Substring(replacewithcharat + 1));
                                    //}
                                    //append add rest;
                                    foundat.RemoveAt(0);
                                    foundatend.RemoveAt(0);
                                }
                            }
                            else
                                newtext.Append(eltext.Text[curchar]);
                            innertextpos++;
                        }
                        string newtextstr = newtext.ToString();

                        if (newtextstr.IndexOf('\n') == -1)
                            eltext.Text = newtextstr;
                        else
                        {
                            eltext.Text = "to be replaced";
                            tofixnewlines.Add(eltext);
                            tofixnewlines_str.Add(newtextstr);
                        }

                        if (newtextstr.Length == 0)
                        {
                            todeleteempty.Add(eltext);
                        }
                    }
                }
                for (int i = 0; i < tofixnewlines.Count; i++)
                {
                    string[] lines = tofixnewlines_str[i].Replace("\r", "").Split('\n');
                    Text last_el = tofixnewlines[i];
                    OpenXmlElement newline_el;
                    OpenXmlElement copy_el;
                    last_el.Text = lines[0];
                    Text next_el;
                    for (int j = 1; j < lines.Length; j++)
                    {
                        //create nextline text
                        copy_el = last_el.Parent.CloneNode(true);
                        next_el = copy_el.Descendants<Text>().First();
                        next_el.Text = lines[j];

                        //create newline  //"<w:r><w:rPr><w:rFonts w:hint="cs" /><w:rtl /></w:rPr><w:br /></w:r>"
                        newline_el = last_el.Parent.CloneNode(true);
                        IEnumerable<OpenXmlElement> se = newline_el.ChildElements.Where(e => e.LocalName != "rPr");
                        foreach (OpenXmlElement item in se) item.Remove();
                        newline_el.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Break());//<w:br />


                        last_el.Parent.InsertAfterSelf(copy_el);
                        last_el.Parent.InsertAfterSelf(newline_el);//add a newline after the last_el.Parent(the add order is switched,i always add after the first element but in reverse order)

                        last_el = next_el;

                    }
                }

                for (int i = 0; i < todeleteempty.Count; i++)
                {
                    Text eltext = todeleteempty[i];
                    //if (eltext.Parent.ChildElements.Count <= 2 && newtextstr.Length == 0)// run.childern<=2 means Run countains the only w:rPr and w:t or just w:t
                    //  {
                    eltext.Parent.Remove();//remove empty run,not sure if this is good, i dont know mybe run could countain other elements besides text like images.
                    // }
                }
            }
        }

    
    
    }
}

 

When i analyze the file with the openxml tool it founds 0 errors

i forgot to mention that the text that needs to be replaced is inside textbox tables and so on.

 

EDIT: i found the solution, conflicting images in the header/footer, setted the "contatore" at 100 and it works :)

OPENXML Word JustificationValues.Both blank problem

$
0
0

I'm create a word document with OpenXML. I try to add paragraph as JustificationValues.Both but when i styled it occure to many blanks in line.

When I press enter it solved. So what can i fixed it with code?

Here is my code :

private void CreateParagraph(string str,string location, string insertLocation, Methods.StyleType style)
{
	try
	{
		Paragraph par = new Paragraph(new ParagraphProperties());
		par.ParagraphProperties.TextAlignment = new TextAlignment();
		par.ParagraphProperties.TextAlignment.Val = VerticalTextAlignmentValues.Top;
		par.ParagraphProperties.Justification = new Justification();
		if (style == Methods.StyleType.Both)
			{
			par.ParagraphProperties.Justification.Val = JustificationValues.Both;
			par.ParagraphProperties.Indentation = new Indentation();
			par.ParagraphProperties.Indentation.FirstLine = "400";
		}
		else
			par.ParagraphProperties.Justification.Val = JustificationValues.Left;
        par.ParagraphProperties.SpacingBetweenLines = new SpacingBetweenLines()
		{
			After = "100",
			Line = "350",
			LineRule = LineSpacingRuleValues.AtLeast
		};
        Run run = new Run(new Text(str));
		par.Append(run);
		AddParagraphAfterBookmark(location, par, insertLocation);
		par.InsertAfterSelf(new Paragraph(new Run(new Break())));
	}
	catch (Exception ex)
	{
		Log.Write(LogType.Error, System.Reflection.MethodBase.GetCurrentMethod().Name, ex, -1, this.GetType().Name);
	}
}

Here is my text :

İşletme sınırları içerisinde imalat, depolama ve yardımcı işlemelerin yer aldığı 5 adet tesise sahiptir.

And It appear in the word :

İşletme          sınırları içerisinde imalat, depolama ve        yardımcı           işlemelerin yer        aldığı           5          adet             tesise         sahiptir.

 

Get all paragraphs between two tables?

$
0
0

Hi there,

I have a Word document with x tables and I would like to be able to get all paragraphs between the tables.

Is this posibble with open XML?

Best regards
Martin

Validating a Microsoft Word 2010 Document using OPEN XML or XSD

$
0
0

Hi,

We want to validate a word 2010 document.We have a High Level Design document template.All the application teams will use the same template for their projects.

Users can edit the whole document.We don't want to protect the document.This is the High Level Design Document(HLD).They can add their project details in the template that we provide.

But we want to validate the document to see whether they are removing any sections.For example the template is having 12 sections like Software architecture diagram,Common Infrastructure design guidelines,Deployment guidelines etc.If they remove any sections in their application high level design document by thinking that they don't need this section then we need to validate the document and giving error so that everybody is strictly following the template that we provide.

I just looked into the below mentioned blog which is there for Microsoft Word 2003.I am not sure whether we can take the document.xml file in the word folder and convert it to XSD and validate the document using the steps mentioned in the below mentioned blog.

https://msdn.microsoft.com/en-us/library/office/ee364552(v=office.11).aspx

Please help.

 

Problem about page x of y values in .docx file

$
0
0

Hello everybody.
I am searching for a way to have correct "page x of y" values in .docx file, which will be generated server-side without interaction with MS Office. The language to generate will be Python, using Office SDK is not in my plans (xml parts will be filled with data from database like templates and then assembled into package).
My research for a way to implement "page x of y" has failed so far, and I ask now for your wisdom how can it be done (or it cannot be done and the idea must be dropped).
As far as I know calculating page number and count of total pages is a function of MS Word application only (please correct me if I'm wrong), so I am trying to find a solution where correct "page x of y" will be calculated at the moment when the generated document is opened in Word.
So far I have tried to place in document.xml instruction fields with "dirty" values:

<w:sdt>
 
<w:sdtPr>
   
<w:idw:val="250395305"/>
   
<w:docPartObj>
     
<w:docPartGalleryw:val="Page Numbers (Top of Page)"/>
     
<w:docPartUnique/>
   
</w:docPartObj>
 
</w:sdtPr>
 
<w:sdtContent>
   
<w:pw:rsidR="005122CB"w:rsidRDefault="005122CB">
     
<w:r>
       
<w:txml:space="preserve">Page </w:t>
     
</w:r>
     
<w:fldSimplew:instr=" PAGE "w:dirty="true">
       
<w:r>
         
<w:rPr>
           
<w:noProof/>
         
</w:rPr>
         
<w:t>1</w:t>
       
</w:r>
     
</w:fldSimple>
     
<w:r>
       
<w:txml:space="preserve">of </w:t>
     
</w:r>
     
<w:fldSimplew:instr=" NUMPAGES "w:dirty="true">
       
<w:r>
         
<w:rPr>
           
<w:noProof/>
         
</w:rPr>
         
<w:t>2</w:t>
       
</w:r>
     
</w:fldSimple>
   
</w:p>
 
</w:sdtContent>
</w:sdt>

 

And to set updateFields value in settings.xml:
 
<w:updateFields w:value="true"/> 
In both cases when the document is opened in Word 2007, I do not have correct "page x of y".
Is it possible to implement a solution where dynamically generated word document will have "page x of y"?

author: internet việt nam

Ads: FPT Hải Phòng thực hiện lắp đặt dịch vụ cho khách hàng theo đúng cam kết, thời gian được tính từ lúc khách hàng làm hợp đồng và thanh toán phí lắp mạng fpt hải phònglắp mạng fpt hoài đứclắp mạng fpt biên hòa và được tính theo giờ hành chánh, nếu sau 16 giờ thì tính là 8 giờ ngày hôm sau.

Trong các gói cước dịch vụ internet fpt của chúng tôi.
Khi triển khai lắp đặt dịch vụ lắp mạng fpt đà lạtlắp mạng fpt đống đalắp mạng fpt hải dương, FPT Hải Phòng lắp đặt đường cáp đồng, cáp quang tại địa chỉ khách hàng để đến được máy tính sử dụng (đi dây trần). Quý khách phải thanh toán các chi phí phát sinh nếu có yêu cầu khác.

Question about SaveAs option in VC++

$
0
0

Hello everybody.

I am working  on module to convert Doc/Docx to word 2003 XML document using c++..But i had great problem writing native c++ code for conversion process..I had come across interop assemblies which easy the process instead of writing prolonged code..But interop assemblies have support to .NET and C#..i have seen so many examples which have implemented this task using c#..is there any existing examples in C++ to implement this task??..This is my sample code..please correct it..i am not getting proper output:

void SaveXml();
    {
        String fn = @"C:\Users\zbook\Desktop\Track test.docx";
        String fn_xml = @"C:\Users\zbook\Desktop\Track test3.xml";
        Microsoft::Office::Interop::Word::Application app = new Microsoft::Office::Interop::Word:: Application();
        Word::Documents docs = app->Documents;
        Word::Document doc = docs->Open(fn, ReadOnly:true);
        //bool b = doc.TrackFormatting; // for some reason this line bombs
        doc->SaveAs2(fn_xml, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXML);
        doc->Close(false);
        Marshal->ReleaseComObject(doc);

        // now open up fn_xml ... and do whatever

        app->Quit(false);
        Marshal->ReleaseComObject(docs);
        Marshal->ReleaseComObject(app);

    }

 

Ads: Khi lắp đặt dịch vụ, Kỹ Thuật viên của công ty sẽ lắp đặt miễn phí cho 1 máy tính của khách hàng kết nối vào mạng Internet. Nếu khách hàng có yêu cầu lắp mạng fpt vĩnh longlắp mạng fpt hòa bìnhlắp mạng fpt quận 12 với nhiều máy (hoặc cả mạng LAN) xin vui lòng liên hệ kỹ thuật bên ngoài, hiện tại chúng tôi chưa có chính sách hỗ trợ khách hàng.
.FPT mong muốn trở thành một tổ chức kiểu mới, giàu mạnh bằng nỗ lực lao động sáng tạo trong dịch vụ đăng ký truyền hình fptlắp mạng fpt thanh hóalắp mạng fpt ba đình khoa học kỹ thuật và công nghệ, làm khách hàng hài lòng.

góp phần hưng thịnh quốc gia, đem lại cho mỗi khach hàng đăng ký internet cáp quang của mình điều kiện phát triển tốt nhất tài năng và một cuộc sống đầy đủ về vật chất, phong phú về tinh thần.


How to add CRLF to generated Word .docx from code?

$
0
0

The project has content controls put into a template .docx that is opened, converted to byte[]

 public static IEnumerable<OpenXmlElement> ContentControls(
            this OpenXmlPart part)
        {
            return part.RootElement
                .Descendants()
                .Where(e => e is SdtBlock || e is SdtRun || e is SdtCell);
        }

        public static IEnumerable<OpenXmlElement> ContentControls(
            this WordprocessingDocument doc)
        {
            foreach (var cc in doc.MainDocumentPart.ContentControls())
                yield return cc;
            //foreach (var header in doc.MainDocumentPart.Pa)
            //    foreach (var cc in header.ContentControls())
            //        yield return cc;
            //foreach (var footer in doc.MainDocumentPart.FooterParts)
            //    foreach (var cc in footer.ContentControls())
            //        yield return cc;
            //if (doc.MainDocumentPart.FootnotesPart != null)
            //    foreach (var cc in doc.MainDocumentPart.FootnotesPart.ContentControls())
            //        yield return cc;
            //if (doc.MainDocumentPart.EndnotesPart != null)
            //    foreach (var cc in doc.MainDocumentPart.EndnotesPart.ContentControls())
            //        yield return cc;
        }


 byte[] byteArray = System.IO.File.ReadAllBytes(fileName);
            using (MemoryStream mem = new MemoryStream())
            {
                mem.Write(byteArray, 0, (int)byteArray.Length);
                using (WordprocessingDocument wordDoc =
                    WordprocessingDocument.Open(mem, true))
                {
                    MainDocumentPart mainDoc = wordDoc.MainDocumentPart;
                    Body bodyDoc = mainDoc.Document.Body;
                    foreach (var cc in wordDoc.ContentControls())
                    {
                        SdtProperties props = cc.Elements<SdtProperties>().FirstOrDefault();
                        Tag tag = props.Elements<Tag>().FirstOrDefault();
                       // richTextBox1.Text += "new data is: " + tag.Val + "\n";
                        dat1 = tag.Val.ToString();
                     switch  (dat1)
                     {
                         case "CustName":
                             cc.Descendants<Text>().First().Text = Custdb.cName;
                             break;
                           case "CustType":
                             cc.Descendants<Text>().First().Text = "\n\r"+ Custdb.cType;
                            cc.Descendants<Run>().First().InsertAfterSelf(new Break());  <==
                             break;


on and on.  it builds the doc and saves it.   what it CANNOT DO is have word see the CRLF, it will not do a linefeed

in the openxml productivity tool its showing the inserted <br /> in there.  Word?  rejects these, the sentences run together.

I have been searching and searching and trying different things to do this simple task.  

 

the resulting code must have a sentence, when i add in the ??? for telling to do a carriage return thats what I expect to happen in word.  i have to have an adjustable document, some reports will have 10 sentences, others 3.  in NONE of the videos or blogs or ? that Eric or anyone has done, have i found anything related to doing this.  

 

 

 

 

Checking the Content Control Type and Value for the particular Content Control Type in Word 2010 Document

$
0
0

Hi,

I want to iterate all the content controls in Microsoft Word 2010 document using OPENXML.I have Checkbox,RichTextBox and Plain Text Box Content Controls in my document.

For example

All the headings(Heading 1, Heading 2, Heading 3 etc.) in my Word document are of Rich Text Box Content Control.

I have several sections like Technology Used, Web Server requirements etc. in my document with Check Box Content Control Types in it.

Technology Used:

ASP.NET (Check Box Content Control Type),MVC(Check Box Content Control Type), JavaScript(Check Box Content Control Type)) etc.

I need to read the values of anyone of the Check Box content control type in the section named Technology Used that is checked by the user.Otherwise i need give error for the validation that we are doing.

The below mentioned blog is iterating all the content control values using Tag values.Is there a way to check the Content Control Type and the Check Box content control type is checked or not.

http://openxmldeveloper.org/blog/b/openxmldeveloper/archive/2011/04/11/137383.aspx

Please help.

 

Showing HTML in Rich Content Control.

$
0
0

Hello,

Apologies for a long write-up.

I am currently working on a project using XML based Content Control approach, where I have a template with Rich Text Content Controls and using XPath, I am generating the document based on the XML generated from the DB.

Everything works fine for Text, Tables, etc. However, the "Product Description" field has HTML and that's where I am running into issues. Currently, the Word (.docx) output file has HTML as embedded (Example: <h1>HELLO</h1>). I would like the final output to actually recognize HTML as HTML and not Text.

Another method I tried was using ALtChunk & formatImportPart but then XPath based approach stopped working.

Any ideas of how to get the two approaches working together in one solution.

How to parse raw HTML text to Word format using OpenXML?

$
0
0

Hello,

Fairly new to using OpenXML. I have a site which uses a rich-text editor (ckeditor IIRC), which outputs text into it as raw HTML data. Sample is below of a simple text with an inline-image:

 

<p>PHD Abstract</p><p><strong>Title</strong></p><ul><li>Item 1</li><li>Item 2</li></ul><p><img alt="" border="0" hspace="0" src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxASEBAUDxQWDxQQFRAQFRAPEA8QFBAPFBQWFhQXFBQYHCggGBolHBQYITEhJSkrLi4uGB8zODMsNygtMCsBCgoKDg0OGhAQGCwcHB8sLCwsLCwsLCssLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCs3LCsrK//AABEIAK4BIgMBIgACEQEDEQH/xAAbAAACAwEBAQAAAAAAAAAAAAAAAQIDBAUGB//EADoQAAEDAwIDB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GE5dKW36aWtbYgb4i+TaM9f5dOjTaS6o+xiQ1p27nHFxiI5LHp9Q4FsWDgfcHjPkrKeou7dJsDY8z1TtO20OJkAQRuHicAIi8k9AokC/S8fNbF/VZ9Jrt2+0yDMk8Qp1qhLXR81rzmTBB/nBTrS0rRqajCQC37+4cfEOcXgXMLBVYzcXVHF5YDYfKL2PpN7XHkmyvAaXiZAiDg85VrKLS2GgA2eXcSSceSXcW5biupVMi20QcbXtIjcT7D6Qojd8r7mC7adoAZEmeXD2Vwe4fKYm3qf2gSp0m73OmHQMuAnxSLfmpit7Z2AlhAAfPI7S0CIAnPESrNDQf4gIlplvisHDAA4ym522bAukNdwDg75fUEZUqeumQABHQCRm6mZ6q0sW6jYXbnmH23Q3wg/wBtrHqqqVHcJu1pue82kRaOXms51rw7nFyCZGPJZv8AuFTxBsAWF28vywou6rydGpTLvmbaQYDYw3AibXWd1MCQ1sSB4SSL3WLU6irudLsQDmJjkqaXaJ2h5EknZfgenunHJnc5tt1dBoIB8NgLZOZAOeKzmg4knhixaSB7qRq7oJnA4m3ks2tc5gaWHNnSXSZE8/RWx3elcjbonQPE33H6oVQc7kPc/ohW/sjp/9k=" style="border:0px solid black; height:174px; margin-bottom:0px; margin-left:0px; margin-right:0px; margin-top:0px; width:290px" vspace="0" /></p>

I store the data above in a DB for various purposes, mainly 1.) loading it back to display and 2.) generating some word documents. I currently have a library grabbed from the internet for HTML to OpenXML calledHTML2OpenXML.

The problem is, the current library I am using cannot parse the stored data completely (simplest example is the image is not displayed, as well as bulleted items).

Is there a recommended way of parsing HTML back to Open XML? ckeditor can already do the reverse (you copy-paste data from Word to the ckeditor text-area on the browser).

Thank you! 



How to control .rels / Relationship / Id ?

$
0
0

I'm writing some unit tests of my OpenXML SDK code for our continuous integration build. I need to do a binary file compare of the output across runs.

So I ran the tiny example docx OpenXML SDK code from this URL twice.

https://msdn.microsoft.com/en-us/library/dd440953(v=office.12).aspx
There's a difference in the .rels / Relationships / Relationship / Id. The first time it's R0632e32242c64585 and the second time it's Re3cc37e9c491418a. (Example below)

So of course my binary compare fails. How can I control this value?

 

Howard Rubin


<?xml version="1.0" encoding="utf-8" ?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="/word/document.xml" Id="R0632e32242c64585"/></Relationships>

Docx to html XSLT stylesheet

$
0
0

Dear community

I have started an project which aim to create as good as it can be transform from docx to html with XSLT stylesheet. It can be found from github, please see docx to html project.

I already contributed almost thousand lines to project, and I am very proud of some features which I havent seen in similar project, such as pages, tabs and real lists.

You are free to contribute, test or comment my project.

Transforming WordPRocessingML to simpler XML based on headings hierarchy

$
0
0

I have transformed the wordprocessingML to simpler xml and i want to validate the generated XML with XSD.

http://blogs.msdn.com/b/ericwhite/archive/2010/03/01/transforming-wordprocessingml-to-simpler-xml-for-easier-processing.aspx

But i want to generate the XML based on the Headings hierarachy in the word document.I have attached the xsd that i am going to use for validating the sample xml which is mentioned below.

i have modified the code inside the TransformXML method.How can create the XML based on <Heading 1><Heading2><Heading3></Heading3></Heading2></Heading1> 

 public object TransformToSimpleXml(XNode node, string defaultParagraphStyleId)    {        //DQ stands for Design Quality
        XElement element = node as XElement;        if (element != null)        {            if (element.Name == W.document)            {                return new XElement(DQ + "document",                        new XAttribute(XNamespace.Xmlns + "DQ", DQ),                        element.Element(W.body).Elements()                            .Select(e => TransformToSimpleXml(e, defaultParagraphStyleId)));            }            //Iterating Paragrpah            if (element.Name == W.p)            {                string styleId = (string)element.Elements(W.pPr)                    .Elements(W.pStyle).Attributes(W.val).FirstOrDefault();
                //if ((styleId != null) && (styleId == "Heading1") || ((styleId == "Heading2") || ((styleId == "Heading3") || ((styleId == "Heading4") || (styleId == "Heading5")))))                //{                //    string xmlElement = element.LogicalChildrenContent(W.r).Elements(W.t).Select(t => (string)t)                //            .StringConcatenate().Trim();
                //    if (styleId == null)                //    {                //        styleId = defaultParagraphStyleId;                //    }                //    if (!string.IsNullOrEmpty(xmlElement))                //    {                //        //removing spaces between XML Elements                //        xmlElement = xmlElement.Replace(" ", string.Empty);
                //        //removing Special Characters in XML Elements                //        xmlElement = RemoveSpecialCharacters(xmlElement);
                //        if ((xmlElement != null) && (xmlElement != string.Empty))                //        {                //            return new XElement(DQ + xmlElement,                //                        new XAttribute("style", styleId),                //            element.LogicalChildrenContent(W.r).Elements(W.t).Select(t => (string)t)                //                .StringConcatenate());
                //        }                //    }                if ((styleId != null) && (styleId == "Heading1"))                {                    return GetXElementValue(node, styleId);                 }                else if ((styleId != null) && (styleId == "Heading2"))                {                    return GetXElementValue(node, defaultParagraphStyleId, styleId);                }                else if ((styleId != null) && (styleId == "Heading3"))                {                    return GetXElementValue(node, defaultParagraphStyleId, styleId);                }                else if ((styleId != null) && (styleId == "Heading4"))                {                    return GetXElementValue(node, defaultParagraphStyleId, styleId);                }                else if ((styleId != null) && (styleId == "Heading5"))                {                    return GetXElementValue(node, defaultParagraphStyleId, styleId);                }                else if ((styleId != null) && (styleId == "Heading6"))                {                    return GetXElementValue(node, defaultParagraphStyleId, styleId);                }            }            //Iterating Content Controls            if (element.Name == W.sdt)            {                string Xelementname = (string)element.Elements(W.sdtPr).Elements(W.tag).Attributes(W.val).FirstOrDefault().Value.ToString();
                if (!string.IsNullOrEmpty(Xelementname))                {
                    Xelementname = Xelementname.Replace(" ", string.Empty);
                    //removing Special Characters in XML Elements                    Xelementname = RemoveSpecialCharacters(Xelementname);

                    //return new XElement(DQ + "contentControl",                    //    new XAttribute("tag", (string)element.Elements(W.sdtPr)                    //        .Elements(W.tag).Attributes(W.val).FirstOrDefault()),                    //    element.Elements(W.sdtContent).Elements()                    //        .Select(e => TransformToSimpleXml(e, defaultParagraphStyleId)));
                    return new XElement(DQ + Xelementname, Xelementname);                }            }            return null;        }        return node;    }

 

XSD:

 

<?xml version="1.0" encoding="utf-8"?><xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:DQ="DesignQuality" targetNamespace="DesignQuality" elementFormDefault="qualified">  <xs:element name="document">    <xs:complexType>      <xs:sequence>        <xs:element name="ProjectMetadata">          <xs:complexType>            <xs:sequence>              <xs:element name="References" type="xs:string" />              <xs:element name="RevisionHistory" type="xs:string" />            </xs:sequence>            <xs:attribute name="style" use="optional" type="xs:string"></xs:attribute>          </xs:complexType>        </xs:element>        <xs:element name="ProjectOverview">          <xs:complexType>            <xs:sequence>              <xs:element name="Scope" type="xs:string" />            </xs:sequence>            <xs:attribute name="style" use="optional" type="xs:string"></xs:attribute>          </xs:complexType>        </xs:element>        <xs:element name="MSWMProcessAreaGroupPAG" type="xs:string" />        <xs:element name="ExecutiveSummaryofHighLevelRequirements" type="xs:string" />        <xs:element name="ExecutiveSummaryofHighLevelUseCases" type="xs:string" />        <xs:element name="LoginAuthentication" type="xs:string" />        <xs:element name="CommonSolutions" type="xs:string" />        <xs:element name="NewAccountOpening" type="xs:string" />        <xs:element name="ApplicationArchitecture">          <xs:complexType>            <xs:sequence>              <xs:element name="HighlevelSystemInteractionDiagramApplicableNotApplicable" type="xs:string" />              <xs:element name="HighlevelSystemInteractionSequenceDiagramApplicableNotApplicable" type="xs:string" />              <xs:element name="ArchitecturePatternsUsed">                <xs:complexType>                  <xs:sequence>                    <xs:element name="ExistingPatterns" type="xs:string" />                    <xs:element name="NewPatterns" type="xs:string" />                  </xs:sequence>                  <xs:attribute name="style" use="optional" type="xs:string"></xs:attribute>                </xs:complexType>              </xs:element>              <xs:element name="ArchitectureDesignPrerequisites" type="xs:string" />              <xs:element name="CommonSolutionUsage" type="xs:string" />              <xs:element name="ArchitectureDesignDiagram" type="xs:string" />              <xs:element name="ArchitectureDescription" type="xs:string" />              <xs:element name="ApplicationCommonSolutions">                <xs:complexType>                  <xs:sequence>                    <xs:element name="AuthorizationAccessControlModel" type="xs:string" />                    <xs:element name="ConfigurationManagement" type="xs:string" />                    <xs:element name="DataInputValidationFramework" type="xs:string" />                    <xs:element name="SessionManagement" type="xs:string" />                    <xs:element name="Cryptography" type="xs:string" />                    <xs:element name="AuditingandLogging" type="xs:string" />                  </xs:sequence>                  <xs:attribute name="style" use="optional" type="xs:string"></xs:attribute>                </xs:complexType>              </xs:element>              <xs:element name="KeyTechnologiesUsed" type="xs:string" />              <xs:element name="PotentiallyImpactedApplications" type="xs:string" />              <xs:element name="VendorProducts">                <xs:complexType>                  <xs:sequence>                    <xs:element name="BusinessProducts" type="xs:string" />                  </xs:sequence>                  <xs:attribute name="style" use="optional" type="xs:string"></xs:attribute>                </xs:complexType>              </xs:element>              <xs:element name="SubSystemDependencies" type="xs:string" />            </xs:sequence>            <xs:attribute name="style" use="optional" type="xs:string"></xs:attribute>          </xs:complexType>        </xs:element>        <xs:element name="SystemRequirements">          <xs:complexType>            <xs:sequence>              <xs:element name="ApplicationAvailabilityStorage" type="xs:string" />              <xs:element name="NetworkComponents" type="xs:string" />              <xs:element name="DatabaseDesign" type="xs:string" />              <xs:element name="DeploymentView" type="xs:string" />              <xs:element name="ApplicationWebServerRequirements" type="xs:string" />              <xs:element name="ApplicationDatabaseServerRequirements" type="xs:string" />              <xs:element name="ApplicationAppServerRequirements" type="xs:string" />            </xs:sequence>            <xs:attribute name="style" use="optional" type="xs:string"></xs:attribute>          </xs:complexType>        </xs:element>        <xs:element name="DisasterRecoveryandBCPProcess" type="xs:string" />        <xs:element name="ArchitectureDesignTechnologychecklist" type="xs:string" />        <xs:element name="BusinessIntelligenceArchitectureDesignDiagram" type="xs:string" />        <xs:element name="UtilityLayerArchitectureDesignDiagram" type="xs:string" />        <xs:element name="BusinessProcessManagementArchitectureDesign" type="xs:string" />      </xs:sequence>      <xs:attribute name="style" use="optional" type="xs:string"></xs:attribute>    </xs:complexType>  </xs:element></xs:schema>

 

 

private XElement GetXElementValue(XNode node, string defaultParagraphStyleId, string styleId)    {        XElement element = node as XElement;
        if (element != null)        {            XElement XElementval = null;
            string xmlElement = element.LogicalChildrenContent(W.r).Elements(W.t).Select(t => (string)t)                           .StringConcatenate().Trim();
            if (styleId == null)            {                styleId = defaultParagraphStyleId;            }            if (!string.IsNullOrEmpty(xmlElement))            {                //removing spaces between XML Elements                xmlElement = xmlElement.Replace(" ", string.Empty);
                //removing Special Characters in XML Elements                xmlElement = RemoveSpecialCharacters(xmlElement);
                if ((xmlElement != null) && (xmlElement != string.Empty))                {                    XElementval = new XElement(DQ + xmlElement,                                 new XAttribute("style", styleId),                     element.LogicalChildrenContent(W.r).Elements(W.t).Select(t => (string)t)                         .StringConcatenate());
                }            }            return XElementval;        }        else        {            return null;        }
    }
    private XElement GetXElementValue(XNode node, string styleId)    {        XElement element = node as XElement;
        if (element != null)        {            XElement XElementval = null;
            string xmlElement = element.LogicalChildrenContent(W.r).Elements(W.t).Select(t => (string)t)                           .StringConcatenate().Trim();
            if (!string.IsNullOrEmpty(xmlElement))            {                //removing spaces between XML Elements                xmlElement = xmlElement.Replace(" ", string.Empty);
                //removing Special Characters in XML Elements                xmlElement = RemoveSpecialCharacters(xmlElement);
                if ((xmlElement != null) && (xmlElement != string.Empty))                {                    XElementval = new XElement(DQ + xmlElement,                                 new XAttribute("style", styleId));
                }            }            return XElementval;        }        else        {            return null;        }
    }

<DQ:ExecutiveSummaryofHighLevelUseCases style="Heading1" >  <DQ:LoginAuthentication style="Heading2">Login Authentication</DQ:LoginAuthentication>    <DQ:CommonSolutions style="Heading2">Common Solutions</DQ:CommonSolutions>    <DQ:NewAccountOpening style="Heading2">New Account Opening</DQ:NewAccountOpening>  </DQ:ExecutiveSummaryofHighLevelUseCases>

Please help.


Reading Tables in Microsoft Word 2010 based on a check box content control checked and inserting into SQL Tables using OPEN XML SDK

$
0
0

Hi,

I have a use case where i need to scan the High level design and low level design document and read the tables and insert into sql tables based on the Content Control checked checkbox..

For ex: After two years if i want to know all the applications in the organization that are using ORACLE i can query my db and find the list of applications that are using ORACLE .

WordprocessingML from document.xml:

For ex the section named Architecture Design prerequisites is inside the paragraph and the contents are inside the table within a table cell inside a table row.

Please find the attached file for section named Architecture Design prerequisites from the word document.

There are several columns(Table Cell as headings) in table.


Code Used:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Xml;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml.Office2010.Word;
using System.Diagnostics;



namespace Desiqn_Quality
{
    public class Class1
    {

        public bool isArchitecture_Pre;
        public bool isProject_Metadata;
        public bool isAppserverreq;
        public bool isReusableCompt;

        public bool isPresentation;
        public bool isAppBusinessService;
        public bool isDatasource;
        public bool isDevice;
        public bool isUtility;
        public bool isDependent_Common;
        public bool isCommunication;
        public bool isSecurity;

        public bool isAppwebserver;
        public bool isAppOS;
        public bool isNETfrwkversion;
        public bool isAppmemory;
        public bool isAppdskspace;


        public DataTable dt_AppWebServerReq = new DataTable();
        public DataRow dr_AppWebServerReq;

        public DataTable dt_Architecture = new DataTable();



        public string ParseDocxDocument(string pathToFile)
        {
            StringBuilder result = new StringBuilder();

            WordprocessingDocument wordProcessingDoc = WordprocessingDocument.Open(pathToFile, true);

            List<ImagePart> imgPart = wordProcessingDoc.MainDocumentPart.ImageParts.ToList();

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

            IEnumerable<Paragraph> paragraphElement = wordProcessingDoc.MainDocumentPart.Document.Descendants<Paragraph>();

            int imgCounter = 0;

            foreach (OpenXmlElement section in wordProcessingDoc.MainDocumentPart.Document.Body.Elements<OpenXmlElement>())
            {
                Console.WriteLine(section.GetType().Name);

                if (section.GetType().Name == "Paragraph")
                {
                    Paragraph par = (Paragraph)section;

                    //Add new paragraph tag
                    //result.Append("<div style=\"width:100%;font-family:calibri;font-size:11pt;border-width:0px;border-color: #666666;border-collapse:collapse;color:#1F497D;text-align:");

                    //Append anchor style
                    if (par.ParagraphProperties != null && par.ParagraphProperties.Justification != null)
                        switch (par.ParagraphProperties.Justification.Val.Value)
                        {
                            case JustificationValues.Left:
                                //result.Append("left;");
                                break;
                            case JustificationValues.Center:
                                //result.Append("center;");
                                break;
                            case JustificationValues.Both:
                                //result.Append("justify;");
                                break;
                            case JustificationValues.Right:
                            default:
                                //result.Append("right;");
                                break;
                        }
                    else
                        //result.Append("left;");

                        //Append text decoration style
                        if (par.ParagraphProperties != null && par.ParagraphProperties.ParagraphMarkRunProperties != null && par.ParagraphProperties.ParagraphMarkRunProperties.HasChildren)
                            foreach (OpenXmlElement chield in par.ParagraphProperties.ParagraphMarkRunProperties.ChildElements)
                            {
                                switch (chield.GetType().Name)
                                {
                                    case "Bold":
                                        //result.Append("font-weight:bold;");
                                        break;
                                    case "Underline":
                                        //result.Append("text-decoration:underline;");
                                        break;
                                    case "Italic":
                                        //result.Append("font-style:italic;");
                                        break;
                                    case "FontSize":
                                        //result.Append("font-size:" + ((DocumentFormat.OpenXml.Wordprocessing.FontSize)chield).Val.Value + "px;");
                                        break;
                                    default: break;
                                }
                            }

                    // result.Append("\">");

                    //Add image tag
                    IEnumerable<Run> runs = par.Descendants<Run>();

                    foreach (Run run in runs)
                    {
                        if (run.HasChildren)
                        {
                            OpenXmlElementList list = run.ChildElements;


                            foreach (OpenXmlElement chield in run.ChildElements.Where(o => o.GetType().Name == "Picture"))
                            {
                                //result.Append(string.Format("<img style=\"{1}\" src=\"data:image/jpeg;base64,{0}\" />", GetBase64Image(imgPart[imgCounter].GetStream()),
                                //               ((DocumentFormat.OpenXml.Vml.Shape)chield.ChildElements.Where(o => o.GetType().Name == "Shape").FirstOrDefault()).Style
                                //    ));
                                imgCounter++;
                            }
                            foreach (OpenXmlElement table in run.ChildElements.Where(o => o.GetType().Name == "Table"))
                            {
                                //result.Append("<strong>HERE'S TABLE</strong>");
                            }
                        }
                    }
                    //Append inner text
                    IEnumerable<Text> textElement = par.Descendants<Text>();
                    if (par.Descendants<Text>().Count() == 0)
                    {
                        //result.Append("<br />");
                    }
                    foreach (Text txt in textElement.Where(o => !tableCellContent.Contains(o.Text.Trim())))
                    {
                        //result.Append(t.Text);

                        if (txt.Text == "Project Metadata")
                        {
                            isProject_Metadata = true;
                        }
                        else if (txt.Text == "Architecture Design Prerequisites")
                        {
                            isArchitecture_Pre = true;
                        }
                        if (txt.Text == "Application Web Server Requirements")
                        {
                            isAppserverreq = true;
                        }
                        if (txt.Text == "Common Solution Usage")
                        {
                            isReusableCompt = true;
                        }
                    }
                    //result.Append("</div>");
                    //result.Append(Environment.NewLine);
                }
                else if (section.GetType().Name == "Table")
                {
                    DataRow dr = null;
                    //result.Append("<table style='font-family:calibri;font-size:13px;border-width:0px;border-color: #666666;border-collapse:collapse;color:#1F497D'>");

                    Table tab = (Table)section;

                    foreach (TableRow row in tab.Descendants<TableRow>())
                    {
                        //result.Append("<tr style='font-family:calibri;font-size:13pt;color:#1F497D'>");

                        foreach (TableCell cell in row.Descendants<TableCell>())
                        {                            
                            foreach (Paragraph paragraph in cell.Descendants<Paragraph>())
                            {
                                if (paragraph.HasChildren)
                                {
                                    IEnumerable<Run> runs = paragraph.Descendants<Run>();

                                    foreach (Run run in runs)
                                    {
                                        if (run.HasChildren)
                                        {
                                            foreach (Text txt in run.Descendants<Text>())
                                            {
                                                //result.Append(t.Text);

                                                if ((txt != null) && (isArchitecture_Pre))
                                                {

                                                    if (cell.InnerText == "Presentation")
                                                    {
                                                        isPresentation = true;
                                                        dt_Architecture.Columns.Add(txt.Text, txt.Text.GetType());
                                                    }
                                                    else if (cell.InnerText == "App Business Service")
                                                    {
                                                        isAppBusinessService = true;
                                                        dt_Architecture.Columns.Add(txt.Text, txt.Text.GetType());
                                                    }
                                                    else if (cell.InnerText == "Data source")
                                                    {
                                                        isDatasource = true;
                                                        dt_Architecture.Columns.Add(txt.Text, txt.Text.GetType());
                                                    }
                                                    else if (cell.InnerText == "Device/s")
                                                    {
                                                        isDevice = true;
                                                        dt_Architecture.Columns.Add(txt.Text, txt.Text.GetType());
                                                    }
                                                    else if (cell.InnerText == "Utility")
                                                    {
                                                        isUtility = true;
                                                        dt_Architecture.Columns.Add(txt.Text, txt.Text.GetType());
                                                    }
                                                    else if (cell.InnerText == "Dependent/Common Services")
                                                    {
                                                        isDependent_Common = true;
                                                        dt_Architecture.Columns.Add(txt.Text, txt.Text.GetType());
                                                    }
                                                    else if (cell.InnerText == "CommunicationChannel")
                                                    {
                                                        isCommunication = true;
                                                        dt_Architecture.Columns.Add(txt.Text, txt.Text.GetType());
                                                    }
                                                    else if (cell.InnerText == "Security")
                                                    {
                                                        isSecurity = true;
                                                        dt_Architecture.Columns.Add(txt.Text, txt.Text.GetType());
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    foreach (SdtElement Block in paragraph.Descendants<SdtElement>())
                                    {
                                        if (Block.HasChildren)
                                        {
                                            foreach (SdtProperties prop in Block.Descendants<SdtProperties>())
                                            {
                                                if (prop.HasChildren)
                                                {
                                                    foreach (SdtContentCheckBox chkbox in prop.Elements<SdtContentCheckBox>())
                                                    {
                                                        Tag chktag = prop.Elements<Tag>().FirstOrDefault();

                                                        if ((chktag != null) && (chkbox != null))
                                                        {
                                                            if (isPresentation)
                                                            {
                                                                dr = dt_Architecture.NewRow();

                                                                if (chkbox.Checked.Val == "1")
                                                                {
                                                                    dr["Presentation"] = chktag.Val.Value;
                                                                    isPresentation = false;
                                                                }
                                                                else
                                                                {
                                                                    dr["Presentation"] = string.Empty;
                                                                    isPresentation = false;
                                                                }
                                                            }
                                                            else if (isAppBusinessService)
                                                            {
                                                                if (chkbox.Checked.Val == "1")
                                                                {
                                                                    dr["App Business Service"] = chktag.Val.Value;
                                                                    isAppBusinessService = false;
                                                                }
                                                                else
                                                                {
                                                                    dr["App Business Service"] = string.Empty;
                                                                    isAppBusinessService = false;
                                                                }
                                                            }
                                                            else if (isDatasource)
                                                            {
                                                                if (chkbox.Checked.Val == "1")
                                                                {
                                                                    dr["Data source"] = chktag.Val.Value;
                                                                    isDatasource = false;
                                                                }
                                                                else
                                                                {
                                                                    dr["Data source"] = string.Empty;
                                                                    isDatasource = false;
                                                                }
                                                            }
                                                            else if (isDevice)
                                                            {
                                                                if (chkbox.Checked.Val == "1")
                                                                {
                                                                    dr["Device" + Path.AltDirectorySeparatorChar + "s"] = chktag.Val.Value;
                                                                    isDevice = false;
                                                                }
                                                                else
                                                                {
                                                                    dr["Device" + Path.AltDirectorySeparatorChar + "s"] = string.Empty;
                                                                    isDevice = false;
                                                                }
                                                            }
                                                            else if (isUtility)
                                                            {
                                                                if (chkbox.Checked.Val == "1")
                                                                {
                                                                    dr["Utility"] = chktag.Val.Value;
                                                                    isUtility = false;
                                                                }
                                                                else
                                                                {
                                                                    dr["Utility"] = string.Empty;
                                                                    isUtility = false;
                                                                }
                                                            }
                                                            else if (isDependent_Common)
                                                            {
                                                                if (chkbox.Checked.Val == "1")
                                                                {
                                                                    dr["Dependent/Common Services"] = chktag.Val.Value;
                                                                    isDependent_Common = false;
                                                                }
                                                                else
                                                                {
                                                                    dr["Dependent/Common Services"] = string.Empty;
                                                                    isDependent_Common = false;
                                                                }
                                                            }
                                                            else if (isCommunication)
                                                            {
                                                                if (chkbox.Checked.Val == "1")
                                                                {
                                                                    dr["Communication Channel"] = chktag.Val.Value;
                                                                    isCommunication = false;
                                                                }
                                                                else
                                                                {
                                                                    dr["Communication"] = string.Empty;
                                                                    isCommunication = false;
                                                                }
                                                            }
                                                            else if (isSecurity)
                                                            {
                                                                if (chkbox.Checked.Val == "1")
                                                                {
                                                                    dr["Security"] = chktag.Val.Value;
                                                                    isSecurity = false;
                                                                }
                                                                else
                                                                {
                                                                    dr["Security"] = string.Empty;
                                                                    isSecurity = false;
                                                                }
                                                                dt_Architecture.Rows.Add(dr);
                                                            }                                                           
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            //result.Append("<td style='font-family:calibri;font-size:11pt;color:#1F497D'>");
                            //result.Append(cell.InnerText);
                            //tableCellContent.Add(cell.InnerText.Trim());
                            //result.Append("</td>");

                            //result.Append("</tr>");
                        }                        
                        //result.Append("</table>");
                    }
                }
                //iterating ContentControls inside the document                    
                else if (section.GetType().Name == "SdtBlock")
                {

                    
                }                
            }

            dt_AppWebServerReq.Rows.Add(dr_AppWebServerReq);

            wordProcessingDoc.Close();

            return result.ToString();
        }
    }

}

 

 

 

 

 

 

 

Paragraph and Run Properties not removed as part of Markup simplifier

$
0
0

Hi,

I am using the code from the below mentioned blog and i am trying to simplify the markup and i don't see that Run and paragraph properties are getting removed from the document.xml.

I know that the below mentioned approach simplifies the markup only in Memory not writing back to the file.So i have downloaded the markupSimplifier project and its modifying the original file that is uploaded in the OpenFileDialog.

Please let me know whether we need to create custom transformation for removing the Paragraph and Run properties.

http://blogs.msdn.com/b/ericwhite/archive/2010/02/08/enabling-better-transformations-by-simplifying-open-xml-wordprocessingml-markup.aspx


 

WordProcessingML For Headings:

 

<w:p w14:paraId="08BADB8B" w14:textId="5A9A23C4"><w:pPr><w:pStyle w:val="Heading2" /><w:rPr><w:rFonts w:asciiTheme="minorHAnsi" w:hAnsiTheme="minorHAnsi" w:cstheme="minorHAnsi" /><w:color w:val="1F497D" w:themeColor="text2" /></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:asciiTheme="minorHAnsi" w:hAnsiTheme="minorHAnsi" w:cstheme="minorHAnsi" /><w:color w:val="1F497D" w:themeColor="text2" /></w:rPr><w:t>Architecture Design Prerequisites</w:t></w:r></w:p>


 

WordProcessingML For Table Cell:

 

<w:tc><w:tcPr><w:tcW w:w="1454" w:type="dxa" /><w:tcBorders><w:top w:val="single" w:sz="4" w:space="0" w:color="000000" /><w:bottom w:val="single" w:sz="4" w:space="0" w:color="000000" /></w:tcBorders><w:shd w:val="clear" w:color="auto" w:fill="8DB3E2" w:themeFill="text2" w:themeFillTint="66" /><w:vAlign w:val="center" /></w:tcPr><w:p w14:paraId="08BADB8C" w14:textId="49B811AB"><w:pPr><w:spacing w:before="20" /><w:jc w:val="center" /><w:rPr><w:rFonts w:ascii="Calibri" w:hAnsi="Calibri" w:cs="Calibri" /><w:b /><w:color w:val="1F497D" /><w:sz w:val="22" /><w:szCs w:val="22" /></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:ascii="Calibri" w:hAnsi="Calibri" w:cs="Calibri" /><w:b /><w:color w:val="1F497D" /><w:sz w:val="22" /><w:szCs w:val="22" /></w:rPr><w:t>Presentation</w:t></w:r></w:p></w:tc>

 

 

Expected Output for Headings:

<w:p> <w:r> <w:t>Architecture Design Prerequisites</w:t> </w:r></w:p>

 

Expected Output for Table Cell:

 

<w:tc><w:p><w:r><w:t>Presentation</w:t></w:r></w:p></w:tc>

 

 

 

Replacing comments with hyperlinks

$
0
0

Hello, I'm brand new to OpenXML and am doing research on how/what we can do.

The problem I'm trying to address is showing comments on a web page.  I want to use the Hyperlink system to show comments.

I've found the WordprocessingCommentsPart collection, the CommentRangeStart, the CommentRangeEnd but I'm at a loss on how to insert a HyperLink for each comment.  

Each comment has a start and an end, but I'm not sure how to insert a Hyperlink that highlights the same text as the comment.

Maybe I can just punt on hyperlinking the same text and just INSERT a HyperLink with the name of the comment ID.

Here's my research code...the document I'm loading has 8 comments and I'm trying to insert a hyperlink BEFORE the first one.  I'm getting the error: Operation is not valid due to the current state of the object.   

                DocumentFormat.OpenXml.Wordprocessing.Document doc = wordDoc.MainDocumentPart.Document;
                List<CommentRangeStart> commentRangeStart = doc.Descendants<CommentRangeStart>().ToList();
                List<CommentRangeEnd> commentRangeEnd = doc.Descendants<CommentRangeEnd>().ToList();
                DocumentFormat.OpenXml.Wordprocessing.Paragraph p = new DocumentFormat.OpenXml.Wordprocessing.Paragraph( 
                    new DocumentFormat.OpenXml.Wordprocessing.Hyperlink(new Run(new Text("Click here"))) { Anchor = "Description", DocLocation = "location" }
                    );
                doc.Body.InsertBefore<DocumentFormat.OpenXml.Wordprocessing.Paragraph>(p, commentRangeStart[0]);
                wordDoc.SaveAs(@"C:\Development\mockedupa.docx");

I'm sure that I'm missing something 'obvious'.  For some reason, it's always something right in front of me that I'm missing.

Thank you in advance for your help.

Gene

Xpath Content Controls

$
0
0

Good day,

 

I only recently found the PowerTools for Open XML v4.0 and I've been playing around with it. It works great but I would like to know if the Xpath Content Controls listed in the template documents can be enhanced or expanded on. So far I've only seen

  • Content select
  • Table select
  • Conditional select
  • Repeat Select

Are there any others? Where can i find more information on how i can get more selective? Example, in the templates there is a Conditional select that would do something if an element sting matches a value. Is it however possible to have a conditional select based on the existence of a element e.g. if element exists, content select element string.

 

Thanks in advance

 

Regards

 

Riaan Badenhorst

Reading Connected Shapes in the word document

$
0
0

Hi,

I have a word 2010 document with images,content controls,paragraphs and tables in it.

There are few cases we have connected shapes in Word 2010 document. These shapes are not images in the word document.

The Architecture block diagram in the HLD document  is not an image in the document.

We are rending the images, paragraphs, tables in a web application by reading the document using OPENXML SDK.

Reason for having them as connected Shapes:

I am in the process of standardizing the HLD and LLD document for the organization.So predefined Architecture approved patterns for Web Application Architectural styles will be inserted as connected shapes instead of images in Word 2010 document.

So development teams can get the HLD template and they can add or remove the existing connected shapes in the diagram without starting from scratch.Images are not preferred since they are not editable in the template that we provide for HLD.

Question Reading the Connected Shapes and Rendering it in a ASP.NET Web Form:

I saw several blogs for changing the format of the shapes in the VML using regex.

http://openxmldeveloper.org/discussions/development_tools/f/17/t/7299.aspx

Is there a way t render the connected shapes(Architecture block diagram) using OPENXML SDK and render it in a Web Form.

We are planning to have Visio Objects embedded for these connected shapes also.But through my surfing in internet Visio is using DataDiagrammingML in Visio 2010 for .VDX files which is now chnaged in Visio 2013 and Visio 2016.

Is there any other SDK avaialble to read the DataDiagramminML from a Visio diagram and render it in ASP.NET Web Form(Will VISIO 2010 SDK help in reading the DataDiagrammingML).

Please help me how to achieve this use case.


Viewing all 1417 articles
Browse latest View live