private IList<OpenXmlCompositeElement> ConvertContentToParagraphs(MainDocumentPart mainDocumentPart) { var converter = new HtmlConverter(mainDocumentPart) { RenderPreAsTable = false }; return converter.Parse(_content .Replace("<img", "<img style=\"max-width:550;\"") .Replace("<pre><code>", "<p class=\"codesnippet\"><pre>") .Replace("</code></pre>", "</pre></p>") .Replace("<code>", "<span class=\"inlinecodesnippet\">") .Replace("</code>", "</span>")); }
/// <summary> /// Gets the type of the name to value collection from element for. /// </summary> /// <param name="mainDocumentPart">The main document part.</param> /// <param name="elementName">Name of the element.</param> /// <param name="forNodeType">Type of for node.</param> /// <returns></returns> public Dictionary<string, string> GetNameToValueCollectionFromElementForType(MainDocumentPart mainDocumentPart, string elementName, NodeType forNodeType) { Dictionary<string, string> nameToValueCollection = new Dictionary<string, string>(); CustomXmlPart customXmlPart = this.customXmlPartCore.GetCustomXmlPart(mainDocumentPart); if (customXmlPart != null) { XElement element = this.customXmlPartCore.GetFirstElementFromCustomXmlPart(customXmlPart, elementName); if (element != null) { if (forNodeType == NodeType.Element) { foreach (XElement elem in element.Elements()) { nameToValueCollection.Add(elem.Name.LocalName, elem.Nodes().Where(node => node.NodeType == XmlNodeType.Element).FirstOrDefault().ToString()); } } else if (forNodeType == NodeType.Attribute) { foreach (XAttribute attr in element.Attributes()) { nameToValueCollection.Add(attr.Name.LocalName, attr.Value); } } } } return nameToValueCollection; }
/// <summary> /// Refreshes the charts. /// </summary> /// <param name="mainDocumentPart">The main document part.</param> protected override void RefreshCharts(MainDocumentPart mainDocumentPart) { if (mainDocumentPart != null) { foreach (ChartPart chartPart in mainDocumentPart.ChartParts) { Chart chart = chartPart.ChartSpace.Elements<Chart>().FirstOrDefault(); if (chart != null) { DocumentFormat.OpenXml.Drawing.Charts.ScatterChart scatterChart = chart.Descendants<DocumentFormat.OpenXml.Drawing.Charts.ScatterChart>().FirstOrDefault(); DocumentFormat.OpenXml.Drawing.Charts.Line3DChart lineChart = chart.Descendants<DocumentFormat.OpenXml.Drawing.Charts.Line3DChart>().FirstOrDefault(); if (scatterChart != null) { ScatterChartEx chartEx = new ScatterChartEx(chartPart, this.scatterChartData); chartEx.Refresh(); } if (lineChart != null) { Line3DChartEx chartEx = new Line3DChartEx(chartPart, this.lineChartData); chartEx.Refresh(); } } chartPart.ChartSpace.Save(); } } }
/// <summary> /// Gets the custom XML part. /// </summary> /// <param name="mainDocumentPart">The main document part.</param> /// <returns></returns> public CustomXmlPart GetCustomXmlPart(MainDocumentPart mainDocumentPart) { if (mainDocumentPart == null) { throw new ArgumentNullException("mainDocumentPart"); } CustomXmlPart result = null; foreach (CustomXmlPart part in mainDocumentPart.CustomXmlParts) { using (XmlTextReader reader = new XmlTextReader(part.GetStream(FileMode.Open, FileAccess.Read))) { reader.MoveToContent(); bool exists = reader.NamespaceURI.Equals(this.namespaceUri); if (exists) { result = part; break; } } } return result; }
public override void AppendTo(OpenXmlElement openXmlNode, MainDocumentPart mainDocumentPart) { _mainDocumentPart = mainDocumentPart; var imagePart = CreateImagePart(); openXmlNode.Append(CreateImageElement(mainDocumentPart.GetIdOfPart(imagePart), Path.GetFileName(_content))); }
public override void InsertAfter(OpenXmlElement openXmlNode, MainDocumentPart mainDocumentPart) { _mainDocumentPart = mainDocumentPart; var imagePart = CreateImagePart(); openXmlNode.InsertAfterSelf(CreateImageElement(mainDocumentPart.GetIdOfPart(imagePart), Path.GetFileName(_content))); }
public NumberingListStyleCollection(MainDocumentPart mainPart) { this.mainPart = mainPart; this.absNumId = -1; this.numInstances = new Stack<Int32>(); InitNumberingIds(); }
/// <summary> /// Get ContentControl from word document /// </summary> /// <param name="pDoc">Document mainpart</param> /// <param name="pTag">ContentControl tag to find</param> /// <returns>The ContentControl</returns> public static SdtBlock GetContentControl(MainDocumentPart pDoc, string pTag) { SdtBlock cc = pDoc.Document.Body.Descendants<SdtBlock>().Where (r => r.SdtProperties.GetFirstChild<Tag>().Val == pTag).Single(); return cc; }
/// <summary> /// Generates a hyperlink and embed it /// in a paragraph tag /// </summary> /// <param name="mainDocPart">The main doc part.</param> /// <param name="hyperLink">The hyper link.</param> /// <returns></returns> public static Paragraph GenerateParagraphWithHyperLink(MainDocumentPart mainDocPart, String hyperLink) { //this will be display as //the text String urlLabel = hyperLink; //build the hyperlink //file:// ensure that document does not corrupt System.Uri uri = new Uri(@"file://" + hyperLink); //add it to the document HyperlinkRelationship rel = mainDocPart.AddHyperlinkRelationship(uri, true); //get the hyperlink id string relationshipId = rel.Id; //create the new paragraph tag Paragraph newParagraph = new Paragraph( new DocumentFormat.OpenXml.Wordprocessing.Hyperlink( new ProofError() { Type = ProofingErrorValues.GrammarStart }, new DocumentFormat.OpenXml.Wordprocessing.Run( new DocumentFormat.OpenXml.Wordprocessing.RunProperties( new RunStyle() { Val = "Hyperlink" }), new DocumentFormat.OpenXml.Wordprocessing.Text(urlLabel) )) { History = OnOffValue.FromBoolean(true), Id = relationshipId }); return newParagraph; }
/// <summary> /// Open an Word XML document /// </summary> /// <param name="docname">name of the document to be opened</param> public void OpenTheDocuemnt(string docname) { // open the word docx wordProcessingDocument = WordprocessingDocument.Open(docname, true); // get the Main Document part mainDocPart = wordProcessingDocument.MainDocumentPart; }
public override void AppendTo(OpenXmlElement openXmlNode, MainDocumentPart mainDocumentPart) { var paragraphs = ConvertContentToParagraphs(mainDocumentPart); foreach (var paragraph in paragraphs) { openXmlNode.Append(paragraph); } }
public static Styles CreateStyles(MainDocumentPart mainPart) { StyleDefinitionsPart styleDefinitionsPart = mainPart.AddNewPart<StyleDefinitionsPart>(); Styles styles = new Styles(); styleDefinitionsPart.Styles = styles; //styles.Save(); return styles; }
internal WordprocessingDocument CreateDocument(String fileName) { docxFile = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document); mainPart = docxFile.AddMainDocumentPart(); docxFile.MainDocumentPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document(new Body()); body = docxFile.MainDocumentPart.Document.Body; return docxFile; }
public override void AppendTo(OpenXmlElement openXmlNode, MainDocumentPart mainDocumentPart) { var text = _newParagraph ? (OpenXmlElement)new Paragraph(new Run(new Text(_content))) : (OpenXmlElement)new Run(new Text(_content)); openXmlNode.Append(text); }
internal HtmlDocumentStyle(MainDocumentPart mainPart) { PrepareStyles(mainPart); tableStyle = new TableStyleCollection(this); runStyle = new RunStyleCollection(this); paraStyle = new ParagraphStyleCollection(this); this.QuoteCharacters = QuoteChars.IE; this.mainPart = mainPart; }
public static IEnumerable <Section> SplitToSections( this Pack.MainDocumentPart mainDocument, IStyleFactory styleFactory) { var sections = mainDocument.Document.Body .SplitToSectionsCore(mainDocument, styleFactory) .ToArray(); return(sections); }
public override void InsertAfter(OpenXmlElement openXmlNode, MainDocumentPart mainDocumentPart) { var paragraphs = ConvertContentToParagraphs(mainDocumentPart); var insertPoint = openXmlNode; foreach (var paragraph in paragraphs) { insertPoint.InsertAfterSelf(paragraph); insertPoint = paragraph; } }
/// <summary> /// Constructor. /// </summary> /// <param name="mainPart">The mainDocumentPart of a document where to write the conversion to.</param> /// <remarks>We preload some configuration from inside the document such as style, bookmarks,...</remarks> public HtmlConverter(MainDocumentPart mainPart) { this.mainPart = mainPart; this.RenderPreAsTable = true; this.ImageProcessing = ImageProcessing.AutomaticDownload; this.knownTags = InitKnownTags(); this.htmlStyles = new HtmlDocumentStyle(mainPart); this.knownImageParts = new Dictionary<Uri, CachedImagePart>(); this.WebProxy = new WebProxy(); }
public void GenerateTextContent(MainDocumentPart mainPart, Client client, string contentFile) { GetContent(client, contentFile); string customXml = File.ReadAllText(destinationXml); replaceCustomXML(mainPart, customXml); mainPart.Document.Save(); //Delete the temp files //File.Delete(tempFile); //File.Delete(destinationXml); }
private OpenXmlElement GetHeaderTextElement(MainDocumentPart mainDocumentPart) { var paragraph = new Paragraph(new Run(new Text(_content))); var styleId = GetStyleIdbyName(mainDocumentPart, string.Format("Heading {0}", _navigationLevel)); if (!string.IsNullOrEmpty(styleId)) { paragraph.ParagraphProperties = new ParagraphProperties(new ParagraphStyleId() { Val = styleId }); } return paragraph; }
/// <summary> /// Removes the custom XML part. /// </summary> /// <param name="mainDocumentPart">The main part.</param> /// <param name="customXmlPart">The custom XML part.</param> public static void RemoveCustomXmlPart(MainDocumentPart mainDocumentPart, CustomXmlPart customXmlPart) { if (mainDocumentPart == null) { throw new ArgumentNullException("mainDocumentPart"); } if (customXmlPart != null) { RemoveCustomXmlParts(mainDocumentPart, new List<CustomXmlPart>(new[] { customXmlPart })); } }
private NumberingDefinitionsPart FindOrCreateNumberingDefinitionPart(MainDocumentPart mainDocumentPart) { NumberingDefinitionsPart result = null; var existingDefinitions = mainDocumentPart.GetPartsOfType<NumberingDefinitionsPart>(); foreach (NumberingDefinitionsPart existingDefinition in existingDefinitions) { result = existingDefinition; } if (result == null) result = mainDocumentPart.AddNewPart<NumberingDefinitionsPart>(); return result; }
public DocumentBuilder(WordprocessingDocument document, bool isEmptyDocument) { this.document = document; if (isEmptyDocument) { main = document.AddMainDocumentPart(); main.Document = new Document(); body = main.Document.AppendChild(new Body()); InsertParagraph(); } else { throw new Exception("Manipulating existing documents is not supported."); } }
private static Section CreateSection( this IReadOnlyCollection <OpenXml.OpenXmlCompositeElement> xmlElements, Word.SectionProperties wordSectionProperties, Pack.MainDocumentPart mainDocumentPart, HeaderFooterConfiguration headerFooterConfiguration, bool isFirst, IStyleFactory styleFactory) { var imageAccessor = new ImageAccessor(mainDocumentPart); var sectionProperties = wordSectionProperties.CreateSectionProperties(mainDocumentPart, isFirst, headerFooterConfiguration); var columnsConfiguration = wordSectionProperties.CreateColumnsConfiguration(sectionProperties.PageConfiguration, sectionProperties.Margin); var sectionContents = xmlElements.SplitToSectionContents(columnsConfiguration, imageAccessor, styleFactory); var sd = new Section(sectionProperties, sectionContents, imageAccessor, styleFactory); return(sd); }
private static HeaderFooterConfiguration GetHeaderFooterConfiguration( this Word.SectionProperties wordSectionProperties, Pack.MainDocumentPart mainDocument, HeaderFooterConfiguration previousHeaderFooterConfiguration) { var hasTitlePage = wordSectionProperties.ChildsOfType <Word.TitlePage>().SingleOrDefault() .IsOn(ifOnOffTypeNull: false, ifOnOffValueNull: true); var headerRefs = wordSectionProperties .ChildsOfType <Word.HeaderReference>() .Select(fr => new HeaderFooterRef(fr.Id, fr.Type)); var footerRefs = wordSectionProperties .ChildsOfType <Word.FooterReference>() .Select(fr => new HeaderFooterRef(fr.Id, fr.Type)); return(previousHeaderFooterConfiguration.Inherited(mainDocument, hasTitlePage, headerRefs, footerRefs)); }
private static IEnumerable <Section> SplitToSectionsCore( this Word.Body body, Pack.MainDocumentPart mainDocumentPart, IStyleFactory styleFactory) { var sections = new List <Section>(); var sectionElements = new List <OpenXml.OpenXmlCompositeElement>(); var headerFooterConfiguration = HeaderFooterConfiguration.Empty; Word.SectionProperties wordSectionProperties; foreach (var e in body.RenderableChildren()) { sectionElements.Add(e); if (!(e is Word.Paragraph paragraph)) { continue; } wordSectionProperties = paragraph.GetSectionProperties(); if (wordSectionProperties == null) { continue; } var section = sectionElements.CreateSection(wordSectionProperties, mainDocumentPart, headerFooterConfiguration, sections.Count == 0, styleFactory); headerFooterConfiguration = section.HeaderFooterConfiguration; sections.Add(section); sectionElements.Clear(); } wordSectionProperties = body .ChildsOfType <Word.SectionProperties>() .Single(); var lastSection = sectionElements.CreateSection(wordSectionProperties, mainDocumentPart, headerFooterConfiguration, sections.Count == 0, styleFactory); sections.Add(lastSection); return(sections); }
internal static void ClearHeaderFooter(MainDocumentPart mdp) { mdp.DeleteParts(mdp.HeaderParts); mdp.DeleteParts(mdp.FooterParts); var hp = mdp.AddNewPart<HeaderPart>(); var fp = mdp.AddNewPart<FooterPart>(); hp.Header = new Header(); fp.Footer = new Footer(); foreach (var sps in mdp.Document.Body.Elements<SectionProperties>()) { sps.RemoveAllChildren<HeaderReference>(); sps.RemoveAllChildren<FooterReference>(); sps.PrependChild(new HeaderReference { Id = mdp.GetIdOfPart(hp) }); sps.PrependChild(new FooterReference { Id = mdp.GetIdOfPart(fp) }); } mdp.Document.Save(); }
/// <summary> /// Adds the custom XML part. /// </summary> /// <param name="mainDocumentPart">The main part.</param> /// <param name="rootElementName">Name of the root element.</param> /// <returns> /// Returns CustomXmlPart /// </returns> public CustomXmlPart AddCustomXmlPart(MainDocumentPart mainDocumentPart, string rootElementName) { if (mainDocumentPart == null) { throw new ArgumentNullException("mainDocumentPart"); } if (string.IsNullOrEmpty(rootElementName)) { throw new ArgumentNullException("rootElementName"); } XName rootElementXName = XName.Get(rootElementName, this.namespaceUri); XElement rootElement = new XElement(rootElementXName); CustomXmlPart customXmlPart = mainDocumentPart.AddCustomXmlPart(CustomXmlPartType.CustomXml); CustomXmlPropertiesPart customXmlPropertiesPart = customXmlPart.AddNewPart<CustomXmlPropertiesPart>(); GenerateCustomXmlPropertiesPartContent(customXmlPropertiesPart); WriteElementToCustomXmlPart(customXmlPart, rootElement); return customXmlPart; }
private static SectionProperties CreateSectionProperties( this Word.SectionProperties wordSectionProperties, Pack.MainDocumentPart mainDocument, bool isFirstSection, HeaderFooterConfiguration inheritHeaderFooterConfiguration) { var pageCongifuration = wordSectionProperties.GetPageConfiguration(); var pageMargin = wordSectionProperties.GetPageMargin(); var sectionMark = wordSectionProperties.ChildsOfType <Word.SectionType>().SingleOrDefault()?.Val ?? Word.SectionMarkValues.NextPage; var requiresNewPage = isFirstSection || sectionMark == Word.SectionMarkValues.NextPage; var headerFooterConfiguration = wordSectionProperties .GetHeaderFooterConfiguration(mainDocument, inheritHeaderFooterConfiguration); return(new SectionProperties( pageCongifuration, headerFooterConfiguration, pageMargin, requiresNewPage)); }
public void GenerateTextContent(MainDocumentPart mainPart, string contentFileName, Stream tempContentFile, bool fillControls) { var contents = Data.Content.GetContents(Client.StrategyID, Client.ExistingAssets).ToList(); if (fillControls) { fillContentControlsText(mainPart, contents); fillContentControlsClientData(mainPart); } else { GetContent(Client, contentFileName, tempContentFile, contents); StreamReader sr = new StreamReader(tempContentFile, Encoding.UTF8); string customXml = sr.ReadToEnd(); sr.Close(); replaceCustomXML(mainPart, customXml); } // Remove unused text Content Controls var all = Data.Content.GetAllContentIDs(Client.StrategyID); var unused = all.Except(contents.Select(c => c.ContentID)); removeUnusedContentControls(mainPart, unused); // Save doc mainPart.Document.Save(); }
/// <summary> /// Gets the type of the name to value collection from element for. /// </summary> /// <param name="mainDocumentPart">The main document part.</param> /// <param name="elementName">Name of the element.</param> /// <param name="forNodeType">Type of for node.</param> /// <returns>Returns the type of the name to value collection from element for</returns> public Dictionary<string, string> GetNameToValueCollectionFromElementForType(MainDocumentPart mainDocumentPart, string elementName, NodeType forNodeType) { var nameToValueCollection = new Dictionary<string, string>(); var customXmlPart = this.CustomXmlPartCore.GetCustomXmlPart(mainDocumentPart); if (customXmlPart != null) { var element = this.CustomXmlPartCore.GetFirstElementFromCustomXmlPart(customXmlPart, elementName); if (element != null) { switch (forNodeType) { case NodeType.Element: foreach (var elem in element.Elements()) { var firstOrDefault = elem.Nodes().FirstOrDefault(node => node.NodeType == XmlNodeType.Element); if (firstOrDefault != null) { nameToValueCollection.Add(elem.Name.LocalName, firstOrDefault.ToString()); } } break; case NodeType.Attribute: foreach (var attr in element.Attributes()) { nameToValueCollection.Add(attr.Name.LocalName, attr.Value); } break; } } } return nameToValueCollection; }
void AddAltChunk(MainDocumentPart mainPart, Word.SdtElement sdt, SPFile filename) { string altChunkId = "AltChunkId" + id; id++; byte[] byteArray = filename.OpenBinary(); AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart( AlternativeFormatImportPartType.WordprocessingML, altChunkId); using (MemoryStream mem = new MemoryStream()) { mem.Write(byteArray, 0, (int)byteArray.Length); mem.Seek(0, SeekOrigin.Begin); chunk.FeedData(mem); } Word.AltChunk altChunk = new Word.AltChunk(); altChunk.Id = altChunkId; // Replace content control with altChunk information. OpenXmlElement parent = sdt.Parent; parent.InsertAfter(altChunk, sdt); sdt.Remove(); }
/// <summary> /// Ensures the unique content control ids for main document part. /// </summary> /// <param name="mainDocumentPart">The main document part.</param> public static void EnsureUniqueContentControlIdsForMainDocumentPart(MainDocumentPart mainDocumentPart) { var contentControlIds = new List<int>(); if (mainDocumentPart == null) { return; } foreach (var part in mainDocumentPart.HeaderParts) { SetUniquecontentControlIds(part.Header, contentControlIds); part.Header.Save(); } foreach (var part in mainDocumentPart.FooterParts) { SetUniquecontentControlIds(part.Footer, contentControlIds); part.Footer.Save(); } SetUniquecontentControlIds(mainDocumentPart.Document.Body, contentControlIds); mainDocumentPart.Document.Save(); }
/// <summary> /// Sets the document properties. /// </summary> /// <param name="mainDocumentPart">The main document part.</param> /// <param name="docProperties">The doc properties.</param> protected void SetDocumentProperties(MainDocumentPart mainDocumentPart, DocumentMetadata docProperties) { if (mainDocumentPart == null) { throw new ArgumentNullException("mainDocumentPart"); } if (docProperties == null) { throw new ArgumentNullException("docProperties"); } Dictionary<string, string> idtoValues = new Dictionary<string, string>(); idtoValues.Add(DocumentTypeNodeName, string.IsNullOrEmpty(docProperties.DocumentType) ? string.Empty : docProperties.DocumentType); idtoValues.Add(DocumentVersionNodeName, string.IsNullOrEmpty(docProperties.DocumentVersion) ? string.Empty : docProperties.DocumentVersion); this.customXmlPartHelper.SetElementFromNameToValueCollectionForType(mainDocumentPart, DocumentRootNode, DocumentNode, idtoValues, NodeType.Attribute); }
/// <summary> /// Saves the data content to data bound controls data store. /// </summary> /// <param name="mainDocumentPart">The main document part.</param> protected void SaveDataToDataBoundControlsDataStore(MainDocumentPart mainDocumentPart) { string dataContextAsXml = this.SerializeDataContextToXml(); Dictionary<string, string> nameToValueCollection = new Dictionary<string, string>(); nameToValueCollection.Add(DataNode, dataContextAsXml); this.customXmlPartHelper.SetElementFromNameToValueCollectionForType(mainDocumentPart, DocumentRootNode, DataBoundControlsDataStoreNode, nameToValueCollection, NodeType.Element); }