public TResult WriteCustomProperties <TResult>( Func <Action <string, string>, TResult> callback) { var customPropsPart = workbook.AddCustomFilePropertiesPart(); var properties = new CustomDocumentProperty[] { }; var result = callback( (string name, string value) => { var property = new CustomDocumentProperty(); property.FormatId = Guid.NewGuid().ToString("B"); property.Name = name; property.VTBString = new VTBString(value); property.PropertyId = properties.Length + 2; properties = properties.Append(property).ToArray(); }); customPropsPart.Properties = new Properties(properties); var writer = OpenXmlWriter.Create(customPropsPart); writer.WriteStartElement(customPropsPart.Properties); writer.WriteEndElement(); writer.Close(); return(result); }
/// <summary> /// Set custom property for proper control /// </summary> /// <param name="propertyName">Custom property identificator</param> /// <param name="model">Data model that is needed to be stored</param> public DocxCustomPropertiesEditor AddProperties(string propertyName, string model) { if (_CustomProperties == null) { throw new InvalidOperationException($"Unable to add Property:please read document before do this action"); } var newProperty = new CustomDocumentProperty(); // every property should have the same formatId newProperty.FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"; newProperty.Name = propertyName; newProperty.VTLPWSTR = new VTLPWSTR(model); var properties = _CustomProperties.Properties; if (properties != null) { // msdn sayes that propertyId should be started from 2 int propertyId = properties.Count() == 0 ? 2 : properties.Select(item => ((CustomDocumentProperty)item).PropertyId.Value).Max() + 1; newProperty.PropertyId = propertyId; properties.AppendChild(newProperty); properties.Save(); } return(this); }
public virtual bool SetDocumentProperty <T>(string propertyName, T value) { var propertiesPart = GetCustomFilePropertiesPart(); if (propertiesPart != null) { var props = propertiesPart.Properties; var prop = props.OfType <CustomDocumentProperty>().FirstOrDefault(p => p.Name.Value == propertyName); if (prop == null) { prop = new CustomDocumentProperty { Name = propertyName, FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", // siehe https://msdn.microsoft.com/en-us/library/office/hh674468.aspx PropertyId = props.OfType <CustomDocumentProperty>().Max(prp => (int)prp.PropertyId) + 1 }; propertiesPart.Properties.AppendChild(prop); } //prop.SetProperty(value); props.Save(); // Create object to update fields on open var settingsPart = GetDocumentSettingsPart(); if (settingsPart != null) { var updateFields = new UpdateFieldsOnOpen { Val = new OnOffValue(true) }; settingsPart.Settings.PrependChild(updateFields); settingsPart.Settings.Save(); } return(true); } return(false); }
private static string AddProperty(CustomDocumentProperty newProperty, OpenXmlPackage document) { var originalValue = ""; var customProps = GetCustomDocumentProperties(document); var existinProperties = customProps.Properties; if (existinProperties == null) { return(originalValue); } var existingProperty = existinProperties.FirstOrDefault(p => string.Equals(((CustomDocumentProperty)p).Name.Value, newProperty.Name.Value, StringComparison.CurrentCultureIgnoreCase)); if (existingProperty != null) { originalValue = existingProperty.InnerText; existingProperty.Remove(); } // Append the new property, and // fix up all the property ID values. // The PropertyId value must start at 2. existinProperties.AppendChild(newProperty); var pid = 2; foreach (var openXmlElement in existinProperties) { var item = (CustomDocumentProperty)openXmlElement; item.PropertyId = pid++; } existinProperties.Save(); return(originalValue); }
public void CheckIfDocumentExist(WordprocessingDocument doc, int id) { var customPropsAdd = doc.CustomFilePropertiesPart; if (customPropsAdd == null) { var customFilePropPart = doc.AddCustomFilePropertiesPart(); customFilePropPart.Properties = new DocumentFormat.OpenXml.CustomProperties.Properties(); var customProp = new CustomDocumentProperty(); customProp.Name = "ParentId"; customProp.FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"; customProp.VTLPWSTR = new VTLPWSTR(id.ToString()); customFilePropPart.Properties.AppendChild(customProp); int pid = 2; foreach (CustomDocumentProperty item in customFilePropPart.Properties) { item.PropertyId = pid++; } customFilePropPart.Properties.Save(); } }
private void GenerateCustomFilePropertiesPartContent(CustomFilePropertiesPart customFilePropertiesPart1) { var properties2 = new DocumentFormat.OpenXml.CustomProperties.Properties(); properties2.AddNamespaceDeclaration("vt", "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"); var propertyId = 1; foreach (XlCustomProperty p in Properties) { propertyId++; var customDocumentProperty = new CustomDocumentProperty { FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", PropertyId = propertyId, Name = p.Name }; var vTlpwstr1 = new VTLPWSTR { Text = p.Value }; customDocumentProperty.AppendChild(vTlpwstr1); properties2.AppendChild(customDocumentProperty); } customFilePropertiesPart1.Properties = properties2; customFilePropertiesPart1.Properties.Save(); }
private string ProcessExcel(CustomDocumentProperty newProperty) { var originalValue = ""; using (var document = SpreadsheetDocument.Open(_filename, true)) { originalValue = AddProperty(newProperty, document); } return(originalValue); }
private string ProcessWord(CustomDocumentProperty newProperty) { var originalValue = ""; using (var document = WordprocessingDocument.Open(_filename, true)) { originalValue = AddProperty(newProperty, document); } return(originalValue); }
private void SetFileProperties(CustomFilePropertiesPart customProp) { customProp.Properties = new Properties(); int kvIndex = 2; foreach (KeyValuePair <string, string> kvPair in DocProperties) { CustomDocumentProperty newProp = new CustomDocumentProperty() { Name = kvPair.Key, FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", PropertyId = Int32Value.FromInt32(kvIndex), VTLPWSTR = new DocumentFormat.OpenXml.VariantTypes.VTLPWSTR(kvPair.Value) }; customProp.Properties.Append(newProp); kvIndex++; } }
private string AddPropertyToDocument(string returnValue, CustomDocumentProperty newProperty) { if (_filename.EndsWith("xlsx")) { returnValue = ProcessExcel(newProperty); } else if (_filename.EndsWith("docx")) { returnValue = ProcessWord(newProperty); } else { throw new Exception("Unknown Filetype"); } return(returnValue); }
public void MarkPptxAsFinal(string input) { if (!File.Exists(input)) { throw new FileNotFoundException(); } using (var ppt = PresentationDocument.Open(input, true)) { var filename = Path.GetFileName(input); Log.Information("Processing {inputFile}...", filename); var customProps = ppt.CustomFilePropertiesPart; if (customProps == null) { customProps = ppt.AddCustomFilePropertiesPart(); customProps.Properties = new Properties(); } var props = customProps.Properties; var markAsFinalProp = props .OfType <CustomDocumentProperty>() .FirstOrDefault(x => x.Name == "_MarkAsFinal"); if (markAsFinalProp != null) { Log.Warning("{inputFile} had already been marked as final, skipping...", filename); return; } var newProp = new CustomDocumentProperty { FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", Name = "_MarkAsFinal", VTBool = new VTBool("true") }; props.AppendChild(newProp); var pid = 2; foreach (var openXmlElement in props) { if (openXmlElement is CustomDocumentProperty customDocumentProperty) { customDocumentProperty.PropertyId = pid++; } } ppt.PackageProperties.ContentStatus = "Final"; Log.Information("Marked {inputName} as final.", filename); } }
//gavdcodeend 05 //gavdcodebegin 06 public static void WordOpenXmlAddOneCustomPropertyDocument() { string propName = "myCustomProperty"; string returnValue = string.Empty; CustomDocumentProperty newProp = new CustomDocumentProperty(); newProp.FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"; newProp.Name = propName; using (WordprocessingDocument myWordDoc = WordprocessingDocument.Open(@"C:\Temporary\WordDoc01.docx", true)) { newProp.VTLPWSTR = new VTLPWSTR("This is the value of the property"); var customPropsPart = myWordDoc.CustomFilePropertiesPart; if (customPropsPart == null) { customPropsPart = myWordDoc.AddCustomFilePropertiesPart(); customPropsPart.Properties = new DocumentFormat.OpenXml.CustomProperties.Properties(); } var customProps = customPropsPart.Properties; if (customProps != null) { var oneProp = customProps.Where( prp => ((CustomDocumentProperty)prp).Name.Value == propName).FirstOrDefault(); if (oneProp != null) { returnValue = oneProp.InnerText; oneProp.Remove(); } customProps.AppendChild(newProp); int pid = 2; foreach (CustomDocumentProperty item in customProps) { item.PropertyId = pid++; } customProps.Save(); } } }
public List <CustomPropertyEntity> GetCustomProperities() { List <CustomPropertyEntity> allCustomProperities = new List <CustomPropertyEntity>(); // Given a document name, a property name/value, and the property type, // add a custom property to a document. The method returns the original // value, if it existed. var cPropnewProp = new CustomDocumentProperty(); // Now that you have handled the parameters, start // working on the document. //newProp.FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"; //newProp.Name = propertyName; using (var document = WordprocessingDocument.Open(this.FileLocation, true)) { var customProps = document.CustomFilePropertiesPart; if (customProps == null) { // No custom properties? Add the part, and the // collection of properties now. return(null); } var props = customProps.Properties; if (props != null) { // This will trigger an exception if the property's Name // property is null, but if that happens, the property is damaged, // and probably should raise an exception. foreach (CustomDocumentProperty p in props) { CustomPropertyEntity cProp = new CustomPropertyEntity(); cProp.Name = p.Name.Value; cProp.Value = p.InnerText; allCustomProperities.Add(cProp); } } } return(allCustomProperities); }
private void AddCustomProperty(string name, string value) { IEnumerable <CustomDocumentProperty> customPropertyResults = customProperties.Where(c => c.Name.Value.Equals(name)); CustomDocumentProperty customProperty = customPropertyResults.FirstOrDefault(); if (customProperty == default(CustomDocumentProperty)) { CustomDocumentProperty newProp = new CustomDocumentProperty(); newProp.VTLPWSTR = new DocumentFormat.OpenXml.VariantTypes.VTLPWSTR(value); newProp.FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"; newProp.Name = name; customProperties.Add(newProp); } if (customPropertyResults.Count() > 1) { Logger.Warn($"A custom property search for the name {name} turned up more than one result."); } }
/// <summary> /// Creates the specific CustomDocumentProperty from the given propertyType with the given value /// </summary> /// <returns>returns null if property is not set</returns> public CustomDocumentProperty CreateProperty(object propertyValue, PropertyType propertyType) { if (propertyValue == null) { throw new ArgumentNullException(nameof(propertyValue)); } var returnedProperty = new CustomDocumentProperty(); var propSet = false; // Calculate the correct type: switch (propertyType) { case PropertyType.DateTime: // Make sure you were passed a real date, // and if so, format in the correct way. // The date/time value passed in should // represent a UTC date/time. if (propertyValue is DateTime) { returnedProperty.VTFileTime = new VTFileTime($"{Convert.ToDateTime(propertyValue):s}Z"); propSet = true; } break; case PropertyType.NumberInteger: if (propertyValue is int) { returnedProperty.VTInt32 = new VTInt32(propertyValue.ToString()); propSet = true; } break; case PropertyType.NumberDouble: if (propertyValue is double) { returnedProperty.VTFloat = new VTFloat(propertyValue.ToString()); propSet = true; } break; case PropertyType.Text: returnedProperty.VTLPWSTR = new VTLPWSTR(propertyValue.ToString()); propSet = true; break; case PropertyType.YesNo: if (propertyValue is bool) { returnedProperty.VTBool = new VTBool(Convert.ToBoolean(propertyValue).ToString().ToLower()); propSet = true; } break; default: throw new ArgumentException($"unknown {nameof(propertyType)} [{propertyType}]"); } return(propSet ? returnedProperty : null); }
/// <summary> convert values to object </summary> /// <param name="PropertyName"> PropertyName </param> /// <param name="PropertyValue"> PropertyValue </param> /// <param name="PropertyType"> PropertyType </param> /// <returns></returns> private static CustomDocumentProperty parseCustomProperty(string PropertyName, object PropertyValue, PropertyTypes PropertyType) { var newProp = new CustomDocumentProperty(); bool propSet = false; // Calculate the correct type. switch (PropertyType) { case PropertyTypes.DateTime: // Be sure you were passed a real date, // and if so, format in the correct way. // The date/time value passed in should // represent a UTC date/time. if ((PropertyValue) is DateTime) { newProp.VTFileTime = new VTFileTime(string.Format("{0:s}Z", Convert.ToDateTime(PropertyValue))); propSet = true; } break; case PropertyTypes.NumberInteger: if ((PropertyValue) is int) { newProp.VTInt32 = new VTInt32(PropertyValue.ToString()); propSet = true; } break; case PropertyTypes.NumberDouble: if (PropertyValue is double) { newProp.VTFloat = new VTFloat(PropertyValue.ToString()); propSet = true; } break; case PropertyTypes.Text: newProp.VTLPWSTR = new VTLPWSTR(PropertyValue.ToString()); propSet = true; break; case PropertyTypes.YesNo: if (PropertyValue is bool) { // Must be lowercase. newProp.VTBool = new VTBool( Convert.ToBoolean(PropertyValue).ToString().ToLower()); propSet = true; } break; } if (!propSet) { return(null); } // Now that you have handled the parameters, start // working on the document. newProp.FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"; newProp.Name = PropertyName; return(newProp); }
internal static string SetCustomProperty(WordprocessingDocument document, string propertyName, object propertyValue, PropertyTypes propertyType) { string returnValue = null; var newProp = new CustomDocumentProperty(); bool propSet = false; // Calculate the correct type. switch (propertyType) { case PropertyTypes.DateTime: // Be sure you were passed a real date, // and if so, format in the correct way. // The date/time value passed in should // represent a UTC date/time. if ((propertyValue) is DateTime) { newProp.VTFileTime = new VTFileTime(string.Format("{0:s}Z", Convert.ToDateTime(propertyValue))); propSet = true; } break; case PropertyTypes.NumberInteger: if ((propertyValue) is int) { newProp.VTInt32 = new VTInt32(propertyValue.ToString()); propSet = true; } break; case PropertyTypes.NumberDouble: if (propertyValue is double) { newProp.VTFloat = new VTFloat(propertyValue.ToString()); propSet = true; } break; case PropertyTypes.Text: newProp.VTLPWSTR = new VTLPWSTR(propertyValue.ToString()); propSet = true; break; case PropertyTypes.YesNo: if (propertyValue is bool) { // Must be lowercase. newProp.VTBool = new VTBool( Convert.ToBoolean(propertyValue).ToString().ToLower()); propSet = true; } break; } if (!propSet) { // If the code was not able to convert the // property to a valid value, throw an exception. throw new InvalidDataException("propertyValue"); } // Now that you have handled the parameters, start // working on the document. newProp.FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"; newProp.Name = propertyName; var customProps = document.CustomFilePropertiesPart; if (customProps == null) { // No custom properties? Add the part, and the // collection of properties now. customProps = document.AddCustomFilePropertiesPart(); customProps.Properties = new Properties(); } var props = customProps.Properties; if (props != null) { // This will trigger an exception if the property's Name // property is null, but if that happens, the property is damaged, // and probably should raise an exception. var prop = props.Where(p => ((CustomDocumentProperty)p).Name.Value == propertyName).FirstOrDefault(); // Does the property exist? If so, get the return value, // and then delete the property. if (prop != null) { returnValue = prop.InnerText; prop.Remove(); } // Append the new property, and // fix up all the property ID values. // The PropertyId value must start at 2. props.AppendChild(newProp); int pid = 2; foreach (CustomDocumentProperty item in props) { item.PropertyId = pid++; } props.Save(); } return(returnValue); }
private static string SetCustomProperty( string fileName, string propertyName, object propertyValue, PropertyTypes propertyType, string extension) { string returnValue = null; var newProp = new CustomDocumentProperty(); bool propSet = false; switch (propertyType) { case PropertyTypes.Text: newProp.VTLPWSTR = new VTLPWSTR(propertyValue.ToString()); propSet = true; break; } if (!propSet) { throw new InvalidDataException("propertyValue"); } newProp.FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"; newProp.Name = propertyName; if (extension == ".docx" || extension == ".docm" || extension == ".dotx" || extension == ".dotm" || extension == ".docb") { using (var document = WordprocessingDocument.Open(fileName, true)) { var customProps = document.CustomFilePropertiesPart; if (customProps == null) { customProps = document.AddCustomFilePropertiesPart(); customProps.Properties = new DocumentFormat.OpenXml.CustomProperties.Properties(); } var props = customProps.Properties; if (props != null) { var prop = props.Where( p => ((CustomDocumentProperty)p).Name.Value == propertyName).FirstOrDefault(); if (prop != null) { returnValue = prop.InnerText; prop.Remove(); } props.AppendChild(newProp); int pid = 2; foreach (CustomDocumentProperty item in props) { item.PropertyId = pid++; } props.Save(); } } return(returnValue); } else if (extension == ".xlsx" || extension == ".xlsm" || extension == ".xltx" || extension == ".xltm") { using (var document = SpreadsheetDocument.Open(fileName, true)) { var customProps = document.CustomFilePropertiesPart; if (customProps == null) { customProps = document.AddCustomFilePropertiesPart(); customProps.Properties = new DocumentFormat.OpenXml.CustomProperties.Properties(); } var props = customProps.Properties; if (props != null) { var prop = props.Where( p => ((CustomDocumentProperty)p).Name.Value == propertyName).FirstOrDefault(); if (prop != null) { returnValue = prop.InnerText; prop.Remove(); } props.AppendChild(newProp); int pid = 2; foreach (CustomDocumentProperty item in props) { item.PropertyId = pid++; } props.Save(); } } return(returnValue); } else if (extension == ".pptx" || extension == "pptm" || extension == ".potx" || extension == "potm" || extension == ".ppam" || extension == ".ppsm" || extension == ".sldx" || extension == ".sldm") { using (var document = PresentationDocument.Open(fileName, true)) { var customProps = document.CustomFilePropertiesPart; if (customProps == null) { customProps = document.AddCustomFilePropertiesPart(); customProps.Properties = new DocumentFormat.OpenXml.CustomProperties.Properties(); } var props = customProps.Properties; if (props != null) { var prop = props.Where( p => ((CustomDocumentProperty)p).Name.Value == propertyName).FirstOrDefault(); if (prop != null) { returnValue = prop.InnerText; prop.Remove(); } props.AppendChild(newProp); int pid = 2; foreach (CustomDocumentProperty item in props) { item.PropertyId = pid++; } props.Save(); } } return(returnValue); } return(null); }
public override async Task <MetadataResponse> Get(HttpContent content) { try { IDictionary <string, string> metadata = new Dictionary <string, string>(); using (var memStream = new MemoryStream()) { await content.CopyToAsync(memStream); using (var document = WordprocessingDocument.Open(memStream, false)) { var packageProps = document.PackageProperties; /* * Document properties: * * Category Language * ContentStatus LastModifiedBy * ContentType Modified * Created Revision * Creator Subject * Description Title * Identifier Version * Keywords */ if (packageProps != null) { if (metaNames.Contains("Category", StringComparer.OrdinalIgnoreCase)) { metadata["Category"] = packageProps.Category; } if (metaNames.Contains("ContentStatus", StringComparer.OrdinalIgnoreCase)) { metadata["ContentStatus"] = packageProps.ContentStatus; } if (metaNames.Contains("ContentType", StringComparer.OrdinalIgnoreCase)) { metadata["ContentType"] = packageProps.ContentType; } if (metaNames.Contains("Created", StringComparer.OrdinalIgnoreCase)) { metadata["Created"] = packageProps.Created.ToString(); } if (metaNames.Contains("Creator", StringComparer.OrdinalIgnoreCase)) { metadata["Creator"] = packageProps.Creator; } if (metaNames.Contains("Description", StringComparer.OrdinalIgnoreCase)) { metadata["Description"] = packageProps.Description; } if (metaNames.Contains("Keywords", StringComparer.OrdinalIgnoreCase)) { metadata["Keywords"] = packageProps.Keywords; } if (metaNames.Contains("Language", StringComparer.OrdinalIgnoreCase)) { metadata["Language"] = packageProps.Language; } if (metaNames.Contains("LastModifiedBy", StringComparer.OrdinalIgnoreCase)) { metadata["LastModifiedBy"] = packageProps.LastModifiedBy; } if (metaNames.Contains("Modified", StringComparer.OrdinalIgnoreCase)) { metadata["Modified"] = packageProps.Modified.ToString(); } if (metaNames.Contains("Revision", StringComparer.OrdinalIgnoreCase)) { metadata["Revision"] = packageProps.Revision; } if (metaNames.Contains("Subject", StringComparer.OrdinalIgnoreCase)) { metadata["Subject"] = packageProps.Subject; } if (metaNames.Contains("Title", StringComparer.OrdinalIgnoreCase)) { metadata["Title"] = packageProps.Title; } if (metaNames.Contains("Version", StringComparer.OrdinalIgnoreCase)) { metadata["Version"] = packageProps.Version; } } var customProps = document.CustomFilePropertiesPart; if (customProps != null) { var props = customProps.Properties; if (props != null) { foreach (var p in props) { CustomDocumentProperty customProp = (CustomDocumentProperty)p; if (metaNames.Contains(customProp.Name.Value, StringComparer.OrdinalIgnoreCase)) { metadata[customProp.Name.Value] = customProp.InnerText; } } } } } } return(new MetadataResponse() { Url = resource.Url, StatusCode = HttpStatusCode.OK, Metadata = metadata, ErrorMessage = null }); } catch (Exception e) { return(new MetadataResponse() { Url = resource.Url, StatusCode = HttpStatusCode.BadRequest, Metadata = null, ErrorMessage = e.Message }); } }