/// <summary> /// Set content of MainDocumentPart. /// </summary> /// <param name="part">MainDocumentPart</param> public void SetMainDocumentContent(MainDocumentPart part) { using (Stream stream = part.GetStream()) { CreateWordProcessingML(stream); } }
/// <summary> /// Create a new documnent. /// </summary> /// <param name="createLocation">The location and path to create the document.</param> protected void CreateDocument(string createLocation) { _templateLocation = createLocation; _createLocation = createLocation; // Create the new doucument _document = WordprocessingDocument.Create(createLocation, WordprocessingDocumentType.Document); // Add a main document part. _documentPart = _document.AddMainDocumentPart(); // Create the document structure and add some text. _documentPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document(); NameTable nt = new NameTable(); _xmlNamespaceManager = new XmlNamespaceManager(nt); _xmlNamespaceManager.AddNamespace("w", nameSpace); NameTable ntr = new NameTable(); _xmlNamespaceManagerRelationships = new XmlNamespaceManager(ntr); _xmlNamespaceManagerRelationships.AddNamespace("r", nameSpaceRelationships); // Get the document part from the package. _xDocument = new XmlDocument(); // Load the XML in the part into an XmlDocument instance. _xDocument.Load(_documentPart.GetStream()); }
static void Main(string[] args) { WordprocessingDocument doc = WordprocessingDocument.Create(@"C:\tmp\testOpenXmlLib.docx", OpenXmlPackage.DocumentType.Document); MainDocumentPart part = doc.MainDocumentPart; const string docXml = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <w:document xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main""> <w:body><w:p><w:r><w:t>Hello world!</w:t></w:r></w:p></w:body> </w:document>"; Stream stream = part.GetStream(); byte[] buf = (new UTF8Encoding()).GetBytes(docXml); stream.Write(buf, 0, buf.Length); doc.Close(); PresentationDocument presentation = PresentationDocument.Create(@"C:\tmp\testOpenXmlLib.pptx", OpenXmlPackage.DocumentType.Document); PresentationPart presentationPart = presentation.PresentationPart; SlidePart slide = presentationPart.AddSlidePart(); string presentationXml = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <p:presentation xmlns:a=""http://schemas.openxmlformats.org/drawingml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"" xmlns:p=""http://schemas.openxmlformats.org/presentationml/2006/main"" saveSubsetFonts=""1""> <p:sldIdLst> <p:sldId id=""256"" r:id=""" + slide.RelIdToString + @"""/> </p:sldIdLst> </p:presentation>"; stream = presentationPart.GetStream(); buf = (new UTF8Encoding()).GetBytes(presentationXml); stream.Write(buf, 0, buf.Length); string slideXml = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <p:sld xmlns:a=""http://schemas.openxmlformats.org/drawingml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"" xmlns:p=""http://schemas.openxmlformats.org/presentationml/2006/main""> </p:sld>"; stream = slide.GetStream(); buf = (new UTF8Encoding()).GetBytes(slideXml); stream.Write(buf, 0, buf.Length); presentation.Close(); }
public static void ProjectThemeApproving(Student studentInfo, string projectTitle, string projectManager, string path) { using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(path, WordprocessingDocumentType.Document)) { // Set the content of the document so that Word can open it. MainDocumentPart mainPart = wordDoc.AddMainDocumentPart(); using (Stream stream = mainPart.GetStream()) { string formatted = string.Format(openXmlCode1, studentInfo.Group, 2, studentInfo.Faculty, studentInfo.Lastname + " " + studentInfo.Firstname + " " + studentInfo.Patronymic, projectTitle, DateTime.Today.ToShortDateString(), DateTime.Today.ToShortDateString(), studentInfo.Fullname, projectManager); byte[] buf = (new UTF8Encoding()).GetBytes(formatted); stream.Write(buf, 0, buf.Length); } } }
public static XDocument GetXDocument(this MainDocumentPart mainPart) { var document = XDocument.Load( XmlReader.Create( new StreamReader(mainPart.GetStream()) ) ); foreach (var part in mainPart.Parts) { if (part.OpenXmlPart is ImagePart) { continue; } document.Root.Add(part.OpenXmlPart.GetXElement()); } return(document); }
internal OpenXmlElement Convert(string html, bool returnInvalid = false) { string xmlContent = Transform(html); xmlContent = this.CleanupXml(xmlContent); using (MemoryStream mem = new MemoryStream()) { using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(mem, WordprocessingDocumentType.Document, true)) { // Add a main document part. MainDocumentPart newPart = wordDocument.AddMainDocumentPart(); using (StreamWriter sw = new StreamWriter(newPart.GetStream())) { sw.Write(xmlContent); } // Validate the parsed content. If validation fails return the content in plain-text, wrapped in a para OpenXmlValidator validator = new OpenXmlValidator(FileFormatVersions.Office2010); IEnumerable <ValidationErrorInfo> validationErrors = validator.Validate(newPart.Document.Body); var filteredErrors = validationErrors.Where(y => y.Description != "The 'http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing:editId' attribute is not declared."); if (filteredErrors.Count() > 0) { Logging.Log.For(this).Error("{0} Validation errors on OpenXml converted from HTML", filteredErrors.Count()); if (!returnInvalid) { return(new Body( new Paragraph( new Run( new Text() { Text = html })))); } } return(newPart.Document.Body); } } }
/// <summary> /// Open a document with the template. /// </summary> /// <param name="templateLocation">The document template location.</param> /// <param name="createLocation">The document creation location.</param> protected void OpenDocument(string templateLocation, string createLocation) { _templateLocation = templateLocation; _createLocation = createLocation; System.IO.File.Copy(templateLocation, createLocation, true); _document = WordprocessingDocument.Open(createLocation, true); _documentPart = _document.MainDocumentPart; NameTable nt = new NameTable(); _xmlNamespaceManager = new XmlNamespaceManager(nt); _xmlNamespaceManager.AddNamespace("w", nameSpace); NameTable ntr = new NameTable(); _xmlNamespaceManagerRelationships = new XmlNamespaceManager(ntr); _xmlNamespaceManagerRelationships.AddNamespace("r", nameSpaceRelationships); // Get the document part from the package. _xDocument = new XmlDocument(); // Load the XML in the part into an XmlDocument instance. _xDocument.Load(_documentPart.GetStream()); }
/// <summary> /// Saves the current document. /// </summary> /// <param name="location">The location where the document is to be saved.</param> protected void SaveDocument(string location) { // Save the document to it-self _xDocument.Save(_documentPart.GetStream(System.IO.FileMode.Create, FileAccess.ReadWrite)); }
public static void FillBookmarksUsingOpenXml(string sourceDoc, string destDoc, Dictionary <string, string> bookmarkData) { string wordmlNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; // Make a copy of the template file. File.Copy(sourceDoc, destDoc, true); //Open the document as an Open XML package and extract the main document part. using (WordprocessingDocument wordPackage = WordprocessingDocument.Open(destDoc, true)) { MainDocumentPart part = wordPackage.MainDocumentPart; //Setup the namespace manager so you can perform XPath queries //to search for bookmarks in the part. NameTable nt = new NameTable(); XmlNamespaceManager nsManager = new XmlNamespaceManager(nt); nsManager.AddNamespace("w", wordmlNamespace); //Load the part's XML into an XmlDocument instance. XmlDocument xmlDoc = new XmlDocument(nt); xmlDoc.Load(part.GetStream()); //Iterate through the bookmarks. foreach (KeyValuePair <string, string> bookmarkDataVal in bookmarkData) { var bookmarks = from bm in part.Document.Body.Descendants <BookmarkStart>() select bm; foreach (var bookmark in bookmarks) { if (bookmark.Name == bookmarkDataVal.Key) { Run bookmarkText = bookmark.NextSibling <Run>(); string[] parts = Regex.Split(bookmarkDataVal.Value, Environment.NewLine); if (bookmarkText != null) // if the bookmark has text replace it { bookmarkText.GetFirstChild <Text>().Text = bookmarkDataVal.Value; } else // otherwise append new text immediately after it { var parent = bookmark.Parent; // bookmark's parent element Paragraph p = new Paragraph(); ParagraphProperties pp = new ParagraphProperties(); pp.Justification = new Justification() { Val = JustificationValues.Left }; // Add paragraph properties to your paragraph p.Append(pp); Text text = new Text(bookmarkDataVal.Value); //string[] parts = Regex.Split(bookmarkDataVal.Value,Environment.NewLine); Run run = new Run(new RunProperties()); List <string> rows = parts.Where(pr => pr != "").ToList(); foreach (string s in rows) { run.Append(new Text(s)); run.Append(new Break()); } p.Append(run); ((Paragraph)bookmark.Parent).InsertAfterSelf(p); // insert after bookmark parent //parent.Append(run); } //bk.Remove(); // we don't want the bookmark anymore } } } //Write the changes back to the document part. xmlDoc.Save(wordPackage.MainDocumentPart.GetStream(FileMode.Create)); } }