/// <summary> /// Reads all metadata keys of the Word document /// </summary> /// <param name="directoryPath">Path to the files</param> public static void ReadMetadataUsingKeys(string directoryPath) { try { //ExStart:ReadMetadataUsingKeys //Get all Word documents inside directory string[] files = Directory.GetFiles(Common.MapSourceFilePath(directoryPath), "*.doc"); foreach (string path in files) { Console.WriteLine("Document: {0}", Path.GetFileName(path)); // open Word document using (DocFormat doc = new DocFormat(path)) { // get metadata Metadata metadata = doc.DocumentProperties; // print all metadata keys presented in DocumentProperties foreach (string key in metadata.Keys) { Console.WriteLine(key); } } } //ExEnd:ReadMetadataUsingKeys } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public static void ApplySettings(APIDocGeneratorSettings settings) { _isAPIAction = settings.IsAPIAction; _judgeAuthorized = settings.JudgeAuthorized; _globalPossibleResponse = settings.GlobalPossibleResponse; _format = settings.Format; }
//ExEnd:SourceDocFilePath #region working with built-in document properties /// <summary> /// Gets builtin document properties from Doc file /// </summary> public static void GetDocumentProperties() { try { //ExStart:GetBuiltinDocumentPropertiesDocFormat // initialize DocFormat DocFormat docFormat = new DocFormat(Common.MapSourceFilePath(filePath)); // initialize metadata DocMetadata docMetadata = docFormat.DocumentProperties; // get properties Console.WriteLine("Built-in Properties: "); foreach (KeyValuePair <string, PropertyValue> property in docMetadata) { // check if built-in property if (docMetadata.IsBuiltIn(property.Key)) { Console.WriteLine("{0} : {1}", property.Key, property.Value); } } //ExEnd:GetBuiltinDocumentPropertiesDocFormat } catch (Exception exp) { Console.WriteLine(exp.Message); } }
/// <summary> /// Adds custom property in Doc file and creates output file /// </summary> public static void AddCustomProperty() { try { //ExStart:AddCustomPropertyDocFormat // initialize DocFormat DocFormat docFormat = new DocFormat(Common.MapSourceFilePath(filePath)); // initialize DocMetadata DocMetadata metadata = docFormat.DocumentProperties; string propertyName = "New Custom Property"; string propertyValue = "123"; // add boolean key if (!metadata.ContainsKey(propertyName)) { // add property metadata.Add(propertyName, propertyValue); } // save file in destination folder docFormat.Save(Common.MapDestinationFilePath(filePath)); //ExEnd:AddCustomPropertyDocFormat Console.WriteLine("File saved in destination folder."); } catch (Exception exp) { Console.WriteLine(exp.Message); } }
/// <summary> /// Gets document comments of Doc file /// </summary> public static void GetDocumentComments() { try { // initialize DocFormat DocFormat docFormat = new DocFormat(Common.MapSourceFilePath(filePath)); //get comments... DocComment[] comments = docFormat.ExtractComments(); //get commnets by author... //DocComment[] comments = docFormat.ExtractComments("USMAN"); // display comments foreach (DocComment comment in comments) { Console.WriteLine("Author: ", comment); Console.WriteLine("Created on Date: ", comment.CreatedDate); Console.WriteLine("Initials: ", comment.Initials); Console.WriteLine("\n"); } } catch (Exception exp) { Console.WriteLine(exp.Message); } }
/// <summary> /// Gets custom properties of Doc file /// </summary> public static void GetCustomProperties() { try { //ExStart:GetCustomPropertiesDocFormat // initialize DocFormat DocFormat docFormat = new DocFormat(Common.MapSourceFilePath(filePath)); // initialize metadata DocMetadata docMetadata = docFormat.DocumentProperties; // get properties Console.WriteLine("\nCustom Properties"); foreach (KeyValuePair <string, PropertyValue> keyValuePair in docMetadata) { // check if property is not built-in if (!docMetadata.IsBuiltIn(keyValuePair.Key)) { // get property value PropertyValue propertyValue = docMetadata[keyValuePair.Key]; Console.WriteLine("Key: {0}, Type:{1}, Value: {2}", keyValuePair.Key, propertyValue.Type, propertyValue); } } //ExEnd:GetCustomPropertiesDocFormat } catch (Exception exp) { Console.WriteLine(exp.Message); } }
/// <summary> /// Updates document properties of Doc file and creates output file /// </summary> public static void UpdateDocumentProperties() { try { //ExStart:UpdateBuiltinDocumentPropertiesDocFormat // initialize DocFormat DocFormat docFormat = new DocFormat(Common.MapSourceFilePath(filePath)); // initialize DocMetadata DocMetadata docMetadata = docFormat.DocumentProperties; //update document property... docMetadata.Author = "Usman"; docMetadata.Company = "Aspose"; docMetadata.Manager = "Usman Aziz"; //save output file... docFormat.Save(Common.MapDestinationFilePath(filePath)); //ExEnd:UpdateBuiltinDocumentPropertiesDocFormat Console.WriteLine("Updated Successfully."); } catch (Exception exp) { Console.WriteLine(exp.Message); } }
//ExEnd:SourceDocFilePath #region working with built-in document properties /// <summary> /// Gets builtin document properties from Doc file /// </summary> public static void GetDocumentProperties() { try { //ExStart:GetBuiltinDocumentPropertiesDocFormat // initialize DocFormat DocFormat docFormat = new DocFormat(Common.MapSourceFilePath(filePath)); // initialize metadata DocMetadata docMetadata = docFormat.DocumentProperties; // get properties Console.WriteLine("Built-in Properties: "); foreach (KeyValuePair<string, PropertyValue> property in docMetadata) { // check if built-in property if (docMetadata.IsBuiltIn(property.Key)) { Console.WriteLine("{0} : {1}", property.Key, property.Value); } } //ExEnd:GetBuiltinDocumentPropertiesDocFormat } catch (Exception exp) { Console.WriteLine(exp.Message); } }
protected float getTotalTaxCompGridandTaxPerc(DataTable dt) { float totalTaxPerc = 0; ArrayList invList = BackEndObjects.DocFormat. getDocFormatforEntityIdandDocTypeDB(Session[SessionFactory.MAIN_BUSINESS_ENTITY_ID_STRING].ToString(), BackEndObjects.DocFormat.DOCFORMAT_DOC_TYPE_INVOICE); int taxCompGridCounter = 0; for (int i = 0; i < invList.Count; i++) { DocFormat invObj = (DocFormat)invList[i]; String sectionType = invObj.getSection_type(); switch (sectionType) { case BackEndObjects.DocFormat.DOCFORMAT_DOC_TYPE_INVOICE_SECTION_TYPE_TAX: dt.Rows.Add(); dt.Rows[taxCompGridCounter]["Hidden"] = invObj.getDocformat_id(); //Component name is the section type name dt.Rows[taxCompGridCounter]["Comp_Name"] = invObj.getSectionTypeName(); dt.Rows[taxCompGridCounter]["Comp_Value"] = invObj.getText(); totalTaxPerc += float.Parse(invObj.getText()); taxCompGridCounter++; break; } } return(totalTaxPerc); }
protected void loadSODetails() { ArrayList soList = BackEndObjects.DocFormat. getDocFormatforEntityIdandDocTypeDB(Session[SessionFactory.MAIN_BUSINESS_ENTITY_ID_STRING].ToString(), BackEndObjects.DocFormat.DOCFORMAT_DOC_TYPE_SALES_ORDER); for (int i = 0; i < soList.Count; i++) { DocFormat soObj = (DocFormat)soList[i]; String sectionType = soObj.getSection_type(); if (TextBox_SO_format_name.Text.Equals("")) { TextBox_SO_format_name.Text = soObj.getDocformat_name(); } switch (sectionType) { case BackEndObjects.DocFormat.DOCFORMAT_DOC_TYPE_SALES_ORDER_SECTION_TYPE_TNC: TextBox_SO_TnC.Text = soObj.getText(); Label_TNC_flag_SO.Text = TextBox_SO_TnC.Text.Equals("") ? "Y" : "N"; break; } } }
protected void Button_SO_Update_Click(object sender, EventArgs e) { String sectionTnC = Label_TNC_flag_SO.Text; Boolean insertFlag = sectionTnC.Equals("Y"); Boolean updateStat = true; ArrayList docFormatList = new ArrayList(); DocFormat sectionTnCObj = new DocFormat(); String docFormatId = ""; if (sectionTnC.Equals("Y")) { if (!TextBox_SO_format_name.Text.Equals("") && !TextBox_SO_TnC.Text.Equals("")) { docFormatId = new BackEndObjects.Id().getNewId(BackEndObjects.Id.ID_TYPE_DOCFORMAT_ID_STRING); sectionTnCObj.setCmp_id(Session[SessionFactory.MAIN_BUSINESS_ENTITY_ID_STRING].ToString()); sectionTnCObj.setDoc_type(BackEndObjects.DocFormat.DOCFORMAT_DOC_TYPE_SALES_ORDER); sectionTnCObj.setDocformat_id(docFormatId); sectionTnCObj.setDocformat_name(TextBox_SO_format_name.Text); sectionTnCObj.setSection_type(BackEndObjects.DocFormat.DOCFORMAT_DOC_TYPE_SALES_ORDER_SECTION_TYPE_TNC); sectionTnCObj.setText(TextBox_SO_TnC.Text); docFormatList.Add(sectionTnCObj); } } else { Dictionary <String, String> whereCls = new Dictionary <string, string>(); whereCls.Add(BackEndObjects.DocFormat.DOCFORMAT_COL_CMP_ID, Session[SessionFactory.MAIN_BUSINESS_ENTITY_ID_STRING].ToString()); whereCls.Add(BackEndObjects.DocFormat.DOCFORMAT_COL_DOC_TYPE, BackEndObjects.DocFormat.DOCFORMAT_DOC_TYPE_SALES_ORDER); whereCls.Add(BackEndObjects.DocFormat.DOCFORMAT_COL_SECTION_TYPE, BackEndObjects.DocFormat.DOCFORMAT_DOC_TYPE_SALES_ORDER_SECTION_TYPE_TNC); Dictionary <String, String> targetVals = new Dictionary <string, string>(); targetVals.Add(BackEndObjects.DocFormat.DOCFORMAT_COL_TEXT, TextBox_SO_TnC.Text); targetVals.Add(BackEndObjects.DocFormat.DOCFORMAT_COL_DOCFORMAT_NAME, TextBox_SO_format_name.Text); BackEndObjects.DocFormat.updateDocFormatObjsDB(whereCls, targetVals, DBConn.Connections.OPERATION_UPDATE); updateStat = true; } try { if (insertFlag) { BackEndObjects.DocFormat.insertDocFormatDB(docFormatList); } Label_SO_update_stat.Visible = true; Label_SO_update_stat.ForeColor = System.Drawing.Color.Green; Label_SO_update_stat.Text = "Updated Successfully"; } catch (Exception ex) { Label_SO_update_stat.Visible = true; Label_SO_update_stat.ForeColor = System.Drawing.Color.Red; Label_SO_update_stat.Text = "Update Failed"; } }
public static void ApplySettings(APIDocGeneratorSettings settings) { _isAPIAction = settings.IsAPIAction; _judgeAuthorized = settings.JudgeAuthorized; _globalPossibleResponse = settings.GlobalPossibleResponse; _format = settings.Format; _docAddress = settings.DocAddress.TrimStart('/').ToLower(); }
protected OfficeDocument(DocFormat format, byte[] document) { Format = format; DocumentStream = new MemoryStream(); if (document != null) { DocumentStream.Write(document, 0, document.Length); } }
/// <summary> /// Takes author name and removes metadata in files created by specified author /// </summary> /// <param name="authorName">Author name</param> public void RemoveMetadataByAuthor(string authorName) { // Map directory in source folder string sourceDirectoryPath = Common.MapSourceFilePath(this.DocumentsPath); // get files presented in target directory string[] files = Directory.GetFiles(sourceDirectoryPath); foreach (string path in files) { // recognize format using (FormatBase format = FormatFactory.RecognizeFormat(path)) { // initialize DocFormat DocFormat docFormat = format as DocFormat; if (docFormat != null) { // get document properties DocMetadata properties = docFormat.DocumentProperties; // check if author is the same if (string.Equals(properties.Author, authorName, StringComparison.OrdinalIgnoreCase)) { // remove comments docFormat.ClearComments(); List <string> customKeys = new List <string>(); // find all custom keys foreach (KeyValuePair <string, PropertyValue> keyValuePair in properties) { if (!properties.IsBuiltIn(keyValuePair.Key)) { customKeys.Add(keyValuePair.Key); } } // and remove all of them foreach (string key in customKeys) { properties.Remove(key); } //====== yet to change things ========================= // and commit changes string fileName = Path.GetFileName(path); string outputFilePath = Common.MapDestinationFilePath(this.DocumentsPath + "/" + fileName); docFormat.Save(outputFilePath); //===================================================== } } } } Console.WriteLine("Press any key to exit."); }
public virtual void LoadXlsx(string file) { Format = DocFormat.Xlsx; if (!File.Exists(file)) { throw new ArgumentException("File " + file + " error"); } Book = new SpreadBook(); Book.Open(file); }
public virtual IWorkbookBase LoadNPoiStream(Stream fileXls, string fileName) { Format = DocFormat.Xls; Guard.Check(fileXls != null); Book = new NPoiWorkbook(); var npoiBook = Book as NPoiWorkbook; npoiBook.ReadStream(fileXls, fileName); return(Book); }
protected void loadInvDetails() { ArrayList invList = BackEndObjects.DocFormat. getDocFormatforEntityIdandDocTypeDB(Session[SessionFactory.MAIN_BUSINESS_ENTITY_ID_STRING].ToString(), BackEndObjects.DocFormat.DOCFORMAT_DOC_TYPE_INVOICE); DataTable dt = new DataTable(); dt.Columns.Add("Hidden"); dt.Columns.Add("Comp_Name"); dt.Columns.Add("Comp_Value"); int taxCompGridCounter = 0; for (int i = 0; i < invList.Count; i++) { DocFormat invObj = (DocFormat)invList[i]; String sectionType = invObj.getSection_type(); if (TextBox_INV_format_name.Text.Equals("")) { TextBox_INV_format_name.Text = invObj.getDocformat_name(); } switch (sectionType) { case BackEndObjects.DocFormat.DOCFORMAT_DOC_TYPE_INVOICE_SECTION_TYPE_TNC: TextBox_INV_TnC.Text = invObj.getText(); Label_TNC_flag_Inv.Text = TextBox_INV_TnC.Text.Equals("") ? "Y" : "N"; break; case BackEndObjects.DocFormat.DOCFORMAT_DOC_TYPE_INVOICE_SECTION_TYPE_TAX: dt.Rows.Add(); dt.Rows[taxCompGridCounter]["Hidden"] = invObj.getDocformat_id(); //Component name is the section type name dt.Rows[taxCompGridCounter]["Comp_Name"] = invObj.getSectionTypeName(); dt.Rows[taxCompGridCounter]["Comp_Value"] = invObj.getText(); taxCompGridCounter++; break; } } if (dt.Rows.Count > 0) { GridView_Inv_Tax_Comp.DataSource = dt; GridView_Inv_Tax_Comp.DataBind(); GridView_Inv_Tax_Comp.Visible = true; GridView_Inv_Tax_Comp.Columns[2].Visible = false; Session[SessionFactory.ADMIN_PREF_DOCFORMAT_MGMT_TAX_COMP_GRID] = dt; } }
public DocFormat GenerateFormat() { var format = new DocFormat { MiddleWareVersion = "v1.0" }; _scourer.Scour(); _xmlReader.Load(_scourer.ExecutionAssembly.GetDocumentPath()); format.Service = GenerateService(); format.Definitions = GenerateAllDefinitions().ToList(); format.Types = GenerateAllTypes().ToList(); return(format); }
/// <summary> /// Removes custom properties of Doc file and creates output file /// </summary> public static void RemoveCustomProperties() { try { //ExStart:RemoveCustomPropertyDocFormat // initialize DocFormat DocFormat docFormat = new DocFormat(Common.MapSourceFilePath(filePath)); // initialize DocMetadata DocMetadata metadata = docFormat.DocumentProperties; string propertyName = "New Custom Property"; // check if property is not built-in if (metadata.ContainsKey(propertyName)) { if (!metadata.IsBuiltIn(propertyName)) { // remove property metadata.Remove(propertyName); } else { Console.WriteLine("Can not remove built-in property."); } } else { Console.WriteLine("Property does not exist."); } bool isexist = metadata.ContainsKey(propertyName); // save file in destination folder docFormat.Save(Common.MapDestinationFilePath(filePath)); //ExEnd:RemoveCustomPropertyDocFormat Console.WriteLine("File saved in destination folder."); } catch (Exception exp) { Console.WriteLine(exp.Message); } }
/// <summary> /// Removes document comments of Doc file /// </summary> public static void RemoveComments() { try { // initialize DocFormat DocFormat docFormat = new DocFormat(Common.MapSourceFilePath(filePath)); // remove comments docFormat.ClearComments(); // save file in destination folder docFormat.Save(Common.MapDestinationFilePath(filePath)); Console.WriteLine("File saved in destination folder."); } catch (Exception exp) { Console.WriteLine(exp.Message); } }
//ExEnd:EnumerateMetadata /// <summary> /// shows how to use library in licensed mode using Dynabic.Metered account /// </summary> public static void UseDynabicMeteredAccount() { //ExStart:UseDynabicMeteredAccount // initialize Metered API GroupDocs.Metadata.Metered metered = new Metered(); // set-up credentials metered.SetMeteredKey(publicKey, privateKey); // do some work: // Open Word document DocFormat docFormat = new DocFormat(MapSourceFilePath("Documents/Doc/Metadata_testfile.docx")); // remove hidden metadata docFormat.RemoveHiddenData(new DocInspectionOptions(DocInspectorOptionsEnum.All)); // and get consumption quantity decimal consumptionQuantity = GroupDocs.Metadata.Metered.GetConsumptionQuantity(); //ExEnd:UseDynabicMeteredAccount }
public bool setFormat(string format) { if (format.Equals(DocFormat.doc.ToString())) this._Format = DocFormat.doc; else if (format.Equals(DocFormat.ppt.ToString())) this._Format = DocFormat.ppt; else if (format.Equals(DocFormat.pdf.ToString())) this._Format = DocFormat.pdf; else if (format.Equals(DocFormat.xls.ToString())) this._Format = DocFormat.xls; else if (format.Equals(DocFormat.docx.ToString())) this._Format = DocFormat.docx; else if (format.Equals(DocFormat.pptx.ToString())) this._Format = DocFormat.pptx; else if (format.Equals(DocFormat.xlsx.ToString())) this._Format = DocFormat.xlsx; else return false; return true; }
/// <summary> /// Gets word count and page count of Doc file /// </summary> public static void GetWordAndPageCount() { try { // initialize DocFormat DocFormat docFormat = new DocFormat(Common.MapSourceFilePath(filePath)); // Get words count... int wordsCount = docFormat.GetWordsCount(); // Get pages count... int pageCounts = docFormat.GetPagesCount(); Console.WriteLine("Words: {0}", wordsCount); Console.WriteLine("Pages: {0}", pageCounts); } catch (Exception exp) { Console.WriteLine(exp.Message); } }
/// <summary> /// Removes document properties of Doc file and creates output file /// </summary> public static void RemoveDocumentProperties() { try { //ExStart:RemoveBuiltinDocumentPropertiesDocFormat // initialize Docformat DocFormat docFormat = new DocFormat(Common.MapSourceFilePath(filePath)); //Clean metadata docFormat.CleanMetadata(); // save output file... docFormat.Save(Common.MapDestinationFilePath(filePath)); //ExEnd:RemoveBuiltinDocumentPropertiesDocFormat Console.WriteLine("File saved in destination folder."); } catch (Exception exp) { Console.WriteLine(exp.Message); } }
protected void Button_Inv_Update_Click(object sender, EventArgs e) { String sectionTnC = Label_TNC_flag_Inv.Text; //The sectionTnC label helps to determinte whethere the sections need an insert or update Boolean insertFlag = sectionTnC.Equals("Y"); Boolean updateStat = true; ArrayList docFormatList = new ArrayList(); DocFormat sectionTnCObj = new DocFormat(); DocFormat sectionTaxCompObj = new DocFormat(); String docFormatId = ""; if (sectionTnC.Equals("Y")) { if (!TextBox_INV_format_name.Text.Equals("") && !TextBox_INV_TnC.Text.Equals("")) { docFormatId = new BackEndObjects.Id().getNewId(BackEndObjects.Id.ID_TYPE_DOCFORMAT_ID_STRING); sectionTnCObj.setCmp_id(Session[SessionFactory.MAIN_BUSINESS_ENTITY_ID_STRING].ToString()); sectionTnCObj.setDoc_type(BackEndObjects.DocFormat.DOCFORMAT_DOC_TYPE_INVOICE); sectionTnCObj.setDocformat_id(docFormatId); sectionTnCObj.setDocformat_name(TextBox_INV_format_name.Text); sectionTnCObj.setSection_type(BackEndObjects.DocFormat.DOCFORMAT_DOC_TYPE_INVOICE_SECTION_TYPE_TNC); sectionTnCObj.setText(TextBox_INV_TnC.Text); docFormatList.Add(sectionTnCObj); } } else { Dictionary <String, String> whereCls = new Dictionary <string, string>(); whereCls.Add(BackEndObjects.DocFormat.DOCFORMAT_COL_CMP_ID, Session[SessionFactory.MAIN_BUSINESS_ENTITY_ID_STRING].ToString()); whereCls.Add(BackEndObjects.DocFormat.DOCFORMAT_COL_DOC_TYPE, BackEndObjects.DocFormat.DOCFORMAT_DOC_TYPE_INVOICE); whereCls.Add(BackEndObjects.DocFormat.DOCFORMAT_COL_SECTION_TYPE, BackEndObjects.DocFormat.DOCFORMAT_DOC_TYPE_INVOICE_SECTION_TYPE_TNC); Dictionary <String, String> targetVals = new Dictionary <string, string>(); targetVals.Add(BackEndObjects.DocFormat.DOCFORMAT_COL_TEXT, TextBox_INV_TnC.Text); targetVals.Add(BackEndObjects.DocFormat.DOCFORMAT_COL_DOCFORMAT_NAME, TextBox_INV_format_name.Text); BackEndObjects.DocFormat.updateDocFormatObjsDB(whereCls, targetVals, DBConn.Connections.OPERATION_UPDATE); updateStat = true; } try { Boolean refreshTaxCompGrid = false; if (!TextBox_Inv_Tax_Comp_Name.Text.Equals("") && !TextBox_Inv_Tax_Comp_Value.Text.Equals("")) { sectionTaxCompObj.setCmp_id(Session[SessionFactory.MAIN_BUSINESS_ENTITY_ID_STRING].ToString()); sectionTaxCompObj.setDoc_type(BackEndObjects.DocFormat.DOCFORMAT_DOC_TYPE_INVOICE); docFormatId = docFormatId.Equals("") ? new BackEndObjects.Id().getNewId(BackEndObjects.Id.ID_TYPE_DOCFORMAT_ID_STRING) : docFormatId; sectionTaxCompObj.setDocformat_id(docFormatId); sectionTaxCompObj.setDocformat_name(TextBox_INV_format_name.Text); sectionTaxCompObj.setSection_type(BackEndObjects.DocFormat.DOCFORMAT_DOC_TYPE_INVOICE_SECTION_TYPE_TAX); sectionTaxCompObj.setSectionTypeName(TextBox_Inv_Tax_Comp_Name.Text); sectionTaxCompObj.setText(TextBox_Inv_Tax_Comp_Value.Text); docFormatList.Add(sectionTaxCompObj); refreshTaxCompGrid = true; } if (docFormatList.Count > 0) { BackEndObjects.DocFormat.insertDocFormatDB(docFormatList); } if (refreshTaxCompGrid) { loadInvTaxCompGrid(); } Label_Inv_Update_stat.Visible = true; Label_Inv_Update_stat.ForeColor = System.Drawing.Color.Green; Label_Inv_Update_stat.Text = "Updated Successfully"; } catch (Exception ex) { Label_Inv_Update_stat.Visible = true; Label_Inv_Update_stat.ForeColor = System.Drawing.Color.Red; Label_Inv_Update_stat.Text = "Update Failed"; } }
public HttpResponseMessage Get(string file) { try { File.Copy(Utils._storagePath + "\\" + file, Utils._storagePath + "\\Cleaned_" + file, true); FileStream original = File.Open(Utils._storagePath + "\\Cleaned_" + file, FileMode.Open, FileAccess.ReadWrite); FileFormatChecker fileFormatChecker = new FileFormatChecker(original); DocumentType documentType = fileFormatChecker.GetDocumentType(); if (fileFormatChecker.VerifyFormat(documentType)) { switch (documentType) { case DocumentType.Doc: DocFormat docFormat = new DocFormat(original); docFormat.CleanMetadata(); docFormat.ClearBuiltInProperties(); docFormat.ClearComments(); docFormat.ClearCustomProperties(); docFormat.RemoveHiddenData(new DocInspectionOptions(DocInspectorOptionsEnum.All)); docFormat.Save(Utils._storagePath + "\\Cleaned_" + file); break; case DocumentType.Xls: XlsFormat xlsFormat = new XlsFormat(original); xlsFormat.CleanMetadata(); xlsFormat.ClearBuiltInProperties(); xlsFormat.ClearContentTypeProperties(); xlsFormat.ClearCustomProperties(); xlsFormat.RemoveHiddenData(new XlsInspectionOptions(XlsInspectorOptionsEnum.All)); xlsFormat.Save(Utils._storagePath + "\\Cleaned_" + file); break; case DocumentType.Pdf: PdfFormat pdfFormat = new PdfFormat(original); pdfFormat.CleanMetadata(); pdfFormat.ClearBuiltInProperties(); pdfFormat.ClearCustomProperties(); pdfFormat.RemoveHiddenData(new PdfInspectionOptions(PdfInspectorOptionsEnum.All)); pdfFormat.RemoveXmpData(); pdfFormat.Save(Utils._storagePath + "\\Cleaned_" + file); break; case DocumentType.Png: PngFormat pngFormat = new PngFormat(original); pngFormat.CleanMetadata(); pngFormat.RemoveXmpData(); pngFormat.Save(Utils._storagePath + "\\Cleaned_" + file); break; case DocumentType.Jpeg: JpegFormat jpegFormat = new JpegFormat(original); jpegFormat.CleanMetadata(); jpegFormat.RemoveExifInfo(); jpegFormat.RemoveGpsLocation(); jpegFormat.RemoveIptc(); jpegFormat.RemovePhotoshopData(); jpegFormat.RemoveXmpData(); jpegFormat.Save(original); break; case DocumentType.Bmp: BmpFormat bmpFormat = new BmpFormat(original); bmpFormat.CleanMetadata(); bmpFormat.Save(Utils._storagePath + "\\Cleaned_" + file); break; case DocumentType.Gif: GifFormat gifFormat = new GifFormat(original); gifFormat.CleanMetadata(); gifFormat.RemoveXmpData(); gifFormat.Save(Utils._storagePath + "\\Cleaned_" + file); break; case DocumentType.Msg: OutlookMessage outlookMessage = new OutlookMessage(original); outlookMessage.CleanMetadata(); outlookMessage.RemoveAttachments(); outlookMessage.Save(Utils._storagePath + "\\Cleaned_" + file); break; case DocumentType.Eml: EmlFormat emlFormat = new EmlFormat(original); emlFormat.CleanMetadata(); emlFormat.RemoveAttachments(); emlFormat.Save(Utils._storagePath + "\\Cleaned_" + file); break; case DocumentType.Dwg: DwgFormat dwgFormat = new DwgFormat(original); dwgFormat.CleanMetadata(); dwgFormat.Save(Utils._storagePath + "\\Cleaned_" + file); break; case DocumentType.Dxf: DxfFormat dxfFormat = new DxfFormat(original); dxfFormat.CleanMetadata(); dxfFormat.Save(Utils._storagePath + "\\Cleaned_" + file); break; default: DocFormat defaultDocFormat = new DocFormat(original); defaultDocFormat.CleanMetadata(); defaultDocFormat.ClearBuiltInProperties(); defaultDocFormat.ClearComments(); defaultDocFormat.ClearCustomProperties(); defaultDocFormat.RemoveHiddenData(new DocInspectionOptions(DocInspectorOptionsEnum.All)); defaultDocFormat.Save(Utils._storagePath + "\\Cleaned_" + file); break; } } else { throw new Exception("File format not supported."); } using (var ms = new MemoryStream()) { original = File.OpenRead(Utils._storagePath + "\\Cleaned_" + file); original.CopyTo(ms); var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(ms.ToArray()) }; result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = "Cleaned_" + file }; result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); original.Close(); File.Delete(Utils._storagePath + "\\Cleaned_" + file); return(result); } } catch (Exception exc) { throw exc; } }
/// <summary> /// Throw an Exception for Protected Document /// </summary> public static void DocumentProtectedException() { //ExStart:DocumentProtectedException // initialize DocFormat try { DocFormat docFormat = new DocFormat(Common.MapSourceFilePath(filePath)); // and try to get document properties var documentProperties = docFormat.DocumentProperties; } catch (DocumentProtectedException ex) { Console.WriteLine("File is protected by password PDF: {0}", ex.Message); } //ExEnd:DocumentProtectedException }
//ExEnd:ApplyLicense public static string CleanFile(string filePath) { try { try { //Apply license... ApplyLicense(); } catch (Exception exp) { MessageBox.Show("In Licence: " + exp.Message); } try { //Recognize format of file... FormatBase format = FormatFactory.RecognizeFormat(filePath); if (format.Type.ToString().ToLower() == "doc" || format.Type.ToString().ToLower() == "docx") { // initialize DocFormat... DocFormat docFormat = format as DocFormat; if (docFormat != null) { // get document properties... DocMetadata properties = new DocMetadata(); properties = docFormat.DocumentProperties; //Remove custom properties... foreach (KeyValuePair <string, PropertyValue> keyValuePair in properties) { if (!properties.IsBuiltIn(keyValuePair.Key)) { properties.Remove(keyValuePair.Key); } } //Reset built-in properties... properties.Author = ""; properties.Category = ""; properties.Comments = ""; properties.Company = ""; properties.ContentStatus = ""; properties.HyperlinkBase = ""; properties.Keywords = ""; properties.Manager = ""; properties.Title = ""; //Update metadata if file... MetadataUtility.UpdateMetadata(filePath, properties); } return("1"); } else if (format.Type.ToString().ToLower() == "xls" || format.Type.ToString().ToLower() == "xlsx") { //Initialize XlsFormat... XlsFormat xlsFormat = format as XlsFormat; if (xlsFormat != null) { //Get document properties... XlsMetadata properties = xlsFormat.DocumentProperties; //Remove custom properties... foreach (KeyValuePair <string, PropertyValue> keyValuePair in properties) { if (!properties.IsBuiltIn(keyValuePair.Key)) { properties.Remove(keyValuePair.Key); } } //Reset built-in properties... properties.Author = ""; properties.Category = ""; properties.Comments = ""; properties.Company = ""; properties.HyperlinkBase = ""; properties.Keywords = ""; properties.Manager = ""; properties.Title = ""; properties.Subject = ""; //Update metadata in files... MetadataUtility.UpdateMetadata(filePath, properties); } return("1"); } else if (format.Type.ToString().ToLower() == "ppt" || format.Type.ToString().ToLower() == "pptx") { //Initialize PptFormat... PptFormat pptFormat = format as PptFormat; if (pptFormat != null) { //Get document properties... PptMetadata properties = pptFormat.DocumentProperties; //Remove custom properties foreach (KeyValuePair <string, PropertyValue> keyValuePair in properties) { if (!properties.IsBuiltIn(keyValuePair.Key)) { properties.Remove(keyValuePair.Key); } } //Reset built-in properties... properties.Author = ""; properties.Category = ""; properties.Comments = ""; properties.Company = ""; properties.Keywords = ""; properties.Manager = ""; properties.Title = ""; properties.Subject = ""; //Update metadata of file... MetadataUtility.UpdateMetadata(filePath, properties); } return("1"); } else if (format.Type.ToString().ToLower() == "pdf") { // initialize PdfFormat... PdfFormat pdfFormat = format as PdfFormat; if (pdfFormat != null) { // get document properties... PdfMetadata properties = pdfFormat.DocumentProperties; // Remove custom properties... foreach (KeyValuePair <string, PropertyValue> keyValuePair in properties) { if (!properties.IsBuiltIn(keyValuePair.Key)) { properties.Remove(keyValuePair.Key); } } //Reset built-in properties... properties.Author = ""; properties.CreatedDate = DateTime.MinValue; properties.Keywords = ""; properties.ModifiedDate = DateTime.MinValue; properties.Subject = ""; properties.TrappedFlag = false; properties.Title = ""; //Update metadata of file... MetadataUtility.UpdateMetadata(filePath, properties); } return("1"); } else if (format.Type.ToString().ToLower() == "jpeg" || format.Type.ToString().ToLower() == "jpg") { //Get EXIF data if exists ExifMetadata exifMetadata = (ExifMetadata)MetadataUtility.ExtractSpecificMetadata(filePath, MetadataType.EXIF); //Get XMP data if exists XmpMetadata xmpMetadata = (XmpMetadata)MetadataUtility.ExtractSpecificMetadata(filePath, MetadataType.XMP); if (exifMetadata != null) { //Remove exif info... ExifInfo exifInfo = exifMetadata.Data; if (exifInfo.GPSData != null) { // set altitude, latitude and longitude to null values exifInfo.GPSData.Altitude = null; exifInfo.GPSData.Latitude = null; exifInfo.GPSData.LatitudeRef = null; exifInfo.GPSData.Longitude = null; exifInfo.GPSData.LongitudeRef = null; } exifInfo.BodySerialNumber = ""; exifInfo.CameraOwnerName = ""; exifInfo.CFAPattern = new byte[] { 0 }; } else { exifMetadata = new ExifMetadata(); } try { //Remove XMP data... XmpPacketWrapper xmpPacket = xmpMetadata.XmpPacket; if (xmpPacket != null) { if (xmpPacket.ContainsPackage(Namespaces.DublinCore)) { // if not - add DublinCore schema xmpPacket.AddPackage(new DublinCorePackage()); DublinCorePackage dublinCorePackage = (DublinCorePackage)xmpPacket.GetPackage(Namespaces.DublinCore); dublinCorePackage.Clear(); xmpMetadata.XmpPacket = xmpPacket; } } } catch { } //Update Exif info... try { MetadataUtility.UpdateMetadata(filePath, exifMetadata); } catch { } //Update XMP data... try { MetadataUtility.UpdateMetadata(filePath, xmpMetadata); } catch { } //Remove custom metadata if any... MetadataUtility.CleanMetadata(filePath); return("1"); } else if (format.Type.ToString().ToLower() == "png") { //Get XMP data... XmpMetadata xmpMetadata = (XmpMetadata)MetadataUtility.ExtractSpecificMetadata(filePath, MetadataType.XMP); try { //Remove XMP metadata... XmpPacketWrapper xmpPacket = xmpMetadata.XmpPacket; if (xmpPacket != null) { if (xmpPacket.ContainsPackage(Namespaces.DublinCore)) { // if not - add DublinCore schema xmpPacket.AddPackage(new DublinCorePackage()); DublinCorePackage dublinCorePackage = (DublinCorePackage)xmpPacket.GetPackage(Namespaces.DublinCore); dublinCorePackage.Clear(); xmpMetadata.XmpPacket = xmpPacket; //Update XMP metadata in file... MetadataUtility.UpdateMetadata(filePath, xmpMetadata); //Clean custom metadata if any... MetadataUtility.CleanMetadata(filePath); } } } catch { } return("1"); } else if (format.Type.ToString().ToLower() == "gif") { //Initialie GifFormat... GifFormat gifFormat = new GifFormat(filePath); //Check if Xmp supported... if (gifFormat.IsSupportedXmp) { //Get XMP data... XmpMetadata xmpMetadata = (XmpMetadata)MetadataUtility.ExtractSpecificMetadata(filePath, MetadataType.XMP); try { XmpPacketWrapper xmpPacket = xmpMetadata.XmpPacket; if (xmpPacket != null) { if (xmpPacket.ContainsPackage(Namespaces.DublinCore)) { // if not - add DublinCore schema xmpPacket.AddPackage(new DublinCorePackage()); DublinCorePackage dublinCorePackage = (DublinCorePackage)xmpPacket.GetPackage(Namespaces.DublinCore); dublinCorePackage.Clear(); xmpMetadata.XmpPacket = xmpPacket; //Update Xmp data in file... MetadataUtility.UpdateMetadata(filePath, xmpMetadata); //Clean custom metadata if any... MetadataUtility.CleanMetadata(filePath); } } } catch { } } return("1"); } else { return("Format not supported."); } } catch (Exception exp) { MessageBox.Show("Exception: " + exp.Message); return(exp.Message); } } catch (Exception exp) { return(exp.Message); } }
/// <summary> /// Gets comments, merge fields and hidden fields of Doc file /// </summary> public static void GetHiddenData() { try { //ExStart:GetHiddenDataInDocument // initialize DocFormat DocFormat docFormat = new DocFormat(Common.MapSourceFilePath(filePath)); // inspect document //InspectionResult inspectionResult = docFormat.InspectDocument(); DocInspectionResult inspectionResult = docFormat.InspectDocument(); // display comments if (inspectionResult.Comments.Length > 0) { Console.WriteLine("Comments in document:"); foreach (DocComment comment in inspectionResult.Comments) { Console.WriteLine("Comment: {0}", comment.Text); Console.WriteLine("Author: {0}", comment.Author); Console.WriteLine("Date: {0}", comment.CreatedDate); } } // display merge fields if (inspectionResult.Fields.Length > 0) { Console.WriteLine("\nMerge Fields in document:"); foreach (DocField field in inspectionResult.Fields) { Console.WriteLine(field.Name); } } // display hidden fields if (inspectionResult.HiddenText.Length > 0) { Console.WriteLine("\nHiddent text in document:"); foreach (string word in inspectionResult.HiddenText) { Console.WriteLine(word); } } //ExEnd:GetHiddenDataInDocument } catch (Exception exp) { Console.WriteLine(exp.Message); } }
/// <summary> /// Gets custom properties of Doc file /// </summary> public static void GetCustomProperties() { try { //ExStart:GetCustomPropertiesDocFormat // initialize DocFormat DocFormat docFormat = new DocFormat(Common.MapSourceFilePath(filePath)); // initialize metadata DocMetadata docMetadata = docFormat.DocumentProperties; // get properties Console.WriteLine("\nCustom Properties"); foreach (KeyValuePair<string, PropertyValue> keyValuePair in docMetadata) { // check if property is not built-in if (!docMetadata.IsBuiltIn(keyValuePair.Key)) { try { // get property value PropertyValue propertyValue = docMetadata[keyValuePair.Key]; Console.WriteLine("Key: {0}, Type:{1}, Value: {2}", keyValuePair.Key, propertyValue.Type, propertyValue); } catch { } } } //ExEnd:GetCustomPropertiesDocFormat } catch (Exception exp) { Console.WriteLine(exp.Message); } }
/// <summary> /// Updates document comments of Doc file /// </summary> public static void UpdateComments() { try { //ExStart:UpdateDocumentComment // initialize DocFormat DocFormat docFormat = new DocFormat(Common.MapSourceFilePath(filePath)); // extract comments DocComment[] comments = docFormat.ExtractComments(); if (comments.Length > 0) { // get first comment if exist var comment = comments[0]; // change comment's author comment.Author = "Jack London"; // change comment's text comment.Text = "This comment is created using GroupDocs.Metadata"; // update comment docFormat.UpdateComment(comment.Id, comment); } // save file in destination folder docFormat.Save(Common.MapDestinationFilePath(filePath)); Console.WriteLine("File saved in destination folder."); //ExEnd:UpdateDocumentComment } catch (Exception exp) { Console.WriteLine(exp.Message); } }
public JsonResult <List <PropertyItem> > Get(string file) { try { FileStream original = File.Open(Utils._storagePath + "\\" + file, FileMode.OpenOrCreate); FileFormatChecker fileFormatChecker = new FileFormatChecker(original); DocumentType documentType = fileFormatChecker.GetDocumentType(); List <PropertyItem> values = new List <PropertyItem>(); if (fileFormatChecker.VerifyFormat(documentType)) { switch (documentType) { case DocumentType.Doc: DocFormat docFormat = new DocFormat(original); values = AppendMetadata(docFormat.GetMetadata(), values); break; case DocumentType.Xls: XlsFormat xlsFormat = new XlsFormat(original); values = AppendMetadata(xlsFormat.GetMetadata(), values); break; case DocumentType.Pdf: PdfFormat pdfFormat = new PdfFormat(original); values = AppendMetadata(pdfFormat.GetMetadata(), values); values = AppendXMPData(pdfFormat.GetXmpData(), values); break; case DocumentType.Png: PngFormat pngFormat = new PngFormat(original); values = AppendMetadata(pngFormat.GetMetadata(), values); values = AppendXMPData(pngFormat.GetXmpData(), values); break; case DocumentType.Jpeg: JpegFormat jpegFormat = new JpegFormat(original); values = AppendMetadata(jpegFormat.GetMetadata(), values); values = AppendXMPData(jpegFormat.GetXmpData(), values); break; case DocumentType.Gif: GifFormat gifFormat = new GifFormat(original); values = AppendMetadata(gifFormat.GetMetadata(), values); values = AppendXMPData(gifFormat.GetXmpData(), values); break; case DocumentType.Bmp: BmpFormat bmpFormat = new BmpFormat(original); values = AppendMetadata(bmpFormat.GetMetadata(), values); break; case DocumentType.Msg: OutlookMessage outlookMessage = new OutlookMessage(original); values = AppendMetadata(outlookMessage.GetMsgInfo(), values); break; case DocumentType.Eml: EmlFormat emlFormat = new EmlFormat(original); values = AppendMetadata(emlFormat.GetEmlInfo(), values); break; case DocumentType.Dwg: DwgFormat dwgFormat = new DwgFormat(original); values = AppendMetadata(dwgFormat.GetMetadata(), values); break; case DocumentType.Dxf: DxfFormat dxfFormat = new DxfFormat(original); values = AppendMetadata(dxfFormat.GetMetadata(), values); break; default: DocFormat defaultDocFormat = new DocFormat(original); values = AppendMetadata(defaultDocFormat.GetMetadata(), values); break; } return(Json(values)); } else { throw new Exception("File format not supported."); } } catch (Exception exc) { throw exc; } }
/// <summary> /// Gets document comments of Doc file /// </summary> public static void GetDocumentComments() { try { // initialize DocFormat DocFormat docFormat = new DocFormat(Common.MapSourceFilePath(filePath)); //get comments... DocComment[] comments = docFormat.ExtractComments(); //get commnets by author... //DocComment[] comments = docFormat.ExtractComments("USMAN"); // display comments foreach (DocComment comment in comments) { Console.WriteLine("Author: ", comment.Author); Console.WriteLine("Created on Date: ", comment.CreatedDate); Console.WriteLine("Initials: ", comment.Initials); Console.WriteLine("\n"); } } catch (Exception exp) { Console.WriteLine(exp.Message); } }
/// <summary> /// Clears custom properties of Doc file and creates output file /// </summary> public static void ClearCustomProperties() { try { //ExStart:ClearCustomPropertyDocFormat // initialize DocFormat DocFormat docFormat = new DocFormat(Common.MapSourceFilePath(filePath)); // use one of the following methods // method:1 - clear custom properties docFormat.ClearCustomProperties(); // method:2 - clear custom properties docFormat.DocumentProperties.ClearCustomData(); // save file in destination folder docFormat.Save(Common.MapDestinationFilePath(filePath)); //ExEnd:ClearCustomPropertyDocFormat Console.WriteLine("File saved in destination folder."); } catch (Exception exp) { Console.WriteLine(exp.Message); } }
protected OfficeDocument(DocFormat format) : this(format, null) { }
/// <summary> /// Gets comments, merge fields and hidden fields of Doc file /// </summary> public static void RemoveMergeFields() { try { //ExStart:RemoveHiddenDataInDocument // initialize DocFormat DocFormat docFormat = new DocFormat(Common.MapSourceFilePath(filePath)); // inspect document //InspectionResult inspectionResult = docFormat.InspectDocument(); DocInspectionResult inspectionResult = docFormat.InspectDocument(); // if merge fields are presented if (inspectionResult.Fields.Length > 0) { // remove it docFormat.RemoveHiddenData(new DocInspectionOptions(DocInspectorOptionsEnum.Fields)); // save file in destination folder docFormat.Save(Common.MapDestinationFilePath(filePath)); } //ExEnd:RemoveHiddenDataInDocument Console.WriteLine("File saved in destination folder."); } catch (Exception exp) { Console.WriteLine(exp.Message); } }
//ExEnd:SourceODTProjectFilePath /// <summary> /// Gets properties of Open Document Format file /// </summary> public static void GetOdtMetadata() { try { //ExStart:ReadOdtMetadata // initialize DocFormat with ODT file's path DocFormat docFormat = new DocFormat(Common.MapSourceFilePath(filePath)); // read all metadata properties Metadata metadata = docFormat.DocumentProperties; // and display them foreach (MetadataProperty property in metadata) { Console.WriteLine(property); } //ExEnd:ReadOdtMetadata } catch (Exception ex) { Console.WriteLine(ex.Message); } }
/// <summary> /// Save Changes after updating metadata of specific format /// </summary> public static void SaveFileAfterMetadataUpdate() { //ExStart:SaveFileAfterMetadataUpdate // initialize DocFormat DocFormat docFormat = new DocFormat(Common.MapSourceFilePath(filePath)); // update document properties docFormat.DocumentProperties.Author = "Joe Doe"; docFormat.DocumentProperties.Company = "Aspose"; // and commit changes docFormat.Save(); //ExEnd:SaveFileAfterMetadataUpdate }
/// <summary> /// Detects document protection /// </summary> public static void DetectProtection(string filePath) { try { //ExStart:DetectProtection FormatBase format = FormatFactory.RecognizeFormat(Common.MapSourceFilePath(filePath)); if (format.Type.ToString().ToLower() == "doc") { // initialize DocFormat DocFormat docFormat = new DocFormat(Common.MapSourceFilePath(filePath)); // determines whether document is protected by password Console.WriteLine(docFormat.IsProtected ? "Document is protected" : "Document is protected"); } else if (format.Type.ToString().ToLower() == "pdf") { // initialize DocFormat PdfFormat pdfFormat = new PdfFormat(Common.MapSourceFilePath(filePath)); // determines whether document is protected by password Console.WriteLine(pdfFormat.IsProtected ? "Document is protected" : "Document is protected"); } else if (format.Type.ToString().ToLower() == "xls") { // initialize DocFormat XlsFormat xlsFormat = new XlsFormat(Common.MapSourceFilePath(filePath)); // determines whether document is protected by password Console.WriteLine(xlsFormat.IsProtected ? "Document is protected" : "Document is protected"); } else if (format.Type.ToString().ToLower() == "ppt") { // initialize DocFormat PptFormat pptFormat = new PptFormat(Common.MapSourceFilePath(filePath)); // determines whether document is protected by password Console.WriteLine(pptFormat.IsProtected ? "Document is protected" : "Document is protected"); } else { Console.WriteLine("Invalid Format."); } //ExEnd:DetectProtection } catch (Exception exp) { Console.WriteLine("Exception occurred: " + exp.Message); } }