public static OpenXmlPowerToolsDocument Insert(OpenXmlPowerToolsDocument doc, IEnumerable <string> certificateList) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (Package package = streamDoc.GetPackage()) { foreach (string digitalCertificate in certificateList) { X509Certificate x509Certificate = X509Certificate2.CreateFromCertFile(digitalCertificate); PackageDigitalSignatureManager digitalSigntaureManager = new PackageDigitalSignatureManager(package); digitalSigntaureManager.CertificateOption = CertificateEmbeddingOption.InSignaturePart; System.Collections.Generic.List <Uri> partsToSign = new System.Collections.Generic.List <Uri>(); //Adds each part to the list, except relationships parts. foreach (PackagePart openPackagePart in package.GetParts()) { if (!PackUriHelper.IsRelationshipPartUri(openPackagePart.Uri)) { partsToSign.Add(openPackagePart.Uri); } } List <PackageRelationshipSelector> relationshipSelectors = new List <PackageRelationshipSelector>(); //Creates one selector for each package-level relationship, based on id foreach (PackageRelationship relationship in package.GetRelationships()) { PackageRelationshipSelector relationshipSelector = new PackageRelationshipSelector(relationship.SourceUri, PackageRelationshipSelectorType.Id, relationship.Id); relationshipSelectors.Add(relationshipSelector); } digitalSigntaureManager.Sign(partsToSign, x509Certificate, relationshipSelectors); } } return(streamDoc.GetModifiedDocument()); } }
/// <summary> /// Apply a cell style to a specific cell /// </summary> /// <param name="worksheet">worksheet containing the cell to be affected</param> /// <param name="fromColumn">Starting Cell Column</param> /// <param name="toColumn">Ending Cell Column</param> /// <param name="fromRow">Starting Cell Row</param> /// <param name="toRow">Ending Cell Row</param> /// <param name="cellStyle">Cell Style</param> public static OpenXmlPowerToolsDocument SetCellStyle(SmlDocument doc, string worksheetName, short fromColumn, short toColumn, int fromRow, int toRow, string cellStyle) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (SpreadsheetDocument document = streamDoc.GetSpreadsheetDocument()) { WorksheetPart worksheet = Get(document, worksheetName); XDocument worksheetXDocument = XDocument.Load(new XmlTextReader(worksheet.GetStream())); for (int row = fromRow; row <= toRow; row++) { for (short col = fromColumn; col <= toColumn; col++) { XElement cellXelement = GetCell(worksheetXDocument, col, row); cellXelement.SetAttributeValue("s", SpreadSheetStyleAccessor.GetCellStyleIndex(document, cellStyle)); } } XmlWriter worksheetWriter = XmlTextWriter.Create(worksheet.GetStream(System.IO.FileMode.Create)); worksheetXDocument.WriteTo(worksheetWriter); worksheetWriter.Flush(); worksheetWriter.Close(); } return(streamDoc.GetModifiedDocument()); } }
public WmlDocument(WmlDocument other, params XElement[] replacementParts) : base(other) { using (var streamDoc = new OpenXmlMemoryStreamDocument(this)) { using (Package package = streamDoc.GetPackage()) { foreach (XElement replacementPart in replacementParts) { XAttribute uriAttribute = replacementPart.Attribute(PtOpenXml.Uri); if (uriAttribute == null) { throw new OpenXmlPowerToolsException("Replacement part does not contain a Uri as an attribute"); } string uri = uriAttribute.Value; PackagePart part = package.GetParts().FirstOrDefault(p => p.Uri.ToString() == uri); using (Stream partStream = part.GetStream(FileMode.Create, FileAccess.Write)) using (XmlWriter partXmlWriter = XmlWriter.Create(partStream)) replacementPart.Save(partXmlWriter); } } DocumentByteArray = streamDoc.GetModifiedDocument().DocumentByteArray; } }
/// <summary> /// Sets the document theme /// </summary> /// <param name="theme">Theme package</param> public static OpenXmlPowerToolsDocument SetTheme(WmlDocument doc, OpenXmlPowerToolsDocument themeDoc) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { using (OpenXmlMemoryStreamDocument themeStream = new OpenXmlMemoryStreamDocument(themeDoc)) using (Package theme = themeStream.GetPackage()) { // Gets the theme manager part PackageRelationship themeManagerRelationship = theme.GetRelationshipsByType(mainDocumentRelationshipType).FirstOrDefault(); if (themeManagerRelationship != null) { PackagePart themeManagerPart = theme.GetPart(themeManagerRelationship.TargetUri); // Gets the theme main part PackageRelationship themeRelationship = themeManagerPart.GetRelationshipsByType(themeRelationshipType).FirstOrDefault(); if (themeRelationship != null) { PackagePart themePart = theme.GetPart(themeRelationship.TargetUri); XDocument newThemeDocument = XDocument.Load(XmlReader.Create(themePart.GetStream(FileMode.Open, FileAccess.Read))); // Removes existing theme part from document if (document.MainDocumentPart.ThemePart != null) { document.MainDocumentPart.DeletePart(document.MainDocumentPart.ThemePart); } // Creates a new theme part ThemePart documentThemePart = document.MainDocumentPart.AddNewPart <ThemePart>(); var embeddedItems = newThemeDocument .Descendants() .Attributes(relationshipns + "embed"); foreach (PackageRelationship imageRelationship in themePart.GetRelationships()) { // Adds an image part to the theme part and stores contents inside PackagePart imagePart = theme.GetPart(imageRelationship.TargetUri); ImagePart newImagePart = documentThemePart.AddImagePart(GetImagePartType(imagePart.ContentType)); newImagePart.FeedData(imagePart.GetStream(FileMode.Open, FileAccess.Read)); // Updates relationship references into the theme XDocument XAttribute relationshipAttribute = embeddedItems.FirstOrDefault(e => e.Value == imageRelationship.Id); if (relationshipAttribute != null) { relationshipAttribute.Value = documentThemePart.GetIdOfPart(newImagePart); } } documentThemePart.PutXDocument(newThemeDocument); } } } } return(streamDoc.GetModifiedDocument()); } }
/// <summary> /// Sets the document background color /// </summary> /// <param name="colorValue">String representation of the hexadecimal RGB color</param> public static OpenXmlPowerToolsDocument SetColor(WmlDocument doc, string colorValue) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { XDocument mainDocument = document.MainDocumentPart.GetXDocument(); // If the background element already exists, deletes it XElement backgroundElement = BackgroundElement(document); if (backgroundElement != null) { backgroundElement.Remove(); } mainDocument.Root.AddFirst( new XElement(ns + "background", new XAttribute(ns + "color", colorValue) ) ); // Enables background displaying by adding "displayBackgroundShape" tag if (SettingAccessor.DisplayBackgroundShapeElements(document) == null) { SettingAccessor.AddBackgroundShapeElement(document); } document.MainDocumentPart.PutXDocument(); } return(streamDoc.GetModifiedDocument()); } }
/// <summary> /// Set a new header in a document /// </summary> /// <param name="header">XDocument containing the header to add in the document</param> /// <param name="type">The header part type</param> public static OpenXmlPowerToolsDocument SetHeader(WmlDocument doc, XDocument header, HeaderType type, int sectionIndex) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { // Removes the reference in the document.xml and the header part if those already // exist XElement headerReferenceElement = GetHeaderReference(document, type, sectionIndex); if (headerReferenceElement != null) { GetHeaderPart(document, type, sectionIndex).RemovePart(); headerReferenceElement.Remove(); } // Add the new header HeaderPart headerPart = document.MainDocumentPart.AddNewPart <HeaderPart>(); headerPart.PutXDocument(header); // Creates the relationship of the header inside the section properties in the document string relID = document.MainDocumentPart.GetIdOfPart(headerPart); AddHeaderReference(document, type, relID, sectionIndex); // add in the settings part the EvendAndOddHeaders. this element // allow to see the odd and even headers and headers in the document. SettingAccessor.AddEvenAndOddHeadersElement(document); } return(streamDoc.GetModifiedDocument()); } }
/// <summary> /// Inserts Xml markup representing format attributes inside a specific paragraph or paragraph run /// </summary> /// <param name="document">Document to insert formatting Xml tags</param> /// <param name="xpathInsertionPoint">Paragraph or paragraph run to set format</param> /// <param name="content">Formatting tags</param> public static OpenXmlPowerToolsDocument Insert(WmlDocument doc, string xpathInsertionPoint, string content) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { XDocument xDocument = document.MainDocumentPart.GetXDocument(); XmlDocument xmlMainDocument = new XmlDocument(); xmlMainDocument.Load(xDocument.CreateReader()); XmlNamespaceManager namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"); XmlNodeList insertionPoints = xmlMainDocument.SelectNodes(xpathInsertionPoint, namespaceManager); if (insertionPoints.Count == 0) { throw new ArgumentException("The xpath query did not return a valid location."); } foreach (XmlNode insertionPoint in insertionPoints) { XmlNode propertiesElement = insertionPoint.SelectSingleNode(@"w:pPr|w:rPr", namespaceManager); if (insertionPoint.Name == "w:p") { // Checks if the rPr or pPr element exists if (propertiesElement == null) { propertiesElement = xmlMainDocument.CreateElement("w", "pPr", namespaceManager.LookupNamespace("w")); insertionPoint.PrependChild(propertiesElement); } } else if (insertionPoint.Name == "w:r") { // Checks if the rPr or pPr element exists if (propertiesElement == null) { propertiesElement = xmlMainDocument.CreateElement("w", "rPr", namespaceManager.LookupNamespace("w")); insertionPoint.PrependChild(propertiesElement); } } if (propertiesElement != null) { propertiesElement.InnerXml += content; } else { throw new ArgumentException("Specified xpath query result is not a valid location to place a formatting markup"); } } XDocument xNewDocument = new XDocument(); using (XmlWriter xWriter = xNewDocument.CreateWriter()) xmlMainDocument.WriteTo(xWriter); document.MainDocumentPart.PutXDocument(xNewDocument); } return(streamDoc.GetModifiedDocument()); } }
/// <summary> /// Set the width for a range of columns /// </summary> /// <param name="worksheet">Worksheet containing the columns to be affected</param> /// <param name="fromColumn">Initial column to affect</param> /// <param name="toColumn">Final column to affect</param> /// <param name="width">Column width</param> public static OpenXmlPowerToolsDocument SetColumnWidth(SmlDocument doc, string worksheetName, short fromColumn, short toColumn, int width) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (SpreadsheetDocument document = streamDoc.GetSpreadsheetDocument()) { WorksheetPart worksheet = Get(document, worksheetName); //Get the worksheet markup XDocument worksheetXDocument = XDocument.Load(new XmlTextReader(worksheet.GetStream())); //Look for worksheet cols element XElement colsXElement = worksheetXDocument.Root.Element(ns + "cols"); if (colsXElement == null) { //cols elements does not exist //create a new one colsXElement = new XElement(ns + "cols"); //create a new col element (for setting the width) //the col element could span more than one column -span is controlled by min (initial column) and max (final column) attributes colsXElement.Add(new XElement(ns + "col", new XAttribute("min", fromColumn.ToString()), new XAttribute("max", toColumn.ToString()), new XAttribute("width", width.ToString()), new XAttribute("customWidth", "1"))); //cols element must be added before worksheet sheetData element worksheetXDocument.Root.Element(ns + "sheetData").AddBeforeSelf(colsXElement); } else { //look for a col element for the column range indicated for fromColumn and toColumn XElement colXElement = colsXElement.Elements(ns + "col") .Where(c => (System.Convert.ToInt32(c.Attribute("min").Value) == fromColumn) && (System.Convert.ToInt32(c.Attribute("max").Value) == toColumn)).FirstOrDefault(); if (colXElement != null) { //col element does exist //change its width value colXElement.SetAttributeValue("width", width); } else { //col element does not exist //create a new one colsXElement.Add(new XElement(ns + "col", new XAttribute("min", fromColumn.ToString()), new XAttribute("max", toColumn.ToString()), new XAttribute("width", width.ToString()), new XAttribute("customWidth", "1"))); } } //Update the worksheet part markup at worksheet part stream XmlWriter worksheetWriter = XmlTextWriter.Create(worksheet.GetStream(System.IO.FileMode.Create)); worksheetXDocument.WriteTo(worksheetWriter); worksheetWriter.Flush(); worksheetWriter.Close(); } return(streamDoc.GetModifiedDocument()); } }
private static OpenXmlPowerToolsDocument CreateCommentsDocument(IEnumerable <XElement> contents) { using (OpenXmlMemoryStreamDocument streamDoc = OpenXmlMemoryStreamDocument.CreateWordprocessingDocument()) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { PowerToolsExtensions.SetContent(document, contents); } return(streamDoc.GetModifiedDocument()); } }
/// <summary> /// Sets the document background image /// </summary> /// <param name="imagePath">Path of the background image</param> public static OpenXmlPowerToolsDocument SetImage(WmlDocument doc, string imagePath) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { XDocument mainDocument = document.MainDocumentPart.GetXDocument(); // Adds the image to the package ImagePart imagePart = document.MainDocumentPart.AddImagePart(ImagePartType.Bmp); Stream imageStream = new StreamReader(imagePath).BaseStream; byte[] imageBytes = new byte[imageStream.Length]; imageStream.Read(imageBytes, 0, imageBytes.Length); imagePart.GetStream().Write(imageBytes, 0, imageBytes.Length); // Creates a "background" element relating the image and the document // If the background element already exists, deletes it XElement backgroundElement = BackgroundElement(document); if (backgroundElement != null) { backgroundElement.Remove(); } // Background element construction mainDocument.Root.Add( new XElement(ns + "background", new XAttribute(ns + "color", defaultBackgroundColor), new XElement(vmlns + "background", new XAttribute(vmlns + "id", defaultVmlBackgroundImageId), new XAttribute(officens + "bwmode", defaultBWMode), new XAttribute(officens + "targetscreensize", defaultTargetScreenSize), new XElement(vmlns + "fill", new XAttribute(relationshipsns + "id", document.MainDocumentPart.GetIdOfPart(imagePart)), new XAttribute("recolor", defaultImageRecolor), new XAttribute("type", defaultImageType) ) ) ) ); // Enables background displaying by adding "displayBackgroundShape" tag if (SettingAccessor.DisplayBackgroundShapeElements(document) == null) { SettingAccessor.AddBackgroundShapeElement(document); } document.MainDocumentPart.PutXDocument(); } return(streamDoc.GetModifiedDocument()); } }
/// <summary> /// RemoveAll /// </summary> public static OpenXmlPowerToolsDocument RemoveAll(OpenXmlPowerToolsDocument doc) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (Package package = streamDoc.GetPackage()) { // Creates the PackageDigitalSignatureManager PackageDigitalSignatureManager digitalSignatureManager = new PackageDigitalSignatureManager(package); digitalSignatureManager.RemoveAllSignatures(); } return(streamDoc.GetModifiedDocument()); } }
/// <summary> /// Sets a new styles part inside the document /// </summary> /// <param name="newStylesDocument">Path of styles definition file</param> public static OpenXmlPowerToolsDocument SetStylePart(WmlDocument doc, XDocument newStylesDocument) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { // Replaces XDocument with the style file to transfer if (document.MainDocumentPart.StyleDefinitionsPart == null) { document.MainDocumentPart.AddNewPart <StyleDefinitionsPart>(); } document.MainDocumentPart.StyleDefinitionsPart.PutXDocument(newStylesDocument); } return(streamDoc.GetModifiedDocument()); } }
public static OpenXmlPowerToolsDocument Lock(WmlDocument doc) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { //Finds the settings part XDocument settingsDocument; XElement documentProtectionElement = null; if (document.MainDocumentPart.DocumentSettingsPart == null) { //If settings part does not exist creates a new one DocumentSettingsPart settingsPart = document.MainDocumentPart.AddNewPart <DocumentSettingsPart>(); settingsDocument = settingsPart.GetXDocument(); settingsDocument.Add(new XElement(W.settings, new XAttribute(XNamespace.Xmlns + "w", W.w), new XAttribute(XNamespace.Xmlns + "r", R.r))); } else { //If the settings part does exist looks if documentProtection has been included settingsDocument = document.MainDocumentPart.DocumentSettingsPart.GetXDocument(); documentProtectionElement = settingsDocument.Element(W.settings).Element(W.documentProtection); } //Creates the documentProtection element, or edits it if it exists if (documentProtectionElement == null) { settingsDocument .Element(W.settings) .Add( new XElement(W.documentProtection, new XAttribute(W.edit, "readOnly") ) ); } else { documentProtectionElement.SetAttributeValue(W.edit, "readOnly"); } document.MainDocumentPart.DocumentSettingsPart.PutXDocument(); } return(streamDoc.GetModifiedDocument()); } }
/// <summary> /// Replaces a previously existing customXml part by another one /// </summary> /// <param name="customXmlDocument">XDocument of part to replace inside the document package</param> /// <param name="partNameOnly">Name of the part.</param> public static OpenXmlPowerToolsDocument SetDocument(WmlDocument doc, XDocument customXmlDocument, string partNameOnly) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { string partName = "/" + partNameOnly; var customXmlPart = document.MainDocumentPart.CustomXmlParts.Where( t => t.Uri.OriginalString.EndsWith(partName, System.StringComparison.OrdinalIgnoreCase) ).FirstOrDefault(); if (customXmlPart == null) customXmlPart = document.MainDocumentPart.AddCustomXmlPart(CustomXmlPartType.CustomXml); customXmlPart.PutXDocument(customXmlDocument); } return streamDoc.GetModifiedDocument(); } }
/// <summary> /// Replaces a previously existing customXml part by another one /// </summary> /// <param name="customXmlDocument">XDocument of part to replace inside the document package</param> /// <param name="partNameOnly">Name of the part.</param> public static OpenXmlPowerToolsDocument SetDocument(WmlDocument doc, XDocument customXmlDocument, string partNameOnly) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { string partName = "/" + partNameOnly; var customXmlPart = document.MainDocumentPart.CustomXmlParts.Where( t => t.Uri.OriginalString.EndsWith(partName, System.StringComparison.OrdinalIgnoreCase) ).FirstOrDefault(); if (customXmlPart == null) { customXmlPart = document.MainDocumentPart.AddCustomXmlPart(CustomXmlPartType.CustomXml); } customXmlPart.PutXDocument(customXmlDocument); } return(streamDoc.GetModifiedDocument()); } }
/// <summary> /// Removes all of the comments existing in the document /// </summary> public static OpenXmlPowerToolsDocument RemoveAll(WmlDocument doc) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { //Removes comment-related tags inside the main document part IEnumerable <XElement> commentReferences = CommentReferences(document).ToList(); commentReferences.Remove(); document.MainDocumentPart.PutXDocument(); WordprocessingCommentsPart commentsPart = document.MainDocumentPart.WordprocessingCommentsPart; if (commentsPart != null) { commentsPart.RemovePart(); } } return(streamDoc.GetModifiedDocument()); } }
/// <summary> /// Set the value for a specific cell /// </summary> /// <param name="worksheet">Worksheet part containing the cell to be affected</param> /// <param name="fromColumn">Initial column for setting the value</param> /// <param name="fromRow">Initial row for setting the value</param> /// <param name="toColumn">Final column for setting the value</param> /// <param name="toRow">Final row for setting the value</param> /// <param name="value">Cell value</param> public static OpenXmlPowerToolsDocument SetCellValue(SmlDocument doc, string worksheetName, int fromRow, int toRow, int fromColumn, int toColumn, string value) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (SpreadsheetDocument document = streamDoc.GetSpreadsheetDocument()) { WorksheetPart worksheet = Get(document, worksheetName); XDocument worksheetXDocument = XDocument.Load(new XmlTextReader(worksheet.GetStream())); for (int row = fromRow; row <= toRow; row++) { for (int col = fromColumn; col <= toColumn; col++) { AddValue(worksheetXDocument, row, col, value); } } XmlWriter worksheetWriter = XmlTextWriter.Create(worksheet.GetStream(System.IO.FileMode.Create)); worksheetXDocument.WriteTo(worksheetWriter); worksheetWriter.Flush(); worksheetWriter.Close(); } return(streamDoc.GetModifiedDocument()); } }
/// <summary> /// Sets the document background color /// </summary> /// <param name="colorValue">String representation of the hexadecimal RGB color</param> public static OpenXmlPowerToolsDocument SetColor(WmlDocument doc, string colorValue) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { XDocument mainDocument = document.MainDocumentPart.GetXDocument(); // If the background element already exists, deletes it XElement backgroundElement = BackgroundElement(document); if (backgroundElement != null) backgroundElement.Remove(); mainDocument.Root.AddFirst( new XElement(ns + "background", new XAttribute(ns + "color", colorValue) ) ); // Enables background displaying by adding "displayBackgroundShape" tag if (SettingAccessor.DisplayBackgroundShapeElements(document) == null) SettingAccessor.AddBackgroundShapeElement(document); document.MainDocumentPart.PutXDocument(); } return streamDoc.GetModifiedDocument(); } }
/// <summary> /// Set the width for a range of columns /// </summary> /// <param name="worksheet">Worksheet containing the columns to be affected</param> /// <param name="fromColumn">Initial column to affect</param> /// <param name="toColumn">Final column to affect</param> /// <param name="width">Column width</param> public static OpenXmlPowerToolsDocument SetColumnWidth(SmlDocument doc, string worksheetName, short fromColumn, short toColumn, int width) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (SpreadsheetDocument document = streamDoc.GetSpreadsheetDocument()) { WorksheetPart worksheet = Get(document, worksheetName); //Get the worksheet markup XDocument worksheetXDocument = XDocument.Load(new XmlTextReader(worksheet.GetStream())); //Look for worksheet cols element XElement colsXElement = worksheetXDocument.Root.Element(ns + "cols"); if (colsXElement == null) { //cols elements does not exist //create a new one colsXElement = new XElement(ns + "cols"); //create a new col element (for setting the width) //the col element could span more than one column -span is controlled by min (initial column) and max (final column) attributes colsXElement.Add(new XElement(ns + "col", new XAttribute("min", fromColumn.ToString()), new XAttribute("max", toColumn.ToString()), new XAttribute("width", width.ToString()), new XAttribute("customWidth", "1"))); //cols element must be added before worksheet sheetData element worksheetXDocument.Root.Element(ns + "sheetData").AddBeforeSelf(colsXElement); } else { //look for a col element for the column range indicated for fromColumn and toColumn XElement colXElement = colsXElement.Elements(ns + "col") .Where(c => (System.Convert.ToInt32(c.Attribute("min").Value) == fromColumn) && (System.Convert.ToInt32(c.Attribute("max").Value) == toColumn)).FirstOrDefault(); if (colXElement != null) { //col element does exist //change its width value colXElement.SetAttributeValue("width", width); } else { //col element does not exist //create a new one colsXElement.Add(new XElement(ns + "col", new XAttribute("min", fromColumn.ToString()), new XAttribute("max", toColumn.ToString()), new XAttribute("width", width.ToString()), new XAttribute("customWidth", "1"))); } } //Update the worksheet part markup at worksheet part stream XmlWriter worksheetWriter = XmlTextWriter.Create(worksheet.GetStream(System.IO.FileMode.Create)); worksheetXDocument.WriteTo(worksheetWriter); worksheetWriter.Flush(); worksheetWriter.Close(); } return streamDoc.GetModifiedDocument(); } }
/// <summary> /// Removes personal information from the document. /// </summary> /// <param name="document"></param> public static OpenXmlPowerToolsDocument RemovePersonalInformation(WmlDocument doc) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { XNamespace x = "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties"; XDocument extendedFileProperties = document.ExtendedFilePropertiesPart.GetXDocument(); extendedFileProperties.Elements(x + "Properties").Elements(x + "Company").Remove(); XElement totalTime = extendedFileProperties.Elements(x + "Properties").Elements(x + "TotalTime").FirstOrDefault(); if (totalTime != null) { totalTime.Value = "0"; } document.ExtendedFilePropertiesPart.PutXDocument(); XNamespace dc = "http://purl.org/dc/elements/1.1/"; XNamespace cp = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties"; XDocument coreFileProperties = document.CoreFilePropertiesPart.GetXDocument(); foreach (var textNode in coreFileProperties.Elements(cp + "coreProperties") .Elements(dc + "creator") .Nodes() .OfType <XText>()) { textNode.Value = ""; } foreach (var textNode in coreFileProperties.Elements(cp + "coreProperties") .Elements(cp + "lastModifiedBy") .Nodes() .OfType <XText>()) { textNode.Value = ""; } foreach (var textNode in coreFileProperties.Elements(cp + "coreProperties") .Elements(dc + "title") .Nodes() .OfType <XText>()) { textNode.Value = ""; } XElement revision = coreFileProperties.Elements(cp + "coreProperties").Elements(cp + "revision").FirstOrDefault(); if (revision != null) { revision.Value = "1"; } document.CoreFilePropertiesPart.PutXDocument(); // add w:removePersonalInformation, w:removeDateAndTime to DocumentSettingsPart XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; XDocument documentSettings = document.MainDocumentPart.DocumentSettingsPart.GetXDocument(); // add the new elements in the right position. Add them after the following three elements // (which may or may not exist in the xml document). XElement settings = documentSettings.Root; XElement lastOfTop3 = settings.Elements() .Where(e => e.Name == w + "writeProtection" || e.Name == w + "view" || e.Name == w + "zoom") .InDocumentOrder() .LastOrDefault(); if (lastOfTop3 == null) { // none of those three exist, so add as first children of the root element settings.AddFirst( settings.Elements(w + "removePersonalInformation").Any() ? null : new XElement(w + "removePersonalInformation"), settings.Elements(w + "removeDateAndTime").Any() ? null : new XElement(w + "removeDateAndTime") ); } else { // one of those three exist, so add after the last one lastOfTop3.AddAfterSelf( settings.Elements(w + "removePersonalInformation").Any() ? null : new XElement(w + "removePersonalInformation"), settings.Elements(w + "removeDateAndTime").Any() ? null : new XElement(w + "removeDateAndTime") ); } document.MainDocumentPart.DocumentSettingsPart.PutXDocument(); } return(streamDoc.GetModifiedDocument()); } }
/// <summary> /// Inserts a watermark text inside a document /// </summary> /// <param name="watermarkText">text to show in the watermark</param> /// <param name="diagonalOrientation">specify that the text orientation will be in a diagonal way</param> public static OpenXmlPowerToolsDocument InsertWatermark(WmlDocument doc, string watermarkText, bool diagonalOrientation) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { Collection<XDocument> headers = new Collection<XDocument>(); if (HeaderAccessor.GetHeaderReference(document, HeaderType.First, 0) == null) headers.Add(HeaderAccessor.AddNewHeader(document, HeaderType.First)); else headers.Add(HeaderAccessor.GetHeader(document, HeaderType.First, 0)); if (HeaderAccessor.GetHeaderReference(document, HeaderType.Even, 0) == null) headers.Add(HeaderAccessor.AddNewHeader(document, HeaderType.Even)); else headers.Add(HeaderAccessor.GetHeader(document, HeaderType.Even, 0)); if (HeaderAccessor.GetHeaderReference(document, HeaderType.Default, 0) == null) headers.Add(HeaderAccessor.AddNewHeader(document, HeaderType.Default)); else headers.Add(HeaderAccessor.GetHeader(document, HeaderType.Default, 0)); foreach (XDocument header in headers) { var runElement = header.Descendants(ns + "r").FirstOrDefault(); if (runElement == null) { header.Root.Add( new XElement(ns + "sdt", new XElement(ns + "sdtContent", new XElement(ns + "p", new XElement(ns + "pPr", new XElement(ns + "pStyle", new XAttribute(ns + "val", "Header") ) ), runElement = new XElement(ns + "r") ) ) ) ); } runElement.AddBeforeSelf(CreateWatermarkVml(watermarkText, diagonalOrientation)); } HeaderAccessor.GetHeaderPart(document, HeaderType.First, 0).PutXDocument(); HeaderAccessor.GetHeaderPart(document, HeaderType.Even, 0).PutXDocument(); HeaderAccessor.GetHeaderPart(document, HeaderType.Default, 0).PutXDocument(); } return streamDoc.GetModifiedDocument(); } }
/// <summary> /// Removes all of the comments existing in the document /// </summary> public static OpenXmlPowerToolsDocument RemoveAll(WmlDocument doc) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { //Removes comment-related tags inside the main document part IEnumerable<XElement> commentReferences = CommentReferences(document).ToList(); commentReferences.Remove(); document.MainDocumentPart.PutXDocument(); WordprocessingCommentsPart commentsPart = document.MainDocumentPart.WordprocessingCommentsPart; if (commentsPart != null) commentsPart.RemovePart(); } return streamDoc.GetModifiedDocument(); } }
public static OpenXmlPowerToolsDocument Insert(WmlDocument doc, string xpathInsertionPoint, Image pictureToInsert, string name) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { XDocument xmlMainDocument = document.MainDocumentPart.GetXDocument(); ImagePart picturePart = null; XmlNamespaceManager namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("w", mainns.NamespaceName); IEnumerable <XElement> insertionPoints = xmlMainDocument.XPathSelectElements(xpathInsertionPoint, namespaceManager); //make the insertion for each insertion point specified in the xpath query foreach (XElement insertionPoint in insertionPoints) { if (picturePart == null) { // Create the picture part in the package picturePart = document.MainDocumentPart.AddImagePart(GetImagePartType(pictureToInsert.RawFormat)); } // the pictures in the main document part goes in a very long xml, wich specifies the way the picture // has to be placed using drawingXml. insertionPoint.AddAfterSelf( new XElement(mainns + "p", new XElement(mainns + "r", new XElement(mainns + "drawing", new XElement(wordprocessingDrawingns + "inline", new XElement(wordprocessingDrawingns + "extent", new XAttribute("cx", pictureToInsert.Width * pixelsPerEmu), new XAttribute("cy", pictureToInsert.Height * pixelsPerEmu) ), new XElement(wordprocessingDrawingns + "docPr", new XAttribute("name", name), new XAttribute("id", "1") ), new XElement(drawingmlMainns + "graphic", new XAttribute(XNamespace.Xmlns + "a", drawingmlMainns.NamespaceName), new XElement(drawingmlMainns + "graphicData", new XAttribute("uri", picturens.NamespaceName), new XElement(picturens + "pic", new XAttribute(XNamespace.Xmlns + "pic", picturens.NamespaceName), new XElement(picturens + "nvPicPr", new XElement(picturens + "cNvPr", new XAttribute("id", "0"), new XAttribute("name", name) ), new XElement(picturens + "cNvPicPr") ), new XElement(picturens + "blipFill", new XElement(drawingmlMainns + "blip", new XAttribute(relationshipns + "embed", document.MainDocumentPart.GetIdOfPart(picturePart)) ), new XElement(drawingmlMainns + "stretch", new XElement(drawingmlMainns + "fillRect") ) ), new XElement(picturens + "spPr", new XElement(drawingmlMainns + "xfrm", new XElement(drawingmlMainns + "off", new XAttribute("x", "0"), new XAttribute("y", "0") ), new XElement(drawingmlMainns + "ext", new XAttribute("cx", pictureToInsert.Width * pixelsPerEmu), new XAttribute("cy", pictureToInsert.Height * pixelsPerEmu) ) ), new XElement(drawingmlMainns + "prstGeom", new XAttribute("prst", "rect") ) ) ) ) ) ) ) ) ) ); } if (picturePart != null) { Stream partStream = picturePart.GetStream(FileMode.Create, FileAccess.ReadWrite); pictureToInsert.Save(partStream, pictureToInsert.RawFormat); } else { throw new ArgumentException("The xpath query did not return a valid location."); } document.MainDocumentPart.PutXDocument(); } return(streamDoc.GetModifiedDocument()); } }
/// <summary> /// Sets the document theme /// </summary> /// <param name="theme">Theme package</param> public static OpenXmlPowerToolsDocument SetTheme(WmlDocument doc, OpenXmlPowerToolsDocument themeDoc) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { using (OpenXmlMemoryStreamDocument themeStream = new OpenXmlMemoryStreamDocument(themeDoc)) using (Package theme = themeStream.GetPackage()) { // Gets the theme manager part PackageRelationship themeManagerRelationship = theme.GetRelationshipsByType(mainDocumentRelationshipType).FirstOrDefault(); if (themeManagerRelationship != null) { PackagePart themeManagerPart = theme.GetPart(themeManagerRelationship.TargetUri); // Gets the theme main part PackageRelationship themeRelationship = themeManagerPart.GetRelationshipsByType(themeRelationshipType).FirstOrDefault(); if (themeRelationship != null) { PackagePart themePart = theme.GetPart(themeRelationship.TargetUri); XDocument newThemeDocument = XDocument.Load(XmlReader.Create(themePart.GetStream(FileMode.Open, FileAccess.Read))); // Removes existing theme part from document if (document.MainDocumentPart.ThemePart != null) document.MainDocumentPart.DeletePart(document.MainDocumentPart.ThemePart); // Creates a new theme part ThemePart documentThemePart = document.MainDocumentPart.AddNewPart<ThemePart>(); var embeddedItems = newThemeDocument .Descendants() .Attributes(relationshipns + "embed"); foreach (PackageRelationship imageRelationship in themePart.GetRelationships()) { // Adds an image part to the theme part and stores contents inside PackagePart imagePart = theme.GetPart(imageRelationship.TargetUri); ImagePart newImagePart = documentThemePart.AddImagePart(GetImagePartType(imagePart.ContentType)); newImagePart.FeedData(imagePart.GetStream(FileMode.Open, FileAccess.Read)); // Updates relationship references into the theme XDocument XAttribute relationshipAttribute = embeddedItems.FirstOrDefault(e => e.Value == imageRelationship.Id); if (relationshipAttribute != null) relationshipAttribute.Value = documentThemePart.GetIdOfPart(newImagePart); } documentThemePart.PutXDocument(newThemeDocument); } } } } return streamDoc.GetModifiedDocument(); } }
/// <summary> /// Insert a style into a given xmlpath inside the document part /// </summary> /// <param name="xpathInsertionPoint">place where we are going to put the style</param> /// <param name="styleValue">name of the style</param> /// <param name="stylesSource">XDocument containing styles</param> public static OpenXmlPowerToolsDocument Insert(WmlDocument doc, string xpathInsertionPoint, string styleValue, XDocument stylesSource) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { XDocument xDocument = document.MainDocumentPart.GetXDocument(); XmlDocument xmlMainDocument = new XmlDocument(); xmlMainDocument.Load(xDocument.CreateReader()); // create the style element to add in the document, based upon the style name. // this is an example of an style element // <w:pStyle w:val="Heading1" /> // so, in order to construct this, we have to know already if the style will be placed inside // a run or inside a paragraph. to know this we have to verify against the xpath, and know if // the query want to access a 'run' or a paragraph XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmlMainDocument.NameTable); namespaceManager.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"); XmlNodeList insertionPoints = xmlMainDocument.SelectNodes(xpathInsertionPoint, namespaceManager); if (insertionPoints.Count == 0) throw new ArgumentException("The xpath query did not return a valid location."); foreach (XmlNode insertionPoint in insertionPoints) { XmlElement xmlStyle = null; if (insertionPoint.LocalName == "r" || insertionPoint.LocalName == "p") { XmlNode propertiesElement = insertionPoint.SelectSingleNode(@"w:pPr|w:rPr", namespaceManager); //if (propertiesElement != null) //{ if (insertionPoint.Name == "w:p") { xmlStyle = xmlMainDocument.CreateElement("w", "pStyle", namespaceManager.LookupNamespace("w")); // retrieve the suffix from the styleAccesor class xmlStyle.SetAttribute("val", namespaceManager.LookupNamespace("w"), styleValue + newStyleNameSuffix); // check if the rPr or pPr element exist, if so, then add the style xml element // inside, if not, then add a new rPr or pPr element if (propertiesElement != null) { // check if there is already a style node and remove it XmlNodeList xmlStyleList = propertiesElement.SelectNodes("w:pStyle", namespaceManager); for (int i = 0; i < xmlStyleList.Count; i++) { propertiesElement.RemoveChild(xmlStyleList[i]); } propertiesElement.PrependChild(xmlStyle); } else { propertiesElement = xmlMainDocument.CreateElement("w", "pPr", namespaceManager.LookupNamespace("w")); propertiesElement.PrependChild(xmlStyle); insertionPoint.PrependChild(propertiesElement); } } if (insertionPoint.Name == "w:r") { xmlStyle = xmlMainDocument.CreateElement("w", "rStyle", namespaceManager.LookupNamespace("w")); xmlStyle.SetAttribute("val", namespaceManager.LookupNamespace("w"), styleValue + newStyleNameSuffix); if (propertiesElement != null) { // check if there is already a style node and remove it XmlNodeList xmlStyleList = propertiesElement.SelectNodes("w:rStyle", namespaceManager); for (int i = 0; i < xmlStyleList.Count; i++) { propertiesElement.RemoveChild(xmlStyleList[i]); } propertiesElement.PrependChild(xmlStyle); } else { propertiesElement = xmlMainDocument.CreateElement("w", "rPr", namespaceManager.LookupNamespace("w")); propertiesElement.PrependChild(xmlStyle); insertionPoint.PrependChild(propertiesElement); } } //} } else { throw new ArgumentException("The xpath query did not return a valid location."); } XDocument xNewDocument = new XDocument(); using (XmlWriter xWriter = xNewDocument.CreateWriter()) xmlMainDocument.WriteTo(xWriter); document.MainDocumentPart.PutXDocument(xNewDocument); // the style has been added in the main document part, but now we have to add the // style definition in the styles definitions part. the style definition need to be // extracted from the given inputStyle file. // Because a style can be linked with other styles and // can also be based on other styles, all the complete hierarchy of styles has // to be added Collection<XElement> styleHierarchy = StyleAccessor.GetStyleHierarchy(styleValue, stylesSource, newStyleNameSuffix); // open the styles file in the document XDocument xmlStylesDefinitionDocument = StyleAccessor.GetStylesDocument(document); XDocument xElem = new XDocument(); xElem.Add(xmlStylesDefinitionDocument.Root); //insert the new style foreach (XElement xmlStyleDefinition in styleHierarchy) { xElem.Root.Add(xmlStyleDefinition); } document.MainDocumentPart.StyleDefinitionsPart.PutXDocument(xElem); } } return streamDoc.GetModifiedDocument(); } }
/// <summary> /// Set a new footer in a document /// </summary> /// <param name="footer">XDocument containing the footer to add in the document</param> /// <param name="type">The footer part type</param> public static OpenXmlPowerToolsDocument SetFooter(WmlDocument doc, XDocument footer, FooterType type, int sectionIndex) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { // Removes the reference in the document.xml and the footer part if those already // exist XElement footerReferenceElement = GetFooterReference(document, type, sectionIndex); if (footerReferenceElement != null) { GetFooterPart(document, type, sectionIndex).RemovePart(); footerReferenceElement.Remove(); } // Add the new footer FooterPart footerPart = document.MainDocumentPart.AddNewPart<FooterPart>(); footerPart.PutXDocument(footer); // If the document does not have a property section a new one must be created if (SectionPropertiesElements(document).Count() == 0) { AddDefaultSectionProperties(document); } // Creates the relationship of the footer inside the section properties in the document string relID = document.MainDocumentPart.GetIdOfPart(footerPart); string kindName = ""; switch ((FooterType)type) { case FooterType.First: kindName = "first"; break; case FooterType.Even: kindName = "even"; break; case FooterType.Default: kindName = "default"; break; } XElement sectionPropertyElement = SectionPropertiesElements(document).Skip(sectionIndex).FirstOrDefault(); if (sectionPropertyElement != null) { sectionPropertyElement.Add( new XElement(ns + "footerReference", new XAttribute(ns + "type", kindName), new XAttribute(relationshipns + "id", relID))); if (sectionPropertyElement.Element(ns + "titlePg") == null) sectionPropertyElement.Add( new XElement(ns + "titlePg") ); } document.MainDocumentPart.PutXDocument(); // add in the settings part the EvendAndOddHeaders. this element // allow to see the odd and even footers and headers in the document. SettingAccessor.AddEvenAndOddHeadersElement(document); } return streamDoc.GetModifiedDocument(); } }
/// <summary> /// Method for adding a new table definition part /// </summary> /// <param name="worksheet">Worksheet to add the table to</param> /// <param name="tableStyle">Style to be assigned to the table</param> /// <param name="useHeaders">Set a header row</param> /// <param name="fromColumn">Initial column for table</param> /// <param name="toColumn">Final column for table</param> /// <param name="fromRow">Intial row for table</param> /// <param name="toRow">Final row for table</param> public static OpenXmlPowerToolsDocument Add(SmlDocument doc, string worksheetName, string tableStyle, bool useHeaders, short fromColumn, short toColumn, int fromRow, int toRow) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (SpreadsheetDocument document = streamDoc.GetSpreadsheetDocument()) { //Getting the id for this table int tableId = GetNextTableId(document); //Set the table cell range string tableRange = string.Format("{0}{1}:{2}{3}", WorksheetAccessor.GetColumnId(fromColumn), fromRow, WorksheetAccessor.GetColumnId(toColumn), toRow); //Creating a new id for the relationship between the table definition part and the worksheet string tableRelationShipId = "rId" + Guid.NewGuid(); //Create a new table definition part WorksheetPart worksheet = WorksheetAccessor.Get(document, worksheetName); TableDefinitionPart table = worksheet.AddNewPart<TableDefinitionPart>(tableRelationShipId); //string tableColumns = string.Empty; XElement tableColumnsXElement = new XElement(ns + "tableColumns", new XAttribute("count", (toColumn - fromColumn) + 1)); //Get the name for table column elements from the first table row string[] tableHeaders = GetTableHeaders(document, worksheet, fromRow, fromColumn, toColumn); for (int i = 0; i <= (toColumn - fromColumn); i++) { //Create the markup for the SpreadsheetML table column elements tableColumnsXElement.Add( new XElement(ns + "tableColumn", new XAttribute("id", i + 1), new XAttribute("name", tableHeaders[i]))); } XElement tableXElement = new XElement(ns + "table", new XAttribute("xmlns", ns), //default namespace new XAttribute("id", tableId), new XAttribute("name", "Table" + tableId.ToString()), new XAttribute("displayName", "Table" + tableId.ToString()), new XAttribute("ref", tableRange), new XAttribute("totalsRowShown", "0")); if (useHeaders) { tableXElement.Add( new XElement(ns + "autoFilter", new XAttribute("ref", tableRange))); } tableXElement.Add(tableColumnsXElement); tableXElement.Add( new XElement(ns + "tableStyleInfo", new XAttribute("name", tableStyle), new XAttribute("showFirstColumn", "0"), new XAttribute("showLastColumn", "0"), new XAttribute("showRowStripes", "0"), new XAttribute("showColumnStripes", "0"))); //Write the markup to the Table Definition Part Stream XmlWriter tablePartStreamWriter = XmlWriter.Create(table.GetStream()); tableXElement.WriteTo(tablePartStreamWriter); tablePartStreamWriter.Flush(); tablePartStreamWriter.Close(); //Create or modify the table parts definition at worksheet (for setting the relationship id with the new table) XDocument worksheetMarkup = worksheet.GetXDocument(); //Look for the tableParts element at worksheet markup XElement tablePartsElement = worksheetMarkup.Root.Element(ns + "tableParts"); if (tablePartsElement != null) { //tableParts elements does exist at worksheet markup //increment the tableParts count attribute value short tableCount = System.Convert.ToInt16(tablePartsElement.Attribute("count").Value); tablePartsElement.SetAttributeValue("count", tableCount++.ToString()); } else { //tableParts does not exist at worksheet markup //create a new tableParts element tablePartsElement = new XElement(ns + "tableParts", new XAttribute(ns + "count", "1")); worksheetMarkup.Root.Add(tablePartsElement); } //create the tablePart element XElement tablePartEntryElement = new XElement(ns + "tablePart", new XAttribute(relationshipns + "id", tableRelationShipId)); //add the new tablePart element to the worksheet tableParts element tablePartsElement.Add(tablePartEntryElement); worksheet.PutXDocument(); } return streamDoc.GetModifiedDocument(); } }
/// <summary> /// Method for adding a new table definition part /// </summary> /// <param name="worksheet">Worksheet to add the table to</param> /// <param name="tableStyle">Style to be assigned to the table</param> /// <param name="useHeaders">Set a header row</param> /// <param name="fromColumn">Initial column for table</param> /// <param name="toColumn">Final column for table</param> /// <param name="fromRow">Intial row for table</param> /// <param name="toRow">Final row for table</param> public static OpenXmlPowerToolsDocument Add(SmlDocument doc, string worksheetName, string tableStyle, bool useHeaders, short fromColumn, short toColumn, int fromRow, int toRow) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (SpreadsheetDocument document = streamDoc.GetSpreadsheetDocument()) { //Getting the id for this table int tableId = GetNextTableId(document); //Set the table cell range string tableRange = string.Format("{0}{1}:{2}{3}", WorksheetAccessor.GetColumnId(fromColumn), fromRow, WorksheetAccessor.GetColumnId(toColumn), toRow); //Creating a new id for the relationship between the table definition part and the worksheet string tableRelationShipId = "rId" + Guid.NewGuid(); //Create a new table definition part WorksheetPart worksheet = WorksheetAccessor.Get(document, worksheetName); TableDefinitionPart table = worksheet.AddNewPart <TableDefinitionPart>(tableRelationShipId); //string tableColumns = string.Empty; XElement tableColumnsXElement = new XElement(ns + "tableColumns", new XAttribute("count", (toColumn - fromColumn) + 1)); //Get the name for table column elements from the first table row string[] tableHeaders = GetTableHeaders(document, worksheet, fromRow, fromColumn, toColumn); for (int i = 0; i <= (toColumn - fromColumn); i++) { //Create the markup for the SpreadsheetML table column elements tableColumnsXElement.Add( new XElement(ns + "tableColumn", new XAttribute("id", i + 1), new XAttribute("name", tableHeaders[i]))); } XElement tableXElement = new XElement(ns + "table", new XAttribute("xmlns", ns), //default namespace new XAttribute("id", tableId), new XAttribute("name", "Table" + tableId.ToString()), new XAttribute("displayName", "Table" + tableId.ToString()), new XAttribute("ref", tableRange), new XAttribute("totalsRowShown", "0")); if (useHeaders) { tableXElement.Add( new XElement(ns + "autoFilter", new XAttribute("ref", tableRange))); } tableXElement.Add(tableColumnsXElement); tableXElement.Add( new XElement(ns + "tableStyleInfo", new XAttribute("name", tableStyle), new XAttribute("showFirstColumn", "0"), new XAttribute("showLastColumn", "0"), new XAttribute("showRowStripes", "0"), new XAttribute("showColumnStripes", "0"))); //Write the markup to the Table Definition Part Stream XmlWriter tablePartStreamWriter = XmlWriter.Create(table.GetStream()); tableXElement.WriteTo(tablePartStreamWriter); tablePartStreamWriter.Flush(); tablePartStreamWriter.Close(); //Create or modify the table parts definition at worksheet (for setting the relationship id with the new table) XDocument worksheetMarkup = worksheet.GetXDocument(); //Look for the tableParts element at worksheet markup XElement tablePartsElement = worksheetMarkup.Root.Element(ns + "tableParts"); if (tablePartsElement != null) { //tableParts elements does exist at worksheet markup //increment the tableParts count attribute value short tableCount = System.Convert.ToInt16(tablePartsElement.Attribute("count").Value); tablePartsElement.SetAttributeValue("count", tableCount++.ToString()); } else { //tableParts does not exist at worksheet markup //create a new tableParts element tablePartsElement = new XElement(ns + "tableParts", new XAttribute(ns + "count", "1")); worksheetMarkup.Root.Add(tablePartsElement); } //create the tablePart element XElement tablePartEntryElement = new XElement(ns + "tablePart", new XAttribute(relationshipns + "id", tableRelationShipId)); //add the new tablePart element to the worksheet tableParts element tablePartsElement.Add(tablePartEntryElement); worksheet.PutXDocument(); } return(streamDoc.GetModifiedDocument()); } }
/// <summary> /// RemoveAll /// </summary> public static OpenXmlPowerToolsDocument RemoveAll(OpenXmlPowerToolsDocument doc) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (Package package = streamDoc.GetPackage()) { // Creates the PackageDigitalSignatureManager PackageDigitalSignatureManager digitalSignatureManager = new PackageDigitalSignatureManager(package); digitalSignatureManager.RemoveAllSignatures(); } return streamDoc.GetModifiedDocument(); } }
static void Main(string[] args) { var xml = GenerateDataFromDataSource(GetData()); using (System.IO.FileStream stream = new System.IO.FileStream(@"E:\currentdevelopment\cresa\Cresa\test.docx", System.IO.FileMode.Open)) { using (System.IO.MemoryStream memStream = new System.IO.MemoryStream()) { stream.CopyTo(memStream); WmlDocument wmlDoc = new WmlDocument("template1.doc", memStream); bool templateError; WmlDocument wmlAssembledDoc = DocumentAssembler.AssembleDocument(wmlDoc, xml, out templateError); string imageid = ""; // using (System.IO.FileStream fs = System.IO.File.OpenRead(@"E:\currentdevelopment\cresa\Buildings_Curtis Block_.jpg")) // { // imageid= InsertPicture(wmlAssembledDoc, fs); // } OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(wmlAssembledDoc); using (WordprocessingDocument wordDoc = streamDoc.GetWordprocessingDocument()) { for (int i=1; i<=2;i ++) { using (System.IO.FileStream fs = System.IO.File.OpenRead(@"E:\currentdevelopment\cresa\Buildings_Curtis Block_.jpg")) { MainDocumentPart mainPart = wordDoc.MainDocumentPart; ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg); imagePart.FeedData(fs); imageid = mainPart.GetIdOfPart(imagePart); } var el = AddImageToBody(imageid); foreach (var txt in wordDoc.MainDocumentPart.Document.Body.Descendants<Text>().Where(x=>x.Text.StartsWith("<BUILDING_IMAGE"))) { try { txt.Parent.AppendChild(el); txt.Text = ""; } catch { } // Console.WriteLine(txt); } // wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(el))); } } streamDoc.GetModifiedDocument().SaveAs("testzz.doc"); // wmlAssembledDoc.SaveAs("template2.doc"); } } }
/// <summary> /// Set the value for a specific cell /// </summary> /// <param name="worksheet">Worksheet part containing the cell to be affected</param> /// <param name="fromColumn">Initial column for setting the value</param> /// <param name="fromRow">Initial row for setting the value</param> /// <param name="toColumn">Final column for setting the value</param> /// <param name="toRow">Final row for setting the value</param> /// <param name="value">Cell value</param> public static OpenXmlPowerToolsDocument SetCellValue(SmlDocument doc, string worksheetName, int fromRow, int toRow, int fromColumn, int toColumn, string value) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (SpreadsheetDocument document = streamDoc.GetSpreadsheetDocument()) { WorksheetPart worksheet = Get(document, worksheetName); XDocument worksheetXDocument = XDocument.Load(new XmlTextReader(worksheet.GetStream())); for (int row = fromRow; row <= toRow; row++) { for (int col = fromColumn; col <= toColumn; col++) { AddValue(worksheetXDocument, row, col, value); } } XmlWriter worksheetWriter = XmlTextWriter.Create(worksheet.GetStream(System.IO.FileMode.Create)); worksheetXDocument.WriteTo(worksheetWriter); worksheetWriter.Flush(); worksheetWriter.Close(); } return streamDoc.GetModifiedDocument(); } }
public WmlDocument(WmlDocument other, params XElement[] replacementParts) : base(other) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(this)) { using (Package package = streamDoc.GetPackage()) { foreach (var replacementPart in replacementParts) { XAttribute uriAttribute = replacementPart.Attribute(PtOpenXml.Uri); if (uriAttribute == null) throw new OpenXmlPowerToolsException("Replacement part does not contain a Uri as an attribute"); String uri = uriAttribute.Value; var part = package.GetParts().FirstOrDefault(p => p.Uri.ToString() == uri); using (Stream partStream = part.GetStream(FileMode.Create, FileAccess.Write)) using (XmlWriter partXmlWriter = XmlWriter.Create(partStream)) replacementPart.Save(partXmlWriter); } } this.DocumentByteArray = streamDoc.GetModifiedDocument().DocumentByteArray; } }
/// <summary> /// Inserts a watermark text inside a document /// </summary> /// <param name="watermarkText">text to show in the watermark</param> /// <param name="diagonalOrientation">specify that the text orientation will be in a diagonal way</param> public static OpenXmlPowerToolsDocument InsertWatermark(WmlDocument doc, string watermarkText, bool diagonalOrientation) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { Collection <XDocument> headers = new Collection <XDocument>(); if (HeaderAccessor.GetHeaderReference(document, HeaderType.First, 0) == null) { headers.Add(HeaderAccessor.AddNewHeader(document, HeaderType.First)); } else { headers.Add(HeaderAccessor.GetHeader(document, HeaderType.First, 0)); } if (HeaderAccessor.GetHeaderReference(document, HeaderType.Even, 0) == null) { headers.Add(HeaderAccessor.AddNewHeader(document, HeaderType.Even)); } else { headers.Add(HeaderAccessor.GetHeader(document, HeaderType.Even, 0)); } if (HeaderAccessor.GetHeaderReference(document, HeaderType.Default, 0) == null) { headers.Add(HeaderAccessor.AddNewHeader(document, HeaderType.Default)); } else { headers.Add(HeaderAccessor.GetHeader(document, HeaderType.Default, 0)); } foreach (XDocument header in headers) { var runElement = header.Descendants(ns + "r").FirstOrDefault(); if (runElement == null) { header.Root.Add( new XElement(ns + "sdt", new XElement(ns + "sdtContent", new XElement(ns + "p", new XElement(ns + "pPr", new XElement(ns + "pStyle", new XAttribute(ns + "val", "Header") ) ), runElement = new XElement(ns + "r") ) ) ) ); } runElement.AddBeforeSelf(CreateWatermarkVml(watermarkText, diagonalOrientation)); } HeaderAccessor.GetHeaderPart(document, HeaderType.First, 0).PutXDocument(); HeaderAccessor.GetHeaderPart(document, HeaderType.Even, 0).PutXDocument(); HeaderAccessor.GetHeaderPart(document, HeaderType.Default, 0).PutXDocument(); } return(streamDoc.GetModifiedDocument()); } }
/// <summary> /// Set a new footer in a document /// </summary> /// <param name="footer">XDocument containing the footer to add in the document</param> /// <param name="type">The footer part type</param> public static OpenXmlPowerToolsDocument SetFooter(WmlDocument doc, XDocument footer, FooterType type, int sectionIndex) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { // Removes the reference in the document.xml and the footer part if those already // exist XElement footerReferenceElement = GetFooterReference(document, type, sectionIndex); if (footerReferenceElement != null) { GetFooterPart(document, type, sectionIndex).RemovePart(); footerReferenceElement.Remove(); } // Add the new footer FooterPart footerPart = document.MainDocumentPart.AddNewPart <FooterPart>(); footerPart.PutXDocument(footer); // If the document does not have a property section a new one must be created if (SectionPropertiesElements(document).Count() == 0) { AddDefaultSectionProperties(document); } // Creates the relationship of the footer inside the section properties in the document string relID = document.MainDocumentPart.GetIdOfPart(footerPart); string kindName = ""; switch ((FooterType)type) { case FooterType.First: kindName = "first"; break; case FooterType.Even: kindName = "even"; break; case FooterType.Default: kindName = "default"; break; } XElement sectionPropertyElement = SectionPropertiesElements(document).Skip(sectionIndex).FirstOrDefault(); if (sectionPropertyElement != null) { sectionPropertyElement.Add( new XElement(ns + "footerReference", new XAttribute(ns + "type", kindName), new XAttribute(relationshipns + "id", relID))); if (sectionPropertyElement.Element(ns + "titlePg") == null) { sectionPropertyElement.Add( new XElement(ns + "titlePg") ); } } document.MainDocumentPart.PutXDocument(); // add in the settings part the EvendAndOddHeaders. this element // allow to see the odd and even footers and headers in the document. SettingAccessor.AddEvenAndOddHeadersElement(document); } return(streamDoc.GetModifiedDocument()); } }
public ActionResult ApplyDocumentOpenXml(string id, string building_vacancy_ids, string[] zoom, string[] lat, string[] lng) { OracleRepository repo = new OracleRepository(); var buildings = repo.QueryAll(String.Format(@" Select VBUILDING.BUILDING_ID, VBUILDING.EXT_REF_ID, VBUILDING.BUILDING_NAME, VBUILDING.CLASS_TYP_ID, VBUILDING.CLASS_TYP, VBUILDING.LOCATION_TYP_ID, VBUILDING.LOCATION_TYP, VBUILDING.QRTRLY_RPT_FLAG, VBUILDING.CONTACT_MECH_ID, VBUILDING.ADDRESS1, VBUILDING.POSTAL_CODE, VBUILDING.YEAR_BUILT, VBUILDING.STOREYS, VBUILDING.NET_RENTABLE, VBUILDING.FLOOR_PLATE, VBUILDING.PARKING_RATIO, VBUILDING.PARKING_RATIO_FORMATTED, VBUILDING.LATEST_OP_COST_AMT, VBUILDING.OP_COST_YEAR, VBUILDING.LANDLORD_CONTACT_ID, VBUILDING.LANDLORD_NAME, VBUILDING.OWNER_CONTACT_ID, VBUILDING.OWNER_NAME, VBUILDING.CREATE_DATE, VBUILDING.CREATE_USER, VBUILDING.UPDATE_DATE, VBUILDING.UPDATE_USER, VBUILDING_VACANCY.BUILDING_VACANCY_ID, VBUILDING_VACANCY.LEASE_TYP_ID, VBUILDING_VACANCY.LEASE_TYP_CODE, VBUILDING_VACANCY.LEASE_TYP, VBUILDING_VACANCY.SUITE_NO, VBUILDING_VACANCY.FLOOR, VBUILDING_VACANCY.FLOOR_NUMERIC, VBUILDING_VACANCY.SIZE_SQ, VBUILDING_VACANCY.SMALLEST_DIV, VBUILDING_VACANCY.INDUCEMENTS, VBUILDING_VACANCY.BASE_RENT, VBUILDING_VACANCY.TERM, VBUILDING_VACANCY.ARCHIVED_YN, VBUILDING_VACANCY.LAST_ARCHIVED_DATE, VBUILDING_VACANCY.RETAIL_YN, VBUILDING_VACANCY.EXCLUSIVE_YN, VBUILDING_VACANCY.VACANCY_DESC, VBUILDING_VACANCY.BROKER_NOTES, TBUILDING_LAT_LONG.LATITUDE, TBUILDING_LAT_LONG.LONGITUDE from VBUILDING inner join VBUILDING_VACANCY on VBUILDING.BUILDING_ID= VBUILDING_VACANCY.BUILDING_ID left join TBUILDING_LAT_LONG on VBUILDING.BUILDING_ID = TBUILDING_LAT_LONG.BUILDING_ID where BUILDING_VACANCY_ID In ({0}) ORDER BY VBUILDING.BUILDING_NAME ", building_vacancy_ids)); Dictionary<string, Tuple<int, string,decimal>> buildingIndices = new Dictionary<string, Tuple<int, string, decimal>>(); Dictionary<string, Tuple<string, decimal>> floorplanIndices = new Dictionary<string, Tuple<string, decimal>>(); Dictionary<int, XElement> buildingXML = new Dictionary<int, XElement>(); Stream st = new MemoryStream(); string docType = "PARENT TEMPLATE"; List<SizeAttribute> sa = new List<SizeAttribute>(); string imageid = ""; using (Stream fs = repo.LoadDocument(id, out docType))//new MemoryStream())// { /* using (FileStream fs1 = System.IO.File.OpenRead(@"d:\CurrentDevelopment\Cresa\Cresa\templates\TOC.dotx")) { fs1.CopyTo(fs); }*/ WmlDocument wmlDoc = new WmlDocument("template1.docx", fs as MemoryStream, true); WmlDocument wmlAssembledDoc; var xml = GenerateDataFromDataSource(buildings.ToList(), ref buildingIndices, ref floorplanIndices, ref buildingXML); if (docType=="PARENT TEMPLATE") { List<Source> sources = new List<Source>(); sources.Add(new Source (wmlDoc,true)); List<Tuple<WmlDocument, string>> docs = new List<Tuple<WmlDocument,string>>(); docs = LoadDocuments(int.Parse(id)); int index = 0; foreach (var b in buildings.ToList()) { foreach (var d in docs) { if (index==0 || d.Item2=="DETAIL") { if (d.Item2 == "SUMMARY") { sources.Add(LoadDocumentToSource(d.Item1, xml,buildingIndices,zoom,lat,lng, sa)); } else { sources.Add(LoadDocumentToSource(d.Item1, buildingXML[index],null, null,null,null, sa)); } } } index++; } wmlAssembledDoc = DocumentBuilder.BuildDocument(sources); } else { bool templateError; wmlAssembledDoc = DocumentAssembler.AssembleDocument(wmlDoc, xml, out templateError, sa); } OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(wmlAssembledDoc); streamDoc.GetModifiedDocument().WriteByteArray(st); string filename = ""; using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(st, true)) { int index = 0; List<decimal> building_ids = new List<decimal>(); foreach (var building in buildings) { building_ids.Add((decimal)building["BUILDING_ID"]); } ProcessMap(buildingIndices, wordDoc, zoom, lat, lng, sa); ProcessFloorplan(floorplanIndices, wordDoc, sa); foreach (var b in buildingIndices.Keys) { using (var picStream = repo.GetBuildingPicture(buildingIndices[b].Item3, out filename)) { picStream.Position = 0; MainDocumentPart mainPart = wordDoc.MainDocumentPart; ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg); imagePart.FeedData(picStream); imageid = mainPart.GetIdOfPart(imagePart); } foreach (var txt in wordDoc.MainDocumentPart.Document.Body.Descendants<Text>().Where(x => x.Text == b)) { try { long width = 1906524; long height = 1906524; foreach (var s in sa) { if (s.TransformedValue == txt.Text) { width = s.Width; height = s.Height; } } var el = AddImageToBody(imageid, width, height); txt.Parent.AppendChild(el); txt.Text = ""; } catch { } } index++; } } } string ext = "doc"; var cd = new System.Net.Mime.ContentDisposition { FileName = "template." + ext, // always prompt the user for downloading, set to true if you want // the browser to try to show the file inline Inline = false, }; Response.AppendHeader("Content-Disposition", cd.ToString()); st.Position = 0; return new FileStreamResult(st, "application/msword"); }
/// <summary> /// Gets the document theme /// </summary> public static OpenXmlPowerToolsDocument GetTheme(WmlDocument doc) { using (OpenXmlMemoryStreamDocument sourceStreamDoc = new OpenXmlMemoryStreamDocument(doc)) using (WordprocessingDocument document = sourceStreamDoc.GetWordprocessingDocument()) { // Loads the theme part main file ThemePart theme = document.MainDocumentPart.ThemePart; if (theme != null) { XDocument themeDocument = theme.GetXDocument(); // Creates the theme package (thmx file) using (OpenXmlMemoryStreamDocument streamDoc = OpenXmlMemoryStreamDocument.CreatePackage()) { using (Package themePackage = streamDoc.GetPackage()) { // Creates the theme manager part on the new package and loads default content PackagePart newThemeManagerPart = themePackage.CreatePart(new Uri("/theme/theme/themeManager.xml", UriKind.RelativeOrAbsolute), "application/vnd.openxmlformats-officedocument.themeManager+xml"); themePackage.CreateRelationship(newThemeManagerPart.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"); using (XmlWriter xWriter = XmlWriter.Create(newThemeManagerPart.GetStream(FileMode.Create, FileAccess.Write))) { CreateEmptyThemeManager().WriteTo(xWriter); xWriter.Flush(); } // Creates the main theme part PackagePart newThemePart = themePackage.CreatePart(new Uri("/theme/theme/" + theme.Uri.OriginalString.Substring(theme.Uri.OriginalString.LastIndexOf('/') + 1), UriKind.RelativeOrAbsolute), theme.ContentType); newThemeManagerPart.CreateRelationship(newThemePart.Uri, TargetMode.Internal, theme.RelationshipType); // Gets embeded part references var embeddedItems = themeDocument .Descendants() .Attributes(relationshipns + "embed"); foreach (IdPartPair partId in theme.Parts) { OpenXmlPart part = partId.OpenXmlPart; // Creates the new media part inside the destination package PackagePart newPart = themePackage.CreatePart(new Uri("/theme/media/" + part.Uri.OriginalString.Substring(part.Uri.OriginalString.LastIndexOf('/') + 1), UriKind.RelativeOrAbsolute), part.ContentType); PackageRelationship relationship = newThemePart.CreateRelationship(newPart.Uri, TargetMode.Internal, part.RelationshipType); // Copies binary content from original part to destination part Stream partStream = part.GetStream(FileMode.Open, FileAccess.Read); Stream newPartStream = newPart.GetStream(FileMode.Create, FileAccess.Write); byte[] fileContent = new byte[partStream.Length]; partStream.Read(fileContent, 0, (int)partStream.Length); newPartStream.Write(fileContent, 0, (int)partStream.Length); newPartStream.Flush(); // Replaces old embed part reference with the freshly created one XAttribute relationshipAttribute = embeddedItems.FirstOrDefault(e => e.Value == theme.GetIdOfPart(part)); if (relationshipAttribute != null) { relationshipAttribute.Value = relationship.Id; } } // Writes the updated theme XDocument into the destination package using (XmlWriter newThemeWriter = XmlWriter.Create(newThemePart.GetStream(FileMode.Create, FileAccess.Write))) themeDocument.WriteTo(newThemeWriter); } return(streamDoc.GetModifiedDocument()); } } return(null); } }
/// <summary> /// Inserts Xml markup representing format attributes inside a specific paragraph or paragraph run /// </summary> /// <param name="document">Document to insert formatting Xml tags</param> /// <param name="xpathInsertionPoint">Paragraph or paragraph run to set format</param> /// <param name="content">Formatting tags</param> public static OpenXmlPowerToolsDocument Insert(WmlDocument doc, string xpathInsertionPoint, string content) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { XDocument xDocument = document.MainDocumentPart.GetXDocument(); XmlDocument xmlMainDocument = new XmlDocument(); xmlMainDocument.Load(xDocument.CreateReader()); XmlNamespaceManager namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"); XmlNodeList insertionPoints = xmlMainDocument.SelectNodes(xpathInsertionPoint, namespaceManager); if (insertionPoints.Count == 0) throw new ArgumentException("The xpath query did not return a valid location."); foreach (XmlNode insertionPoint in insertionPoints) { XmlNode propertiesElement = insertionPoint.SelectSingleNode(@"w:pPr|w:rPr", namespaceManager); if (insertionPoint.Name == "w:p") { // Checks if the rPr or pPr element exists if (propertiesElement == null) { propertiesElement = xmlMainDocument.CreateElement("w", "pPr", namespaceManager.LookupNamespace("w")); insertionPoint.PrependChild(propertiesElement); } } else if (insertionPoint.Name == "w:r") { // Checks if the rPr or pPr element exists if (propertiesElement == null) { propertiesElement = xmlMainDocument.CreateElement("w", "rPr", namespaceManager.LookupNamespace("w")); insertionPoint.PrependChild(propertiesElement); } } if (propertiesElement != null) { propertiesElement.InnerXml += content; } else { throw new ArgumentException("Specified xpath query result is not a valid location to place a formatting markup"); } } XDocument xNewDocument = new XDocument(); using (XmlWriter xWriter = xNewDocument.CreateWriter()) xmlMainDocument.WriteTo(xWriter); document.MainDocumentPart.PutXDocument(xNewDocument); } return streamDoc.GetModifiedDocument(); } }
public static OpenXmlPowerToolsDocument Insert(WmlDocument doc, string xpathInsertionPoint, Image pictureToInsert, string name) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { XDocument xmlMainDocument = document.MainDocumentPart.GetXDocument(); ImagePart picturePart = null; XmlNamespaceManager namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("w", mainns.NamespaceName); IEnumerable<XElement> insertionPoints = xmlMainDocument.XPathSelectElements(xpathInsertionPoint, namespaceManager); //make the insertion for each insertion point specified in the xpath query foreach (XElement insertionPoint in insertionPoints) { if (picturePart == null) { // Create the picture part in the package picturePart = document.MainDocumentPart.AddImagePart(GetImagePartType(pictureToInsert.RawFormat)); } // the pictures in the main document part goes in a very long xml, wich specifies the way the picture // has to be placed using drawingXml. insertionPoint.AddAfterSelf( new XElement(mainns + "p", new XElement(mainns + "r", new XElement(mainns + "drawing", new XElement(wordprocessingDrawingns + "inline", new XElement(wordprocessingDrawingns + "extent", new XAttribute("cx", pictureToInsert.Width * pixelsPerEmu), new XAttribute("cy", pictureToInsert.Height * pixelsPerEmu) ), new XElement(wordprocessingDrawingns + "docPr", new XAttribute("name", name), new XAttribute("id", "1") ), new XElement(drawingmlMainns + "graphic", new XAttribute(XNamespace.Xmlns + "a", drawingmlMainns.NamespaceName), new XElement(drawingmlMainns + "graphicData", new XAttribute("uri", picturens.NamespaceName), new XElement(picturens + "pic", new XAttribute(XNamespace.Xmlns + "pic", picturens.NamespaceName), new XElement(picturens + "nvPicPr", new XElement(picturens + "cNvPr", new XAttribute("id", "0"), new XAttribute("name", name) ), new XElement(picturens + "cNvPicPr") ), new XElement(picturens + "blipFill", new XElement(drawingmlMainns + "blip", new XAttribute(relationshipns + "embed", document.MainDocumentPart.GetIdOfPart(picturePart)) ), new XElement(drawingmlMainns + "stretch", new XElement(drawingmlMainns + "fillRect") ) ), new XElement(picturens + "spPr", new XElement(drawingmlMainns + "xfrm", new XElement(drawingmlMainns + "off", new XAttribute("x", "0"), new XAttribute("y", "0") ), new XElement(drawingmlMainns + "ext", new XAttribute("cx", pictureToInsert.Width * pixelsPerEmu), new XAttribute("cy", pictureToInsert.Height * pixelsPerEmu) ) ), new XElement(drawingmlMainns + "prstGeom", new XAttribute("prst", "rect") ) ) ) ) ) ) ) ) ) ); } if (picturePart != null) { Stream partStream = picturePart.GetStream(FileMode.Create, FileAccess.ReadWrite); pictureToInsert.Save(partStream, pictureToInsert.RawFormat); } else throw new ArgumentException("The xpath query did not return a valid location."); document.MainDocumentPart.PutXDocument(); } return streamDoc.GetModifiedDocument(); } }
/// <summary> /// Insert a style into a given xmlpath inside the document part /// </summary> /// <param name="xpathInsertionPoint">place where we are going to put the style</param> /// <param name="styleValue">name of the style</param> /// <param name="stylesSource">XDocument containing styles</param> public static OpenXmlPowerToolsDocument Insert(WmlDocument doc, string xpathInsertionPoint, string styleValue, XDocument stylesSource) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { XDocument xDocument = document.MainDocumentPart.GetXDocument(); XmlDocument xmlMainDocument = new XmlDocument(); xmlMainDocument.Load(xDocument.CreateReader()); // create the style element to add in the document, based upon the style name. // this is an example of an style element // <w:pStyle w:val="Heading1" /> // so, in order to construct this, we have to know already if the style will be placed inside // a run or inside a paragraph. to know this we have to verify against the xpath, and know if // the query want to access a 'run' or a paragraph XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmlMainDocument.NameTable); namespaceManager.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"); XmlNodeList insertionPoints = xmlMainDocument.SelectNodes(xpathInsertionPoint, namespaceManager); if (insertionPoints.Count == 0) { throw new ArgumentException("The xpath query did not return a valid location."); } foreach (XmlNode insertionPoint in insertionPoints) { XmlElement xmlStyle = null; if (insertionPoint.LocalName == "r" || insertionPoint.LocalName == "p") { XmlNode propertiesElement = insertionPoint.SelectSingleNode(@"w:pPr|w:rPr", namespaceManager); //if (propertiesElement != null) //{ if (insertionPoint.Name == "w:p") { xmlStyle = xmlMainDocument.CreateElement("w", "pStyle", namespaceManager.LookupNamespace("w")); // retrieve the suffix from the styleAccesor class xmlStyle.SetAttribute("val", namespaceManager.LookupNamespace("w"), styleValue + newStyleNameSuffix); // check if the rPr or pPr element exist, if so, then add the style xml element // inside, if not, then add a new rPr or pPr element if (propertiesElement != null) { // check if there is already a style node and remove it XmlNodeList xmlStyleList = propertiesElement.SelectNodes("w:pStyle", namespaceManager); for (int i = 0; i < xmlStyleList.Count; i++) { propertiesElement.RemoveChild(xmlStyleList[i]); } propertiesElement.PrependChild(xmlStyle); } else { propertiesElement = xmlMainDocument.CreateElement("w", "pPr", namespaceManager.LookupNamespace("w")); propertiesElement.PrependChild(xmlStyle); insertionPoint.PrependChild(propertiesElement); } } if (insertionPoint.Name == "w:r") { xmlStyle = xmlMainDocument.CreateElement("w", "rStyle", namespaceManager.LookupNamespace("w")); xmlStyle.SetAttribute("val", namespaceManager.LookupNamespace("w"), styleValue + newStyleNameSuffix); if (propertiesElement != null) { // check if there is already a style node and remove it XmlNodeList xmlStyleList = propertiesElement.SelectNodes("w:rStyle", namespaceManager); for (int i = 0; i < xmlStyleList.Count; i++) { propertiesElement.RemoveChild(xmlStyleList[i]); } propertiesElement.PrependChild(xmlStyle); } else { propertiesElement = xmlMainDocument.CreateElement("w", "rPr", namespaceManager.LookupNamespace("w")); propertiesElement.PrependChild(xmlStyle); insertionPoint.PrependChild(propertiesElement); } } //} } else { throw new ArgumentException("The xpath query did not return a valid location."); } XDocument xNewDocument = new XDocument(); using (XmlWriter xWriter = xNewDocument.CreateWriter()) xmlMainDocument.WriteTo(xWriter); document.MainDocumentPart.PutXDocument(xNewDocument); // the style has been added in the main document part, but now we have to add the // style definition in the styles definitions part. the style definition need to be // extracted from the given inputStyle file. // Because a style can be linked with other styles and // can also be based on other styles, all the complete hierarchy of styles has // to be added Collection <XElement> styleHierarchy = StyleAccessor.GetStyleHierarchy(styleValue, stylesSource, newStyleNameSuffix); // open the styles file in the document XDocument xmlStylesDefinitionDocument = StyleAccessor.GetStylesDocument(document); XDocument xElem = new XDocument(); xElem.Add(xmlStylesDefinitionDocument.Root); //insert the new style foreach (XElement xmlStyleDefinition in styleHierarchy) { xElem.Root.Add(xmlStyleDefinition); } document.MainDocumentPart.StyleDefinitionsPart.PutXDocument(xElem); } } return(streamDoc.GetModifiedDocument()); } }
public static OpenXmlPowerToolsDocument InsertXml(OpenXmlPowerToolsDocument doc, string[] partPaths, string insertionXpath, string content) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (Package package = streamDoc.GetPackage()) { foreach (string partPath in partPaths) { Uri xmlPartUri; XmlDocument xmlDocument; PackagePart xmlPart = null; // Searches for the given part xmlPartUri = new Uri(partPath, UriKind.Relative); //if (!document.Package.PartExists(xmlPartUri)) //throw new ArgumentException("Specified part does not exist."); xmlPart = package.GetPart(xmlPartUri); using (XmlReader xmlReader = XmlReader.Create(xmlPart.GetStream(FileMode.Open, FileAccess.Read))) { try { xmlDocument = new XmlDocument(); xmlDocument.Load(xmlReader); } catch (XmlException) { xmlDocument = new XmlDocument(); } } // Looks into the XmlDocument for nodes at the specified path XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmlDocument.NameTable); namespaceManager.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"); XmlNode insertionPoint = xmlDocument.SelectSingleNode(insertionXpath, namespaceManager); if (insertionPoint == null) { throw new ArgumentException("Insertion point does not exist."); } StringReader r = new StringReader("<w:node xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>" + content + "</w:node>"); XmlNode nodoid = xmlDocument.ReadNode(XmlReader.Create(r)); //doc.LoadXml("<w:node xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>" + xmlContent + "</w:node>"); //// Inserts new contents into the given part XmlNode xmlNodeToInsert = nodoid;// doc.FirstChild; // xmlDocument.CreateElement("w","node", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"); //xmlNodeToInsert. .InnerXml = xmlContent; XmlNodeList nodes = xmlNodeToInsert.ChildNodes; if (nodes.Count > 0) { for (int i = nodes.Count - 1; i >= 0; i--) { XmlNode node = nodes[i]; insertionPoint.ParentNode.InsertAfter(node, insertionPoint); } } // Writes the XmlDocument back to the part using (XmlWriter writer = XmlWriter.Create(xmlPart.GetStream(FileMode.Create, FileAccess.Write))) { xmlDocument.WriteTo(writer); } } } return(streamDoc.GetModifiedDocument()); } }
public static OpenXmlPowerToolsDocument Insert(OpenXmlPowerToolsDocument doc, IEnumerable<string> certificateList) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (Package package = streamDoc.GetPackage()) { foreach (string digitalCertificate in certificateList) { X509Certificate x509Certificate = X509Certificate2.CreateFromCertFile(digitalCertificate); PackageDigitalSignatureManager digitalSigntaureManager = new PackageDigitalSignatureManager(package); digitalSigntaureManager.CertificateOption = CertificateEmbeddingOption.InSignaturePart; System.Collections.Generic.List<Uri> partsToSign = new System.Collections.Generic.List<Uri>(); //Adds each part to the list, except relationships parts. foreach (PackagePart openPackagePart in package.GetParts()) { if (!PackUriHelper.IsRelationshipPartUri(openPackagePart.Uri)) partsToSign.Add(openPackagePart.Uri); } List<PackageRelationshipSelector> relationshipSelectors = new List<PackageRelationshipSelector>(); //Creates one selector for each package-level relationship, based on id foreach (PackageRelationship relationship in package.GetRelationships()) { PackageRelationshipSelector relationshipSelector = new PackageRelationshipSelector(relationship.SourceUri, PackageRelationshipSelectorType.Id, relationship.Id); relationshipSelectors.Add(relationshipSelector); } digitalSigntaureManager.Sign(partsToSign, x509Certificate, relationshipSelectors); } } return streamDoc.GetModifiedDocument(); } }
/// <summary> /// Sets a new styles part inside the document /// </summary> /// <param name="newStylesDocument">Path of styles definition file</param> public static OpenXmlPowerToolsDocument SetStylePart(WmlDocument doc, XDocument newStylesDocument) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { // Replaces XDocument with the style file to transfer if (document.MainDocumentPart.StyleDefinitionsPart == null) document.MainDocumentPart.AddNewPart<StyleDefinitionsPart>(); document.MainDocumentPart.StyleDefinitionsPart.PutXDocument(newStylesDocument); } return streamDoc.GetModifiedDocument(); } }
/// <summary> /// Sets the document background image /// </summary> /// <param name="imagePath">Path of the background image</param> public static OpenXmlPowerToolsDocument SetImage(WmlDocument doc, string imagePath) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { XDocument mainDocument = document.MainDocumentPart.GetXDocument(); // Adds the image to the package ImagePart imagePart = document.MainDocumentPart.AddImagePart(ImagePartType.Bmp); Stream imageStream = new StreamReader(imagePath).BaseStream; byte[] imageBytes = new byte[imageStream.Length]; imageStream.Read(imageBytes, 0, imageBytes.Length); imagePart.GetStream().Write(imageBytes, 0, imageBytes.Length); // Creates a "background" element relating the image and the document // If the background element already exists, deletes it XElement backgroundElement = BackgroundElement(document); if (backgroundElement != null) backgroundElement.Remove(); // Background element construction mainDocument.Root.Add( new XElement(ns + "background", new XAttribute(ns + "color", defaultBackgroundColor), new XElement(vmlns + "background", new XAttribute(vmlns + "id", defaultVmlBackgroundImageId), new XAttribute(officens + "bwmode", defaultBWMode), new XAttribute(officens + "targetscreensize", defaultTargetScreenSize), new XElement(vmlns + "fill", new XAttribute(relationshipsns + "id", document.MainDocumentPart.GetIdOfPart(imagePart)), new XAttribute("recolor", defaultImageRecolor), new XAttribute("type", defaultImageType) ) ) ) ); // Enables background displaying by adding "displayBackgroundShape" tag if (SettingAccessor.DisplayBackgroundShapeElements(document) == null) SettingAccessor.AddBackgroundShapeElement(document); document.MainDocumentPart.PutXDocument(); } return streamDoc.GetModifiedDocument(); } }
/// <summary> /// Set a new header in a document /// </summary> /// <param name="header">XDocument containing the header to add in the document</param> /// <param name="type">The header part type</param> public static OpenXmlPowerToolsDocument SetHeader(WmlDocument doc, XDocument header, HeaderType type, int sectionIndex) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument()) { // Removes the reference in the document.xml and the header part if those already // exist XElement headerReferenceElement = GetHeaderReference(document, type, sectionIndex); if (headerReferenceElement != null) { GetHeaderPart(document, type, sectionIndex).RemovePart(); headerReferenceElement.Remove(); } // Add the new header HeaderPart headerPart = document.MainDocumentPart.AddNewPart<HeaderPart>(); headerPart.PutXDocument(header); // Creates the relationship of the header inside the section properties in the document string relID = document.MainDocumentPart.GetIdOfPart(headerPart); AddHeaderReference(document, type, relID, sectionIndex); // add in the settings part the EvendAndOddHeaders. this element // allow to see the odd and even headers and headers in the document. SettingAccessor.AddEvenAndOddHeadersElement(document); } return streamDoc.GetModifiedDocument(); } }
/// <summary> /// Apply a cell style to a specific cell /// </summary> /// <param name="worksheet">worksheet containing the cell to be affected</param> /// <param name="fromColumn">Starting Cell Column</param> /// <param name="toColumn">Ending Cell Column</param> /// <param name="fromRow">Starting Cell Row</param> /// <param name="toRow">Ending Cell Row</param> /// <param name="cellStyle">Cell Style</param> public static OpenXmlPowerToolsDocument SetCellStyle(SmlDocument doc, string worksheetName, short fromColumn, short toColumn, int fromRow, int toRow, string cellStyle) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (SpreadsheetDocument document = streamDoc.GetSpreadsheetDocument()) { WorksheetPart worksheet = Get(document, worksheetName); XDocument worksheetXDocument = XDocument.Load(new XmlTextReader(worksheet.GetStream())); for (int row = fromRow; row <= toRow; row++) { for (short col = fromColumn; col <= toColumn; col++) { XElement cellXelement = GetCell(worksheetXDocument, col, row); cellXelement.SetAttributeValue("s", SpreadSheetStyleAccessor.GetCellStyleIndex(document, cellStyle)); } } XmlWriter worksheetWriter = XmlTextWriter.Create(worksheet.GetStream(System.IO.FileMode.Create)); worksheetXDocument.WriteTo(worksheetWriter); worksheetWriter.Flush(); worksheetWriter.Close(); } return streamDoc.GetModifiedDocument(); } }