Add Content Control collection and methods to replace text.master
| { | { | ||||
| public abstract class Container : DocXElement | public abstract class Container : DocXElement | ||||
| { | { | ||||
| public virtual ReadOnlyCollection<Content> Contents | |||||
| { | |||||
| get | |||||
| { | |||||
| List<Content> contents = GetContents(); | |||||
| return contents.AsReadOnly(); | |||||
| } | |||||
| } | |||||
| /// <summary> | /// <summary> | ||||
| /// Returns a list of all Paragraphs inside this container. | /// Returns a list of all Paragraphs inside this container. | ||||
| /// </summary> | /// </summary> | ||||
| public ContainerType ParentContainer; | public ContainerType ParentContainer; | ||||
| internal List<Content> GetContents(bool deepSearch = false) | |||||
| { | |||||
| // Need some memory that can be updated by the recursive search. | |||||
| //int index = 0; | |||||
| List<Content> contents = new List<Content>(); | |||||
| foreach (XElement e in Xml.Descendants(XName.Get("sdt", DocX.w.NamespaceName))) | |||||
| { | |||||
| Content content = new Content(Document, e, 0); | |||||
| XElement el = e.Elements(XName.Get("sdtPr", DocX.w.NamespaceName)).First(); | |||||
| content.Name = GetAttribute(el, "alias", "val"); | |||||
| content.Tag = GetAttribute(el, "tag", "val"); | |||||
| contents.Add(content); | |||||
| } | |||||
| return contents; | |||||
| } | |||||
| private string GetAttribute(XElement e, string localName, string attributeName) | |||||
| { | |||||
| string val = string.Empty; | |||||
| try | |||||
| { | |||||
| val = e.Elements(XName.Get(localName, DocX.w.NamespaceName)).Attributes(XName.Get(attributeName, DocX.w.NamespaceName)).FirstOrDefault().Value; | |||||
| } | |||||
| catch (Exception) | |||||
| { | |||||
| val = "Missing"; | |||||
| } | |||||
| return val; | |||||
| } | |||||
| internal List<Paragraph> GetParagraphs(bool deepSearch=false) | internal List<Paragraph> GetParagraphs(bool deepSearch=false) | ||||
| { | { | ||||
| // Need some memory that can be updated by the recursive search. | // Need some memory that can be updated by the recursive search. | ||||
| int index = 0; | int index = 0; | ||||
| List<Paragraph> paragraphs = new List<Paragraph>(); | List<Paragraph> paragraphs = new List<Paragraph>(); | ||||
| GetParagraphsRecursive(Xml, ref index, ref paragraphs, deepSearch); | |||||
| foreach (XElement e in Xml.Descendants(XName.Get("p", DocX.w.NamespaceName))) | |||||
| { | |||||
| index += HelperFunctions.GetText(e).Length; | |||||
| Paragraph paragraph = new Paragraph(Document, e, index); | |||||
| paragraphs.Add(paragraph); | |||||
| } | |||||
| // GetParagraphsRecursive(Xml, ref index, ref paragraphs, deepSearch); | |||||
| return paragraphs; | return paragraphs; | ||||
| } | } | ||||
| // sdtContent are for PageNumbers inside Headers or Footers, don't go any deeper. | // sdtContent are for PageNumbers inside Headers or Footers, don't go any deeper. | ||||
| //if (Xml.Name.LocalName == "sdtContent") | //if (Xml.Name.LocalName == "sdtContent") | ||||
| // return; | // return; | ||||
| var keepSearching = true; | var keepSearching = true; | ||||
| if (Xml.Name.LocalName == "p") | if (Xml.Name.LocalName == "p") | ||||
| { | { |
| using System; | |||||
| using System.Linq; | |||||
| using System.Collections.Generic; | |||||
| using System.Xml.Linq; | |||||
| namespace Novacode | |||||
| { | |||||
| public class Content : InsertBeforeOrAfter | |||||
| { | |||||
| public string Name { get; set; } | |||||
| public string Tag { get; set; } | |||||
| public string Text { get; set; } | |||||
| public List<Content> Sections { get; set; } | |||||
| public ContainerType ParentContainer; | |||||
| internal Content(DocX document, XElement xml, int startIndex) | |||||
| : base(document, xml) | |||||
| { | |||||
| } | |||||
| public void SetText(string newText) | |||||
| { | |||||
| string x = this.Tag; | |||||
| XElement el = Xml; | |||||
| Xml.Descendants(XName.Get("t", DocX.w.NamespaceName)).First().Value = newText; | |||||
| } | |||||
| } | |||||
| } |
| using System; | |||||
| using System.Collections.Generic; | |||||
| using System.Linq; | |||||
| using System.Text; | |||||
| namespace Novacode | |||||
| { | |||||
| public class ContentCollection : List<Content> | |||||
| { | |||||
| public Content this[string name] | |||||
| { | |||||
| get | |||||
| { | |||||
| return this.FirstOrDefault(content => string.Equals(content.Name, name, StringComparison.CurrentCultureIgnoreCase)); | |||||
| } | |||||
| } | |||||
| } | |||||
| } |
| } | } | ||||
| } | } | ||||
| /// <summary> | |||||
| /// Bottom margin value in points. 1pt = 1/72 of an inch. Word internally writes docx using units = 1/20th of a point. | |||||
| /// </summary> | |||||
| public float MarginBottom | |||||
| /// <summary> | |||||
| /// Bottom margin value in points. 1pt = 1/72 of an inch. Word internally writes docx using units = 1/20th of a point. | |||||
| /// </summary> | |||||
| public float MarginBottom | |||||
| { | { | ||||
| get | get | ||||
| { | { | ||||
| } | } | ||||
| } | } | ||||
| /// <summary> | |||||
| /// Left margin value in points. 1pt = 1/72 of an inch. Word internally writes docx using units = 1/20th of a point. | |||||
| /// </summary> | |||||
| public float MarginLeft | |||||
| /// <summary> | |||||
| /// Left margin value in points. 1pt = 1/72 of an inch. Word internally writes docx using units = 1/20th of a point. | |||||
| /// </summary> | |||||
| public float MarginLeft | |||||
| { | { | ||||
| get | get | ||||
| { | { | ||||
| } | } | ||||
| } | } | ||||
| /// <summary> | |||||
| /// Right margin value in points. 1pt = 1/72 of an inch. Word internally writes docx using units = 1/20th of a point. | |||||
| /// </summary> | |||||
| public float MarginRight | |||||
| /// <summary> | |||||
| /// Right margin value in points. 1pt = 1/72 of an inch. Word internally writes docx using units = 1/20th of a point. | |||||
| /// </summary> | |||||
| public float MarginRight | |||||
| { | { | ||||
| get | get | ||||
| { | { | ||||
| } | } | ||||
| } | } | ||||
| /// <summary> | |||||
| /// Page width value in points. 1pt = 1/72 of an inch. Word internally writes docx using units = 1/20th of a point. | |||||
| /// </summary> | |||||
| public float PageWidth | |||||
| /// <summary> | |||||
| /// Page width value in points. 1pt = 1/72 of an inch. Word internally writes docx using units = 1/20th of a point. | |||||
| /// </summary> | |||||
| public float PageWidth | |||||
| { | { | ||||
| get | get | ||||
| { | { | ||||
| } | } | ||||
| } | } | ||||
| /// <summary> | |||||
| /// Page height value in points. 1pt = 1/72 of an inch. Word internally writes docx using units = 1/20th of a point. | |||||
| /// </summary> | |||||
| public float PageHeight | |||||
| /// <summary> | |||||
| /// Page height value in points. 1pt = 1/72 of an inch. Word internally writes docx using units = 1/20th of a point. | |||||
| /// </summary> | |||||
| public float PageHeight | |||||
| { | { | ||||
| get | get | ||||
| { | { | ||||
| } | } | ||||
| } | } | ||||
| return (15840.0f / 20.0f); | |||||
| return (15840.0f / 20.0f); | |||||
| } | } | ||||
| set | set | ||||
| return HelperFunctions.GetText(Xml); | return HelperFunctions.GetText(Xml); | ||||
| } | } | ||||
| } | } | ||||
| /// <summary> | |||||
| /// Get the text of each footnote from this document | |||||
| /// </summary> | |||||
| public IEnumerable<string> FootnotesText | |||||
| { | |||||
| get | |||||
| { | |||||
| /// <summary> | |||||
| /// Get the text of each footnote from this document | |||||
| /// </summary> | |||||
| public IEnumerable<string> FootnotesText | |||||
| { | |||||
| get | |||||
| { | |||||
| foreach (XElement footnote in footnotes.Root.Elements(w + "footnote")) | foreach (XElement footnote in footnotes.Root.Elements(w + "footnote")) | ||||
| { | { | ||||
| yield return HelperFunctions.GetText(footnote); | yield return HelperFunctions.GetText(footnote); | ||||
| merge_footnotes(remote_pp, local_pp, remote_mainDoc, remote_document, remote_footnotes); | merge_footnotes(remote_pp, local_pp, remote_mainDoc, remote_document, remote_footnotes); | ||||
| remote_footnotes = footnotes; | remote_footnotes = footnotes; | ||||
| break; | break; | ||||
| case "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": | case "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": | ||||
| merge_endnotes(remote_pp, local_pp, remote_mainDoc, remote_document, remote_endnotes); | merge_endnotes(remote_pp, local_pp, remote_mainDoc, remote_document, remote_endnotes); | ||||
| remote_endnotes = endnotes; | remote_endnotes = endnotes; | ||||
| // Add the remote documents contents to this document. | // Add the remote documents contents to this document. | ||||
| XElement local_body = mainDoc.Root.Element(XName.Get("body", DocX.w.NamespaceName)); | XElement local_body = mainDoc.Root.Element(XName.Get("body", DocX.w.NamespaceName)); | ||||
| if (append) | |||||
| local_body.Add(remote_body.Elements()); | |||||
| else | |||||
| local_body.AddFirst(remote_body.Elements()); | |||||
| if (append) | |||||
| local_body.Add(remote_body.Elements()); | |||||
| else | |||||
| local_body.AddFirst(remote_body.Elements()); | |||||
| // Copy any missing root attributes to the local document. | |||||
| foreach (XAttribute a in remote_mainDoc.Root.Attributes()) | |||||
| // Copy any missing root attributes to the local document. | |||||
| foreach (XAttribute a in remote_mainDoc.Root.Attributes()) | |||||
| { | { | ||||
| if (mainDoc.Root.Attribute(a.Name) == null) | if (mainDoc.Root.Attribute(a.Name) == null) | ||||
| { | { | ||||
| // In my testing I have found cases of Images inside documents that are not referenced | // In my testing I have found cases of Images inside documents that are not referenced | ||||
| var remote_rel = remote_document.mainPart.GetRelationships().Where(r => r.TargetUri.OriginalString.Equals(remote_pp.Uri.OriginalString.Replace("/word/", ""))).FirstOrDefault(); | var remote_rel = remote_document.mainPart.GetRelationships().Where(r => r.TargetUri.OriginalString.Equals(remote_pp.Uri.OriginalString.Replace("/word/", ""))).FirstOrDefault(); | ||||
| if (remote_rel == null) { | if (remote_rel == null) { | ||||
| remote_rel = remote_document.mainPart.GetRelationships().Where(r => r.TargetUri.OriginalString.Equals(remote_pp.Uri.OriginalString)).FirstOrDefault(); | |||||
| if (remote_rel == null) | |||||
| return; | |||||
| remote_rel = remote_document.mainPart.GetRelationships().Where(r => r.TargetUri.OriginalString.Equals(remote_pp.Uri.OriginalString)).FirstOrDefault(); | |||||
| if (remote_rel == null) | |||||
| return; | |||||
| } | } | ||||
| String remote_Id = remote_rel.Id; | String remote_Id = remote_rel.Id; | ||||
| } | } | ||||
| if (!defRelId.Success) | if (!defRelId.Success) | ||||
| { | |||||
| // Replace all instances of remote_Id in the local document with local_Id | |||||
| var elems_local = mainDoc.Descendants(XName.Get("blip", DocX.a.NamespaceName)); | |||||
| foreach (var elem in elems_local) | |||||
| { | |||||
| XAttribute embed = elem.Attribute(XName.Get("embed", DocX.r.NamespaceName)); | |||||
| if (embed != null && embed.Value == remote_Id) | |||||
| { | |||||
| embed.SetValue(new_Id); | |||||
| } | |||||
| } | |||||
| // Replace all instances of remote_Id in the local document with local_Id | |||||
| var v_elems_local = mainDoc.Descendants(XName.Get("imagedata", DocX.v.NamespaceName)); | |||||
| foreach (var elem in v_elems_local) | |||||
| { | |||||
| XAttribute id = elem.Attribute(XName.Get("id", DocX.r.NamespaceName)); | |||||
| if (id != null && id.Value == remote_Id) | |||||
| { | |||||
| id.SetValue(new_Id); | |||||
| } | |||||
| } | |||||
| } | |||||
| { | |||||
| // Replace all instances of remote_Id in the local document with local_Id | |||||
| var elems_local = mainDoc.Descendants(XName.Get("blip", DocX.a.NamespaceName)); | |||||
| foreach (var elem in elems_local) | |||||
| { | |||||
| XAttribute embed = elem.Attribute(XName.Get("embed", DocX.r.NamespaceName)); | |||||
| if (embed != null && embed.Value == remote_Id) | |||||
| { | |||||
| embed.SetValue(new_Id); | |||||
| } | |||||
| } | |||||
| // Replace all instances of remote_Id in the local document with local_Id | |||||
| var v_elems_local = mainDoc.Descendants(XName.Get("imagedata", DocX.v.NamespaceName)); | |||||
| foreach (var elem in v_elems_local) | |||||
| { | |||||
| XAttribute id = elem.Attribute(XName.Get("id", DocX.r.NamespaceName)); | |||||
| if (id != null && id.Value == remote_Id) | |||||
| { | |||||
| id.SetValue(new_Id); | |||||
| } | |||||
| } | |||||
| } | |||||
| // Replace all instances of remote_Id in the local document with local_Id (for shapes as well) | // Replace all instances of remote_Id in the local document with local_Id (for shapes as well) | ||||
| // Checking whether there were more than 0 elements, helped me get rid of exceptions thrown while using InsertDocument | // Checking whether there were more than 0 elements, helped me get rid of exceptions thrown while using InsertDocument | ||||
| if (numbering.Root.Elements(XName.Get("abstractNum", DocX.w.NamespaceName)).Count() > 0) | if (numbering.Root.Elements(XName.Get("abstractNum", DocX.w.NamespaceName)).Count() > 0) | ||||
| numbering.Root.Elements(XName.Get("abstractNum", DocX.w.NamespaceName)).Last().AddAfterSelf(remote_abstractNums); | |||||
| numbering.Root.Elements(XName.Get("abstractNum", DocX.w.NamespaceName)).Last().AddAfterSelf(remote_abstractNums); | |||||
| if (numbering.Root.Elements(XName.Get("num", DocX.w.NamespaceName)).Count() > 0) | if (numbering.Root.Elements(XName.Get("num", DocX.w.NamespaceName)).Count() > 0) | ||||
| numbering.Root.Elements(XName.Get("num", DocX.w.NamespaceName)).Last().AddAfterSelf(remote_nums); | |||||
| numbering.Root.Elements(XName.Get("num", DocX.w.NamespaceName)).Last().AddAfterSelf(remote_nums); | |||||
| } | } | ||||
| private void merge_fonts(PackagePart remote_pp, PackagePart local_pp, XDocument remote_mainDoc, DocX remote) | private void merge_fonts(PackagePart remote_pp, PackagePart local_pp, XDocument remote_mainDoc, DocX remote) | ||||
| } | } | ||||
| } | } | ||||
| // Replace all instances of remote_Id in the local document with local_Id (for shapes as well) | |||||
| // Replace all instances of remote_Id in the local document with local_Id (for shapes as well) | |||||
| var v_elems = remote_mainDoc.Descendants(XName.Get("imagedata", DocX.v.NamespaceName)); | var v_elems = remote_mainDoc.Descendants(XName.Get("imagedata", DocX.v.NamespaceName)); | ||||
| foreach (var elem in v_elems) | foreach (var elem in v_elems) | ||||
| { | { | ||||
| if (!document.paragraphLookup.ContainsKey(paragraph.endIndex)) | if (!document.paragraphLookup.ContainsKey(paragraph.endIndex)) | ||||
| document.paragraphLookup.Add(paragraph.endIndex, paragraph); | document.paragraphLookup.Add(paragraph.endIndex, paragraph); | ||||
| } | } | ||||
| return document; | return document; | ||||
| } | } | ||||
| public void Save() | public void Save() | ||||
| { | { | ||||
| Headers headers = Headers; | Headers headers = Headers; | ||||
| // Save the main document | // Save the main document | ||||
| using (TextWriter tw = new StreamWriter(mainPart.GetStream(FileMode.Create, FileAccess.Write))) | using (TextWriter tw = new StreamWriter(mainPart.GetStream(FileMode.Create, FileAccess.Write))) | ||||
| mainDoc.Save(tw, SaveOptions.None); | mainDoc.Save(tw, SaveOptions.None); | ||||
| customPropDoc.Save(tw, SaveOptions.None); | customPropDoc.Save(tw, SaveOptions.None); | ||||
| // Refresh all fields in this document which display this custom property. | // Refresh all fields in this document which display this custom property. | ||||
| UpdateCustomPropertyValue(this, cp.Name, (cp.Value ?? "").ToString()); | |||||
| UpdateCustomPropertyValue(this, cp.Name, (cp.Value ?? "").ToString()); | |||||
| } | } | ||||
| /// <summary> | /// <summary> | ||||
| documents.Add(footers.even.Xml); | documents.Add(footers.even.Xml); | ||||
| #endregion | #endregion | ||||
| var matchCustomPropertyName = customPropertyName; | |||||
| if (customPropertyName.Contains(" ")) matchCustomPropertyName = "\"" + customPropertyName + "\""; | |||||
| string match_value = string.Format(@"DOCPROPERTY {0} \* MERGEFORMAT", matchCustomPropertyName).Replace(" ", string.Empty); | |||||
| var matchCustomPropertyName = customPropertyName; | |||||
| if (customPropertyName.Contains(" ")) matchCustomPropertyName = "\"" + customPropertyName + "\""; | |||||
| string match_value = string.Format(@"DOCPROPERTY {0} \* MERGEFORMAT", matchCustomPropertyName).Replace(" ", string.Empty); | |||||
| // Process each document in the list. | // Process each document in the list. | ||||
| foreach (XElement doc in documents) | foreach (XElement doc in documents) | ||||
| { | { | ||||
| foreach (XElement e in doc.Descendants(XName.Get("fldSimple", w.NamespaceName))) | foreach (XElement e in doc.Descendants(XName.Get("fldSimple", w.NamespaceName))) | ||||
| { | { | ||||
| string attr_value = e.Attribute(XName.Get("instr", w.NamespaceName)).Value.Replace(" ", string.Empty).Trim(); | string attr_value = e.Attribute(XName.Get("instr", w.NamespaceName)).Value.Replace(" ", string.Empty).Trim(); | ||||
| if (attr_value.Equals(match_value, StringComparison.CurrentCultureIgnoreCase)) | if (attr_value.Equals(match_value, StringComparison.CurrentCultureIgnoreCase)) | ||||
| { | { | ||||
| XElement firstRun = e.Element(w + "r"); | XElement firstRun = e.Element(w + "r"); | ||||
| return paragraphs.ToArray(); | return paragraphs.ToArray(); | ||||
| } | } | ||||
| public override ReadOnlyCollection<Content> Contents | |||||
| { | |||||
| get | |||||
| { | |||||
| ReadOnlyCollection<Content> l = base.Contents; | |||||
| foreach (var content in l) | |||||
| { | |||||
| content.PackagePart = mainPart; | |||||
| } | |||||
| return l; | |||||
| } | |||||
| } | |||||
| public void SetContent(XElement el) | |||||
| { | |||||
| foreach (XElement e in el.Elements()) | |||||
| { | |||||
| (from d in Document.Contents | |||||
| where d.Name == e.Name | |||||
| select d).First().SetText(e.Value); | |||||
| } | |||||
| } | |||||
| public void SetContent(Dictionary<string, string> dict) | |||||
| { | |||||
| foreach (KeyValuePair<string, string> item in dict) | |||||
| { | |||||
| (from d in Document.Contents | |||||
| where d.Name == item.Key | |||||
| select d).First().SetText(item.Value); | |||||
| } | |||||
| } | |||||
| public void SetContent(string path) | |||||
| { | |||||
| XDocument doc = XDocument.Load(path); | |||||
| SetContent(doc); | |||||
| } | |||||
| public void SetContent(XDocument xmlDoc) | |||||
| { | |||||
| foreach (XElement e in xmlDoc.ElementsAfterSelf()) | |||||
| { | |||||
| (from d in Document.Contents | |||||
| where d.Name == e.Name | |||||
| select d).First().SetText(e.Value); | |||||
| } | |||||
| } | |||||
| public override ReadOnlyCollection<Paragraph> Paragraphs | public override ReadOnlyCollection<Paragraph> Paragraphs | ||||
| { | { | ||||
| get | get |
| <Compile Include="Charts\PieChart.cs" /> | <Compile Include="Charts\PieChart.cs" /> | ||||
| <Compile Include="Charts\XElementHelpers.cs" /> | <Compile Include="Charts\XElementHelpers.cs" /> | ||||
| <Compile Include="Container.cs" /> | <Compile Include="Container.cs" /> | ||||
| <Compile Include="Content.cs" /> | |||||
| <Compile Include="ContentCollection.cs" /> | |||||
| <Compile Include="DocumentTypes.cs" /> | <Compile Include="DocumentTypes.cs" /> | ||||
| <Compile Include="ExtensionsHeadings.cs" /> | <Compile Include="ExtensionsHeadings.cs" /> | ||||
| <Compile Include="Footers.cs" /> | <Compile Include="Footers.cs" /> | ||||
| <Compile Include="Headers.cs" /> | <Compile Include="Headers.cs" /> | ||||
| <Compile Include="HelperFunctions.cs" /> | <Compile Include="HelperFunctions.cs" /> | ||||
| <Compile Include="Hyperlink.cs" /> | <Compile Include="Hyperlink.cs" /> | ||||
| <Compile Include="IContentContainer.cs" /> | |||||
| <Compile Include="IParagraphContainer.cs" /> | <Compile Include="IParagraphContainer.cs" /> | ||||
| <Compile Include="List.cs" /> | <Compile Include="List.cs" /> | ||||
| <Compile Include="PageLayout.cs" /> | <Compile Include="PageLayout.cs" /> |
| using System.Collections.ObjectModel; | |||||
| namespace Novacode | |||||
| { | |||||
| interface IContentContainer | |||||
| { | |||||
| ReadOnlyCollection<Content> Paragraphs { get; } | |||||
| } | |||||
| } |
| using System.Drawing.Imaging; | using System.Drawing.Imaging; | ||||
| using System.IO; | using System.IO; | ||||
| using System.Linq; | using System.Linq; | ||||
| using System.Xml.Linq; | |||||
| using System.Threading.Tasks; | using System.Threading.Tasks; | ||||
| using Novacode; | using Novacode; | ||||
| using Image = Novacode.Image; | using Image = Novacode.Image; | ||||
| static void Main(string[] args) | static void Main(string[] args) | ||||
| { | { | ||||
| Setup(); | Setup(); | ||||
| HelloWorld(); | |||||
| //Contents(); | |||||
| AddList(); | |||||
| Console.ReadLine(); | |||||
| // Examples(); | |||||
| } | |||||
| static void Examples() | |||||
| { | |||||
| // Setup(); | |||||
| // Easy | // Easy | ||||
| Console.WriteLine("\nRunning Easy Examples"); | Console.WriteLine("\nRunning Easy Examples"); | ||||
| HelloWorld(); | HelloWorld(); | ||||
| } | } | ||||
| #endregion | #endregion | ||||
| /// <summary> | |||||
| /// Load a document and set content controls. | |||||
| /// </summary> | |||||
| private static void Contents() | |||||
| { | |||||
| Console.WriteLine("\tContent()"); | |||||
| // Load a document. | |||||
| using (DocX document = DocX.Load(@"docs\Content.docx")) | |||||
| { | |||||
| foreach (var c in document.Contents) | |||||
| { | |||||
| Console.WriteLine(String.Format("Name : {0}, Tag : {1}", c.Name, c.Tag)); | |||||
| } | |||||
| (from d in document.Contents | |||||
| where d.Name == "Name" | |||||
| select d).First().SetText("NewerText"); | |||||
| document.SaveAs(@"docs\ContentSetSingle.docx"); | |||||
| XElement el = new XElement("Root", | |||||
| new XElement("Name", "Claudia"), | |||||
| new XElement("Address", "17 Liberty St"), | |||||
| new XElement("Total", "123.45") | |||||
| ); | |||||
| XDocument doc = new XDocument(el); | |||||
| document.SetContent(el); | |||||
| document.SaveAs(@"docs\ContentSetWithElement.docx"); | |||||
| doc.Save(@"docs\elements.xml"); | |||||
| document.SetContent(@"docs\elements.xml"); | |||||
| document.SaveAs(@"docs\ContentSetWithPath.docx"); | |||||
| } | |||||
| } | |||||
| /// <summary> | /// <summary> | ||||
| /// Create a document with two equations. | |||||
| /// Create a document wit(h two equations. | |||||
| /// </summary> | /// </summary> | ||||
| private static void Equations() | private static void Equations() | ||||
| { | { | ||||
| document.Save(); | document.Save(); | ||||
| Console.WriteLine("\tCreated: docs\\Bookmarks.docx\n"); | Console.WriteLine("\tCreated: docs\\Bookmarks.docx\n"); | ||||
| } | } | ||||
| } | } | ||||
| /// <summary> | /// <summary> | ||||
| Paragraph title = document.InsertParagraph().Append("Test").FontSize(20).Font(new FontFamily("Comic Sans MS")); | Paragraph title = document.InsertParagraph().Append("Test").FontSize(20).Font(new FontFamily("Comic Sans MS")); | ||||
| title.Alignment = Alignment.center; | title.Alignment = Alignment.center; | ||||
| // Insert a new Paragraph into the document. | // Insert a new Paragraph into the document. | ||||
| Paragraph p1 = document.InsertParagraph(); | Paragraph p1 = document.InsertParagraph(); | ||||
| Paragraph p3 = document.InsertParagraph(); | Paragraph p3 = document.InsertParagraph(); | ||||
| p3.AppendLine(); | p3.AppendLine(); | ||||
| p3.AppendLine("Adding another table..."); | p3.AppendLine("Adding another table..."); | ||||
| // Adding another table | // Adding another table | ||||
| Table table1 = document.AddTable(2, 2); | Table table1 = document.AddTable(2, 2); | ||||
| table1.Design = TableDesign.ColorfulGridAccent2; | table1.Design = TableDesign.ColorfulGridAccent2; | ||||
| p4.InsertTableBeforeSelf(table1); | p4.InsertTableBeforeSelf(table1); | ||||
| p4.AppendLine(); | p4.AppendLine(); | ||||
| // Insert numbered list after table | // Insert numbered list after table | ||||
| Paragraph p5 = document.InsertParagraph(); | Paragraph p5 = document.InsertParagraph(); | ||||
| using (DocX document = DocX.Create(@"docs\DocumentMargins.docx")) | using (DocX document = DocX.Create(@"docs\DocumentMargins.docx")) | ||||
| { | { | ||||
| // Create a float var that contains doc Margins properties. | |||||
| // Create a float var that contains doc Margins properties. | |||||
| float leftMargin = document.MarginLeft; | float leftMargin = document.MarginLeft; | ||||
| float rightMargin = document.MarginRight; | float rightMargin = document.MarginRight; | ||||
| float topMargin = document.MarginTop; | float topMargin = document.MarginTop; | ||||
| document.MarginLeft = leftMargin; | document.MarginLeft = leftMargin; | ||||
| document.MarginRight = rightMargin; | document.MarginRight = rightMargin; | ||||
| document.MarginTop = topMargin; | document.MarginTop = topMargin; | ||||
| document.MarginBottom = bottomMargin; | |||||
| document.MarginBottom = bottomMargin; | |||||
| // created bulleted lists | // created bulleted lists | ||||
| var bulletedList = document.AddList("First Bulleted Item.", 0, ListItemType.Bulleted); | var bulletedList = document.AddList("First Bulleted Item.", 0, ListItemType.Bulleted); | ||||
| document.InsertList(bulletedList); | document.InsertList(bulletedList); | ||||
| // Save this document. | // Save this document. | ||||
| document.Save(); | document.Save(); | ||||
| using (DocX document = DocX.Create(@"docs\DocumentsWithListsFontChange.docx")) | using (DocX document = DocX.Create(@"docs\DocumentsWithListsFontChange.docx")) | ||||
| { | { | ||||
| foreach ( FontFamily oneFontFamily in FontFamily.Families ) { | |||||
| foreach (FontFamily oneFontFamily in FontFamily.Families) | |||||
| { | |||||
| FontFamily fontFamily = oneFontFamily; | |||||
| double fontSize = 15; | |||||
| FontFamily fontFamily = oneFontFamily; | |||||
| double fontSize = 15; | |||||
| // created numbered lists | |||||
| var numberedList = document.AddList("First List Item.", 0, ListItemType.Numbered, 1); | |||||
| document.AddListItem(numberedList, "First sub list item", 1); | |||||
| document.AddListItem(numberedList, "Second List Item."); | |||||
| document.AddListItem(numberedList, "Third list item."); | |||||
| document.AddListItem(numberedList, "Nested item.", 1); | |||||
| document.AddListItem(numberedList, "Second nested item.", 1); | |||||
| // created numbered lists | |||||
| var numberedList = document.AddList("First List Item.", 0, ListItemType.Numbered, 1); | |||||
| document.AddListItem(numberedList, "First sub list item", 1); | |||||
| document.AddListItem(numberedList, "Second List Item."); | |||||
| document.AddListItem(numberedList, "Third list item."); | |||||
| document.AddListItem(numberedList, "Nested item.", 1); | |||||
| document.AddListItem(numberedList, "Second nested item.", 1); | |||||
| // created bulleted lists | |||||
| // created bulleted lists | |||||
| var bulletedList = document.AddList("First Bulleted Item.", 0, ListItemType.Bulleted); | |||||
| document.AddListItem(bulletedList, "Second bullet item"); | |||||
| document.AddListItem(bulletedList, "Sub bullet item", 1); | |||||
| document.AddListItem(bulletedList, "Second sub bullet item", 1); | |||||
| document.AddListItem(bulletedList, "Third bullet item"); | |||||
| var bulletedList = document.AddList("First Bulleted Item.", 0, ListItemType.Bulleted); | |||||
| document.AddListItem(bulletedList, "Second bullet item"); | |||||
| document.AddListItem(bulletedList, "Sub bullet item", 1); | |||||
| document.AddListItem(bulletedList, "Second sub bullet item", 1); | |||||
| document.AddListItem(bulletedList, "Third bullet item"); | |||||
| document.InsertList(bulletedList); | |||||
| document.InsertList(numberedList, fontFamily, fontSize); | |||||
| document.InsertList(bulletedList); | |||||
| document.InsertList(numberedList, fontFamily, fontSize); | |||||
| } | } | ||||
| // Save this document. | // Save this document. | ||||
| document.Save(); | document.Save(); | ||||
| using (var document = DocX.Create(@"docs\Lists.docx")) | using (var document = DocX.Create(@"docs\Lists.docx")) | ||||
| { | { | ||||
| var numberedList = document.AddList("First List Item.", 0, ListItemType.Numbered, 2); | |||||
| document.AddListItem(numberedList, "First sub list item", 1); | |||||
| var numberedList = document.AddList("First List Item.", 0, ListItemType.Numbered); | |||||
| //Add a numbered list starting at 2 | |||||
| document.AddListItem(numberedList, "Second List Item."); | document.AddListItem(numberedList, "Second List Item."); | ||||
| document.AddListItem(numberedList, "Third list item."); | document.AddListItem(numberedList, "Third list item."); | ||||
| document.AddListItem(numberedList, "Nested item.", 1); | |||||
| document.AddListItem(numberedList, "Second nested item.", 1); | |||||
| document.AddListItem(numberedList, "First sub list item", 1); | |||||
| document.AddListItem(numberedList, "Nested item.", 2); | |||||
| document.AddListItem(numberedList, "Fourth nested item."); | |||||
| var bulletedList = document.AddList("First Bulleted Item.", 0, ListItemType.Bulleted); | var bulletedList = document.AddList("First Bulleted Item.", 0, ListItemType.Bulleted); | ||||
| document.AddListItem(bulletedList, "Second bullet item"); | document.AddListItem(bulletedList, "Second bullet item"); | ||||
| document.AddListItem(bulletedList, "Sub bullet item", 1); | document.AddListItem(bulletedList, "Sub bullet item", 1); | ||||
| document.AddListItem(bulletedList, "Second sub bullet item", 1); | |||||
| document.AddListItem(bulletedList, "Second sub bullet item", 2); | |||||
| document.AddListItem(bulletedList, "Third bullet item"); | document.AddListItem(bulletedList, "Third bullet item"); | ||||
| document.InsertList(numberedList); | document.InsertList(numberedList); | ||||
| // Insert a Paragraph into the first Header. | // Insert a Paragraph into the first Header. | ||||
| Paragraph p0 = header_first.InsertParagraph(); | Paragraph p0 = header_first.InsertParagraph(); | ||||
| p0.Append("Hello First Header.").Bold(); | p0.Append("Hello First Header.").Bold(); | ||||
| // Insert a Paragraph into the odd Header. | // Insert a Paragraph into the odd Header. | ||||
| Paragraph p1 = header_odd.InsertParagraph(); | Paragraph p1 = header_odd.InsertParagraph(); | ||||
| p1.Append("Hello Odd Header.").Bold(); | p1.Append("Hello Odd Header.").Bold(); | ||||
| // Insert a Paragraph into the even Header. | // Insert a Paragraph into the even Header. | ||||
| Paragraph p2 = header_even.InsertParagraph(); | Paragraph p2 = header_even.InsertParagraph(); | ||||
| p2.Append("Hello Even Header.").Bold(); | p2.Append("Hello Even Header.").Bold(); | ||||
| static void HelloWorldKeepWithNext() | static void HelloWorldKeepWithNext() | ||||
| { | { | ||||
| // Create a Paragraph that will stay on the same page as the paragraph that comes next | |||||
| // Create a Paragraph that will stay on the same page as the paragraph that comes next | |||||
| Console.WriteLine("\tHelloWorldKeepWithNext()"); | Console.WriteLine("\tHelloWorldKeepWithNext()"); | ||||
| // Create a new document. | |||||
| // Create a new document. | |||||
| using (DocX document = DocX.Create("docs\\HelloWorldKeepWithNext.docx")) | using (DocX document = DocX.Create("docs\\HelloWorldKeepWithNext.docx")) | ||||
| { | |||||
| // Create a new Paragraph with the text "Hello World". | |||||
| Paragraph p = document.InsertParagraph("Hello World."); | |||||
| p.KeepWithNext(); | |||||
| document.InsertParagraph("Previous paragraph will appear on the same page as this paragraph"); | |||||
| // Save all changes made to this document. | |||||
| document.Save(); | |||||
| Console.WriteLine("\tCreated: docs\\HelloWorldKeepWithNext.docx\n"); | |||||
| } | |||||
| { | |||||
| // Create a new Paragraph with the text "Hello World". | |||||
| Paragraph p = document.InsertParagraph("Hello World."); | |||||
| p.KeepWithNext(); | |||||
| document.InsertParagraph("Previous paragraph will appear on the same page as this paragraph"); | |||||
| // Save all changes made to this document. | |||||
| document.Save(); | |||||
| Console.WriteLine("\tCreated: docs\\HelloWorldKeepWithNext.docx\n"); | |||||
| } | |||||
| } | } | ||||
| static void HelloWorldKeepLinesTogether() | static void HelloWorldKeepLinesTogether() | ||||
| { | { | ||||
| Console.WriteLine("\tCreated: docs\\HelloWorldKeepLinesTogether.docx\n"); | Console.WriteLine("\tCreated: docs\\HelloWorldKeepLinesTogether.docx\n"); | ||||
| } | } | ||||
| } | } | ||||
| static void LargeTable() | static void LargeTable() | ||||
| { | { | ||||
| Console.WriteLine("\tLargeTable()"); | Console.WriteLine("\tLargeTable()"); | ||||
| Console.WriteLine("\tCreated: docs\\LargeTable.docx\n"); | Console.WriteLine("\tCreated: docs\\LargeTable.docx\n"); | ||||
| } | } | ||||
| static void TableWithSpecifiedWidths() | static void TableWithSpecifiedWidths() | ||||
| { | { | ||||
| Console.WriteLine("\tTableSpecifiedWidths()"); | Console.WriteLine("\tTableSpecifiedWidths()"); | ||||
| /// <summary> | /// <summary> | ||||
| /// Create a document with two pictures. One picture is inserted normal way, the other one with rotation | /// Create a document with two pictures. One picture is inserted normal way, the other one with rotation | ||||
| /// </summary> | /// </summary> | ||||
| static void HelloWorldAddPictureToWord() { | |||||
| Console.WriteLine("\tHelloWorldAddPictureToWord()"); | |||||
| static void HelloWorldAddPictureToWord() | |||||
| { | |||||
| Console.WriteLine("\tHelloWorldAddPictureToWord()"); | |||||
| // Create a document. | |||||
| using (DocX document = DocX.Create(@"docs\HelloWorldAddPictureToWord.docx")) | |||||
| { | |||||
| // Add an image into the document. | |||||
| RelativeDirectory rd = new RelativeDirectory(); // prepares the files for testing | |||||
| rd.Up(2); | |||||
| Image image = document.AddImage(rd.Path + @"\images\logo_template.png"); | |||||
| // Create a picture (A custom view of an Image). | |||||
| Picture picture = image.CreatePicture(); | |||||
| picture.Rotation = 10; | |||||
| picture.SetPictureShape(BasicShapes.cube); | |||||
| // Insert a new Paragraph into the document. | |||||
| Paragraph title = document.InsertParagraph().Append("This is a test for a picture").FontSize(20).Font(new FontFamily("Comic Sans MS")); | |||||
| title.Alignment = Alignment.center; | |||||
| // Insert a new Paragraph into the document. | |||||
| Paragraph p1 = document.InsertParagraph(); | |||||
| // Append content to the Paragraph | |||||
| p1.AppendLine("Just below there should be a picture ").Append("picture").Bold().Append(" inserted in a non-conventional way."); | |||||
| p1.AppendLine(); | |||||
| p1.AppendLine("Check out this picture ").AppendPicture(picture).Append(" its funky don't you think?"); | |||||
| p1.AppendLine(); | |||||
| // Insert a new Paragraph into the document. | |||||
| Paragraph p2 = document.InsertParagraph(); | |||||
| // Append content to the Paragraph. | |||||
| p2.AppendLine("Is it correct?"); | |||||
| p2.AppendLine(); | |||||
| // Lets add another picture (without the fancy stuff) | |||||
| Picture pictureNormal = image.CreatePicture(); | |||||
| Paragraph p3 = document.InsertParagraph(); | |||||
| p3.AppendLine("Lets add another picture (without the fancy rotation stuff)"); | |||||
| p3.AppendLine(); | |||||
| p3.AppendPicture(pictureNormal); | |||||
| // Save this document. | |||||
| document.Save(); | |||||
| Console.WriteLine("\tCreated: docs\\HelloWorldAddPictureToWord.docx\n"); | |||||
| } | |||||
| } | |||||
| // Create a document. | |||||
| using (DocX document = DocX.Create(@"docs\HelloWorldAddPictureToWord.docx")) | |||||
| { | |||||
| // Add an image into the document. | |||||
| RelativeDirectory rd = new RelativeDirectory(); // prepares the files for testing | |||||
| rd.Up(2); | |||||
| Image image = document.AddImage(rd.Path + @"\images\logo_template.png"); | |||||
| // Create a picture (A custom view of an Image). | |||||
| Picture picture = image.CreatePicture(); | |||||
| picture.Rotation = 10; | |||||
| picture.SetPictureShape(BasicShapes.cube); | |||||
| // Insert a new Paragraph into the document. | |||||
| Paragraph title = document.InsertParagraph().Append("This is a test for a picture").FontSize(20).Font(new FontFamily("Comic Sans MS")); | |||||
| title.Alignment = Alignment.center; | |||||
| // Insert a new Paragraph into the document. | |||||
| Paragraph p1 = document.InsertParagraph(); | |||||
| // Append content to the Paragraph | |||||
| p1.AppendLine("Just below there should be a picture ").Append("picture").Bold().Append(" inserted in a non-conventional way."); | |||||
| p1.AppendLine(); | |||||
| p1.AppendLine("Check out this picture ").AppendPicture(picture).Append(" its funky don't you think?"); | |||||
| p1.AppendLine(); | |||||
| // Insert a new Paragraph into the document. | |||||
| Paragraph p2 = document.InsertParagraph(); | |||||
| // Append content to the Paragraph. | |||||
| p2.AppendLine("Is it correct?"); | |||||
| p2.AppendLine(); | |||||
| // Lets add another picture (without the fancy stuff) | |||||
| Picture pictureNormal = image.CreatePicture(); | |||||
| Paragraph p3 = document.InsertParagraph(); | |||||
| p3.AppendLine("Lets add another picture (without the fancy rotation stuff)"); | |||||
| p3.AppendLine(); | |||||
| p3.AppendPicture(pictureNormal); | |||||
| // Save this document. | |||||
| document.Save(); | |||||
| Console.WriteLine("\tCreated: docs\\HelloWorldAddPictureToWord.docx\n"); | |||||
| } | |||||
| } | |||||
| } | } |