//09/05/2017 - SaveDocument before adding signatures private void SaveAsWordDocumentWithoutSignatures(string wordVersion) { Word.Document doc = Globals.ThisAddIn.Application.ActiveDocument; if (File.Exists(wordVersion)) { File.Delete(wordVersion); } //11/05/2017 - protect before saving, but then unprotect after saving //as the process of saving Signature images requires the unptorected document object noReset = false; object password = "******"; object useIRM = false; object enforceStyleLock = false; doc.Protect(Word.WdProtectionType.wdAllowOnlyReading, ref noReset, ref password, ref useIRM, ref enforceStyleLock); var persistFile = (System.Runtime.InteropServices.ComTypes.IPersistFile)doc; persistFile.Save(wordVersion, false); //11/05/2017 doc.Unprotect(password); }
public void PastTest() { Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.ApplicationClass(); app.Visible = false; Microsoft.Office.Interop.Word.Document doc = app.Documents.Open(@"C:\Users\Administrator\Desktop\WorkFiles\Letter Automation\Template\NewTemplate\(chi) Cancellation of PW1.doc", false); doc.Activate(); doc.Tables[2].Cell(2, 2).Range.FormFields[1].Result = "44444444"; int count = doc.FormFields.Count; doc.Tables[1].ConvertToText(WdTableFieldSeparator.wdSeparateByParagraphs, false); doc.Tables[2].Cell(1, 3).Range.Text = "33"; doc.Tables[3].Rows.Add(); object unite = WdUnits.wdStory; app.Selection.EndKey(ref unite, Type.Missing); //将光标移动到文档末尾 doc.Tables[3].Rows[1].Cells[1].Range.Paste(); doc.Tables[3].Rows.Add(); doc.Protect(WdProtectionType.wdAllowOnlyFormFields, true, Type.Missing, Type.Missing, true); doc.Save(); doc.Save(); doc.Close(); app.Quit(); }
internal static void SaveDocumentAsWordWithoutSignatures(Word.Document document, string targetPath) { try { object missing = Missing.Value; //Save as word document as well - this need to be the text without the signatures string wordVersion = Path.Combine(Path.GetDirectoryName(targetPath), (Path.GetFileNameWithoutExtension(targetPath))); if (File.Exists(wordVersion)) { File.Delete(wordVersion); } //08/05/2017 - add password try { object noReset = false; object password = "******"; object useIRM = false; object enforceStyleLock = false; document.Protect(Word.WdProtectionType.wdAllowOnlyReading, ref noReset, ref password, ref useIRM, ref enforceStyleLock); } catch (Exception ex) { logger.LogException(LogLevel.Error, "SaveDocumentAsWordWithoutSignatures", ex); } //24/05/2017 document.SaveAs( wordVersion, ref missing, //WdSaveFormat.wdFormatDocument, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing ); //24/05/2017 //remove password as this document will be used to insert pictures document.Unprotect("NEOPHYTE"); } catch (System.IO.IOException ex) { logger.LogException(LogLevel.Error, "SaveDocumentAsWordWithoutSignatures", ex); throw ex; } catch (Exception ex) { logger.LogException(LogLevel.Error, "SaveDocumentAsWordWithoutSignatures", ex); } }
/// <summary> /// 文档加密 /// </summary> /// <param name="Doc">文档对象</param> /// <param name="DocPassword">密码</param> public void InsertEditPwd(ref Microsoft.Office.Interop.Word.Document Doc, string DocPassword) { object NoReset = false; object Pwd = DocPassword; object enforce = false; Doc.Protect(Microsoft.Office.Interop.Word.WdProtectionType.wdAllowOnlyReading, ref NoReset, ref Pwd, ref missing, ref enforce); }
public string ConvertDocumentTo(string sourcePath, string documentToCreatePath, object fileFormat) // WdSaveFormat.wdFormatPDF; { Microsoft.Office.Interop.Word.Application msWordDoc = null; Microsoft.Office.Interop.Word.Document doc = null; object oMissing = System.Reflection.Missing.Value; msWordDoc = new Microsoft.Office.Interop.Word.Application { Visible = false, ScreenUpdating = false }; doc = msWordDoc.Documents.Open(sourcePath, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing , ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); try { if (doc != null) { doc.Activate(); doc.Protect(WdProtectionType.wdAllowOnlyReading, ref oMissing, ref oMissing, ref oMissing, ref oMissing); //doc.ReadOnly = true; // save Document as PDF //object fileFormat = WdSaveFormat.wdFormatPDF; doc.SaveAs(documentToCreatePath, ref fileFormat, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); } else { return("error"); } } catch (Exception) { return("error"); throw; } finally { if (doc != null) { object saveChanges = WdSaveOptions.wdDoNotSaveChanges; doc.Close(ref saveChanges, ref oMissing, ref oMissing); //Util.releaseObject(doc); } ((_Application)msWordDoc).Quit(ref oMissing, ref oMissing, ref oMissing); //Util.releaseObject(msWordDoc); msWordDoc = null; } return(documentToCreatePath); }
public void TurnOnProtection(int type, string password) { if (_document == null || _document.ProtectionType != WordOM.WdProtectionType.wdNoProtection) { return; } _document.Protect((WordOM.WdProtectionType)type, true, password); ToggleDocumentEditableShade(); }
public static bool protect(Word.Document myDoc) { object False = (object)false; object psd = (object)"jwsj"; if (myDoc == null) { return(false); } myDoc.Protect(Word.WdProtectionType.wdAllowOnlyReading, ref False, ref psd, ref False, ref False); return(true); }
private void Init() { try { this.Cursor = Cursors.WaitCursor; string path = XCommon.TempPath; this.m_FileName = Guid.NewGuid().ToString(); m_FileName = this.m_FileAttachmentBusiness.DownLoadFile(m_EquipmentReceiveInfo.ID, path, m_FileName); if (m_FileName != string.Empty) { XEquipmentReceiveWordTool.FillWordValue(m_FileName, m_EquipmentReceiveInfo); this.fcWord.Open(m_FileName, true, null, null, null); Word.Document dct = this.fcWord.ActiveDocument as Word.Document; if (dct.ProtectionType == Word.WdProtectionType.wdAllowOnlyComments) { dct.Unprotect(); } if (dct.ProtectionType == Word.WdProtectionType.wdNoProtection) { dct.Protect(Word.WdProtectionType.wdAllowOnlyComments); } } else { XMessageBox.ShowError("未找到要打印的报告文档!"); this.Close(); } } catch (Exception ex) { XErrorLogTool.WriteLog(ex.ToString()); } finally { this.Cursor = Cursors.Default; } }
//10/05/2017 private void PasswordProtectDocument(string fileName) { Word.Document doc = null; object missing = System.Reflection.Missing.Value; object readOnly = false; object visible = true; object fileToOpen = fileName; try { doc = Globals.ThisAddIn.Application.Documents.Open(ref fileToOpen, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref visible, ref visible, ref missing, ref missing, ref missing); try { doc.Activate(); object noReset = false; object password = "******"; object useIRM = false; object enforceStyleLock = false; doc.Protect(Word.WdProtectionType.wdAllowOnlyReading, ref noReset, ref password, ref useIRM, ref enforceStyleLock); doc.SaveAs(ref fileToOpen, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); } catch (Exception) { // } } catch (Exception ex) { } finally { doc.Close(ref missing, ref missing, ref missing); } }
//public string suva_EventDatetimeDate; //public string suva_EventDatetimeHour; //public string suva_EventDatetimeMin; //public string suva_EventDatetimeWeekday; //public bool suva_CompanyMode1; //public bool suva_CompanyMode2; //public bool suva_CompanyMode3; //public string suva_CompanyName; //public string suva_CompanyAddress; //public string suva_CompanyZIP; //public string suva_CompanyCity; //public string suva_CompanySector; //public string suva_EmployerAccountNo; //public string suva_NumberOfEmployees; //public string suva_ContractorName; //public string suva_ContractorAddress; //public string suva_ContractorZIP; //public string suva_ContractorCity; //public string suva_ContractorAccountNo; //public string suva_ContractorContact; //public string suva_ContractorContactTel; //public string suva_VictimLastname; //public string suva_VictimFirstname; //public string suva_VictimAddress; //public string suva_VictimZIP; //public string suva_VictimCity; //public string suva_VictimInsuranceComp; //public string suva_VictimInsuranceNo; //public string suva_VictimBirthdateDay; //public string suva_VictimBirthdateMonth; //public string suva_VictimBirthdateYear; //public bool suva_VictimGender1; //public bool suva_VictimGender2; //public string suva_VictimNationality; //public string suva_VictimHiredate; //public string suva_VictimEmployedAs; //public string suva_VictimPersnr; //public string suva_VictimCostCenter; //public bool suva_EmploymentStatus1; //public bool suva_EmploymentStatus2; //public bool suva_EmploymentStatus3; //public bool suva_EmploymentStatus4; //public bool suva_EmploymentExtent1; //public bool suva_EmploymentExtent2; //public bool suva_EmploymentLimit0; //public bool suva_EmploymentLimit1; //public string suva_WorktimeStartHour; //public string suva_WorktimeStartMin; //public string suva_WorktimeEndHour; //public string suva_WorktimeEndMin; //public string suva_OvertimeStartHour; //public string suva_OvertimeStartMin; //public string suva_OvertimeEndHour; //public string suva_OvertimeEndMin; //public bool suva_AccidentLocation1; //public bool suva_AccidentLocation2; //public string suva_AccidentWorkplace; //public string suva_AccidentWorkplaceDet; //public string suva_TypeOfWork; //public string suva_CourseOfEvents; //public bool suva_ReportedBy1; //public bool suva_ReportedBy2; //public bool suva_ReportedBy4; //public bool suva_ReportedBy8; //public string suva_Bodypart; //public string suva_NatureOfInjury; //public bool suva_Attenders1; //public bool suva_Attenders2; //public bool suva_Attenders3; //public string suva_AttenderDetails; //public bool suva_TravelaccidentType1; //public bool suva_TravelaccidentType2; //public bool suva_TravelaccidentType3; //public bool suva_TravelaccidentType4; //public string suva_TravelaccidentPurpos; //public string suva_TravelaccidentOffset; //public string suva_TravelaccidentDest; //public bool suva_Ambulance1; //public bool suva_Ambulance2; //public bool suva_Ambulance3; //public string suva_AmbulanceOrganisat; //public bool suva_InvestigatorPolice; //public string suva_InvestigatorPoliceSt; //public bool suva_InvestAuthority; //public string suva_InvestAuthorityOff; //public bool suva_Workstopped1; //public bool suva_Workstopped2; //public bool suva_Workstopped3; //public string suva_WorkstoppedDate; //public string suva_WorkstoppedHour; //public string suva_WorkstoppedMin; //public bool suva_FatalityRelatives0; //public bool suva_FatalityRelatives1; //public bool suva_FatalityRelations1; //public bool suva_FatalityRelations2; //public bool suva_SickLeave0; //public bool suva_SickLeave1; //public bool suva_SickLeave2; //public string suva_SickLeaveEnded; //public bool suva_Hospital0; //public bool suva_Hospital1; //public bool suva_HospitalStay1; //public bool suva_HospitalStay2; //public string suva_HospitalEntry; //public string suva_HospitalName; //public string suva_Hospitaladdress; //public bool suva_DoctorTreatment0; //public bool suva_DoctorTreatment1; //public string suva_DoctorDate; //public string suva_DoctorName; //public string suva_DoctorAddress; //public bool suva_ObligationToTrain0; //public bool suva_ObligationToTrain1; //public string suva_TrainingText; //public string suva_ReporterNameFunction; //public string suva_BossNameFunction; //public string suva_ContactTel; //public string suva_ContactFax; //public string suva_ContactEMail; //public string suva_IssuedAt; //public string suva_Issued; /// <summary> /// Makes a doc file representing the filled-in SUVA form /// </summary> public bool Render(string rpt_temp_path, ref MemoryStream docstream) { #if LINUX return(false); #else DateTime nowtime = DateTime.UtcNow; const string temp_file_naming = "sherm-suva-temp-doc-template-{0}.doc"; const string dest_file_naming = "sherm-suva-temp-doc-complete-{0}.doc"; const string result_file_naming = "sherm-suva-temp-doc-result-{0}.{1}"; string temp_file_name = String.Format(temp_file_naming, nowtime.ToString("yyyyMMddHHmmss")); string dest_file_name = String.Format(dest_file_naming, nowtime.ToString("yyyyMMddHHmmss")); string result_file_name = String.Format(result_file_naming, nowtime.ToString("yyyyMMddHHmmss"), this.GetResultFileExtension()); object missing = System.Reflection.Missing.Value; object o_false = false; object o_true = true; string templateResourcePath = GetTemplateResourcePath(); try { if (docstream == null) { docstream = new MemoryStream(); } string tempPath = rpt_temp_path; /* [dlatikay 20121121] we do not bother the system, we have our own: was: Path.GetTempPath(); */ string temp_file_path = Path.Combine(tempPath, temp_file_name); string dest_file_path = Path.Combine(tempPath, dest_file_name); object result_file_path = Path.Combine(tempPath, result_file_name); /* 1. open the template */ using (var t_doc = new System.IO.BinaryReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(templateResourcePath))) { /* 1a. we must persist it in the temporary files folder */ using (var os = new FileStream(temp_file_path, FileMode.Create, FileAccess.Write)) { using (BinaryWriter t_doc_wr = new BinaryWriter(os)) { byte[] tempdoccontent = t_doc.ReadBytes((int)t_doc.BaseStream.Length); t_doc_wr.Write(tempdoccontent); } } } /* remove the read-only attribute */ FileAttributes attr = File.GetAttributes(temp_file_path); attr &= ~FileAttributes.ReadOnly; /* lovely */ File.SetAttributes(temp_file_path, attr); /* 1b. get us an instance of MS Word and open the template */ Word.Application word = null; try { object o_temp_file_path = temp_file_path; object o_dest_file_path = dest_file_path; word = new Word.Application(); Word.Document doc = word.Documents.Open(ref o_temp_file_path, ref o_false, ref o_true, ref o_false, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref o_false, ref o_false, ref missing, ref o_true, ref missing); doc.SaveAs(ref o_dest_file_path, ref missing, ref missing, ref missing, ref o_false, ref missing, ref o_false, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); /* set the standard (builtin) document properties */ object oBuiltInProps = doc.BuiltInDocumentProperties; Type tBuiltInProps = oBuiltInProps.GetType(); tBuiltInProps.InvokeMember("Item", BindingFlags.Default | BindingFlags.SetProperty, null, oBuiltInProps, new object[] { "Title", documenttitle }); tBuiltInProps.InvokeMember("Item", BindingFlags.Default | BindingFlags.SetProperty, null, oBuiltInProps, new object[] { "Subject", documentsubject }); tBuiltInProps.InvokeMember("Item", BindingFlags.Default | BindingFlags.SetProperty, null, oBuiltInProps, new object[] { "Author", documentauthor }); tBuiltInProps.InvokeMember("Item", BindingFlags.Default | BindingFlags.SetProperty, null, oBuiltInProps, new object[] { "Manager", documentmanager }); tBuiltInProps.InvokeMember("Item", BindingFlags.Default | BindingFlags.SetProperty, null, oBuiltInProps, new object[] { "Company", documentcompany }); tBuiltInProps.InvokeMember("Item", BindingFlags.Default | BindingFlags.SetProperty, null, oBuiltInProps, new object[] { "Category", documentcategory }); tBuiltInProps.InvokeMember("Item", BindingFlags.Default | BindingFlags.SetProperty, null, oBuiltInProps, new object[] { "Keywords", documentkeywords }); tBuiltInProps.InvokeMember("Item", BindingFlags.Default | BindingFlags.SetProperty, null, oBuiltInProps, new object[] { "Comments", documentcomments }); /* set the extended (custom) document properties */ /* now its time to set all the bookmarks */ //doc.Unprotect(ref missing); SetFormfieldText(doc, "VictimBirthDate", suva_VictimBirthdate); SetFormfieldText(doc, "VictimEmployedAs", suva_VictimEmployedAs); SetFormfieldText(doc, "Bodypart", suva_Bodypart); SetFormfieldText(doc, "Bodyside", suva_Bodyside); SetFormfieldCheck(doc, "WorkStoppedYes", suva_WorkStopped); SetFormfieldCheck(doc, "WorkStoppedNo", !suva_WorkStopped); SetFormfieldText(doc, "WorkStoppedDate", suva_WorkStoppedDatetime); SetFormfieldText(doc, "LastWorkDay", suva_LastWorkday); SetFormfieldText(doc, "ResumedWork", suva_ResumedWork); SetFormfieldText(doc, "HospitalName", suva_HospitalName); SetFormfieldText(doc, "HospitalName2", suva_HospitalName2); SetFormfieldText(doc, "HospitalAddress", suva_HosptialAddress); SetFormfieldText(doc, "HospitalAddress2", suva_HosptialAddress2); //SetFormfieldText(doc, "EventDatetimeDate", suva_EventDatetimeDate); //SetFormfieldText(doc, "EventDatetimeHour", suva_EventDatetimeHour); //SetFormfieldText(doc, "EventDatetimeMin", suva_EventDatetimeMin); //SetFormfieldText(doc, "EventDatetimeWeekday", suva_EventDatetimeWeekday); //SetFormfieldCheck(doc, "CompanyMode1", suva_CompanyMode1); //SetFormfieldCheck(doc, "CompanyMode2", suva_CompanyMode2); //SetFormfieldCheck(doc, "CompanyMode3", suva_CompanyMode3); //SetFormfieldText(doc, "CompanyName", suva_CompanyName); //SetFormfieldText(doc, "CompanyAddress", suva_CompanyAddress); //SetFormfieldText(doc, "CompanyZIP", suva_CompanyZIP); //SetFormfieldText(doc, "CompanyCity", suva_CompanyCity); //SetFormfieldText(doc, "CompanySector", suva_CompanySector); //SetFormfieldText(doc, "EmployerAccountNo", suva_EmployerAccountNo); //SetFormfieldText(doc, "NumberOfEmployees", suva_NumberOfEmployees); //SetFormfieldText(doc, "ContractorName", suva_ContractorName); //SetFormfieldText(doc, "ContractorAddress", suva_ContractorAddress); //SetFormfieldText(doc, "ContractorZIP", suva_ContractorZIP); //SetFormfieldText(doc, "ContractorCity", suva_ContractorCity); //SetFormfieldText(doc, "ContractorAccountNo", suva_ContractorAccountNo); //SetFormfieldText(doc, "ContractorContact", suva_ContractorContact); //SetFormfieldText(doc, "ContractorContactTel", suva_ContractorContactTel); //SetFormfieldText(doc, "VictimLastname", suva_VictimLastname); //SetFormfieldText(doc, "VictimFirstname", suva_VictimFirstname); //SetFormfieldText(doc, "VictimAddress", suva_VictimAddress); //SetFormfieldText(doc, "VictimZIP", suva_VictimZIP); //SetFormfieldText(doc, "VictimCity", suva_VictimCity); //SetFormfieldText(doc, "VictimInsuranceComp", suva_VictimInsuranceComp); //SetFormfieldText(doc, "VictimInsuranceNo", suva_VictimInsuranceNo); //SetFormfieldText(doc, "VictimBirthdateDay", suva_VictimBirthdateDay); //SetFormfieldText(doc, "VictimBirthdateMonth", suva_VictimBirthdateMonth); //SetFormfieldText(doc, "VictimBirthdateYear", suva_VictimBirthdateYear); //SetFormfieldCheck(doc, "VictimGender1", suva_VictimGender1); //SetFormfieldCheck(doc, "VictimGender2", suva_VictimGender2); //SetFormfieldText(doc, "VictimNationality", suva_VictimNationality); //SetFormfieldText(doc, "VictimHiredate", suva_VictimHiredate); //SetFormfieldText(doc, "VictimEmployedAs", suva_VictimEmployedAs); //SetFormfieldCheck(doc, "EmploymentStatus1", suva_EmploymentStatus1); //SetFormfieldCheck(doc, "EmploymentStatus2", suva_EmploymentStatus2); //SetFormfieldCheck(doc, "EmploymentStatus3", suva_EmploymentStatus3); //SetFormfieldCheck(doc, "EmploymentStatus4", suva_EmploymentStatus4); //SetFormfieldCheck(doc, "EmploymentExtent1", suva_EmploymentExtent1); //SetFormfieldCheck(doc, "EmploymentExtent2", suva_EmploymentExtent2); //SetFormfieldCheck(doc, "EmploymentLimit0", suva_EmploymentLimit0); //SetFormfieldCheck(doc, "EmploymentLimit1", suva_EmploymentLimit1); //SetFormfieldText(doc, "WorktimeStartHour", suva_WorktimeStartHour); //SetFormfieldText(doc, "WorktimeStartMin", suva_WorktimeStartMin); //SetFormfieldText(doc, "WorktimeEndHour", suva_WorktimeEndHour); //SetFormfieldText(doc, "WorktimeEndMin", suva_WorktimeEndMin); //SetFormfieldText(doc, "OvertimeStartHour", suva_OvertimeStartHour); //SetFormfieldText(doc, "OvertimeStartMin", suva_OvertimeStartMin); //SetFormfieldText(doc, "OvertimeEndHour", suva_OvertimeEndHour); //SetFormfieldText(doc, "OvertimeEndMin", suva_OvertimeEndMin); //SetFormfieldCheck(doc, "AccidentLocation1", suva_AccidentLocation1); //SetFormfieldCheck(doc, "AccidentLocation2", suva_AccidentLocation2); //SetFormfieldText(doc, "AccidentWorkplace", suva_AccidentWorkplace); //SetFormfieldText(doc, "AccidentWorkplaceDet", suva_AccidentWorkplaceDet); //SetFormfieldText(doc, "TypeOfWork", suva_TypeOfWork); //SetFormfieldText(doc, "CourseOfEvents", suva_CourseOfEvents); //SetFormfieldCheck(doc, "ReportedBy1", suva_ReportedBy1); //SetFormfieldCheck(doc, "ReportedBy2", suva_ReportedBy2); //SetFormfieldCheck(doc, "ReportedBy4", suva_ReportedBy4); //SetFormfieldCheck(doc, "ReportedBy8", suva_ReportedBy8); //SetFormfieldText(doc, "Bodypart", suva_Bodypart); //SetFormfieldText(doc, "NatureOfInjury", suva_NatureOfInjury); //SetFormfieldCheck(doc, "Attenders1", suva_Attenders1); //SetFormfieldCheck(doc, "Attenders2", suva_Attenders2); //SetFormfieldCheck(doc, "Attenders3", suva_Attenders3); //SetFormfieldText(doc, "AttenderDetails", suva_AttenderDetails); //SetFormfieldCheck(doc, "TravelaccidentType1", suva_TravelaccidentType1); //SetFormfieldCheck(doc, "TravelaccidentType2", suva_TravelaccidentType2); //SetFormfieldCheck(doc, "TravelaccidentType3", suva_TravelaccidentType3); //SetFormfieldCheck(doc, "TravelaccidentType4", suva_TravelaccidentType4); //SetFormfieldText(doc, "TravelaccidentPurpos", suva_TravelaccidentPurpos); //SetFormfieldText(doc, "TravelaccidentOffset", suva_TravelaccidentOffset); //SetFormfieldText(doc, "TravelaccidentDest", suva_TravelaccidentDest); //SetFormfieldCheck(doc, "Ambulance1", suva_Ambulance1); //SetFormfieldCheck(doc, "Ambulance2", suva_Ambulance2); //SetFormfieldCheck(doc, "Ambulance3", suva_Ambulance3); //SetFormfieldText(doc, "AmbulanceOrganisat", suva_AmbulanceOrganisat); //SetFormfieldCheck(doc, "InvestigatorPolice", suva_InvestigatorPolice); //SetFormfieldText(doc, "InvestigatorPoliceSt", suva_InvestigatorPoliceSt); //SetFormfieldCheck(doc, "InvestAuthority", suva_InvestAuthority); //SetFormfieldText(doc, "InvestAuthorityOff", suva_InvestAuthorityOff); //SetFormfieldCheck(doc, "Workstopped1", suva_Workstopped1); //SetFormfieldCheck(doc, "Workstopped2", suva_Workstopped2); //SetFormfieldCheck(doc, "Workstopped3", suva_Workstopped3); //SetFormfieldText(doc, "WorkstoppedDate", suva_WorkstoppedDate); //SetFormfieldText(doc, "WorkstoppedHour", suva_WorkstoppedHour); //SetFormfieldText(doc, "WorkstoppedMin", suva_WorkstoppedMin); //SetFormfieldCheck(doc, "FatalityRelatives0", suva_FatalityRelatives0); //SetFormfieldCheck(doc, "FatalityRelatives1", suva_FatalityRelatives1); //SetFormfieldCheck(doc, "FatalityRelations1", suva_FatalityRelations1); //SetFormfieldCheck(doc, "FatalityRelations2", suva_FatalityRelations2); //SetFormfieldCheck(doc, "SickLeave0", suva_SickLeave0); //SetFormfieldCheck(doc, "SickLeave1", suva_SickLeave1); //SetFormfieldCheck(doc, "SickLeave2", suva_SickLeave2); //SetFormfieldText(doc, "SickLeaveEnded", suva_SickLeaveEnded); //SetFormfieldCheck(doc, "Hospital0", suva_Hospital0); //SetFormfieldCheck(doc, "Hospital1", suva_Hospital1); //SetFormfieldCheck(doc, "HospitalStay1", suva_HospitalStay1); //SetFormfieldCheck(doc, "HospitalStay2", suva_HospitalStay2); //SetFormfieldText(doc, "HospitalEntry", suva_HospitalEntry); //SetFormfieldText(doc, "HospitalName", suva_HospitalName); //SetFormfieldText(doc, "Hospitaladdress", suva_Hospitaladdress); //SetFormfieldCheck(doc, "DoctorTreatment0", suva_DoctorTreatment0); //SetFormfieldCheck(doc, "DoctorTreatment1", suva_DoctorTreatment1); //SetFormfieldText(doc, "DoctorDate", suva_DoctorDate); //SetFormfieldText(doc, "DoctorName", suva_DoctorName); //SetFormfieldText(doc, "DoctorAddress", suva_DoctorAddress); //SetFormfieldCheck(doc, "ObligationToTrain0", suva_ObligationToTrain0); //SetFormfieldCheck(doc, "ObligationToTrain1", suva_ObligationToTrain1); //SetFormfieldText(doc, "TrainingText", suva_TrainingText); //SetFormfieldText(doc, "ReporterNameFunction", suva_ReporterNameFunction); //SetFormfieldText(doc, "BossNameFunction", suva_BossNameFunction); //SetFormfieldText(doc, "ContactTel", suva_ContactTel); //SetFormfieldText(doc, "ContactFax", suva_ContactFax); //SetFormfieldText(doc, "ContactEMail", suva_ContactEMail); //SetFormfieldText(doc, "IssuedAt", suva_IssuedAt); //SetFormfieldText(doc, "Issued", suva_Issued); /* set export type dependend bookmarks */ switch (this.SUVAExportType) { default: { break; } } doc.Protect(Microsoft.Office.Interop.Word.WdProtectionType.wdAllowOnlyFormFields, ref o_true, ref missing, ref o_false, ref o_false); /* persist it */ #pragma warning disable 0467 /* the pragma is for the event member */ doc.Save(); object fileFormat = missing; if (this.SUVAExportType != SUVAExportType.Default) { fileFormat = Word.WdSaveFormat.wdFormatPDF; } doc.SaveAs(ref result_file_path, ref fileFormat, ref missing, ref missing, ref o_false, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); doc.Close(ref o_false, ref missing, ref missing); #pragma warning restore 0467 } catch (Exception) { /* up the exception chain */ throw; } finally { /* cleanup word */ if (word != null) { try { #pragma warning disable 0467 /* the pragma is for the event member */ word.Quit(ref missing, ref missing, ref missing); #pragma warning restore 0467 } catch (Exception) { } try { System.Runtime.InteropServices.Marshal.FinalReleaseComObject(word); } catch (System.Exception) { } word = null; } } /* need to wait until the COM handles are really closed */ /* now we load the document into memory and deliver the stream. the file is deleted. */ using (FileStream ifs = new FileStream(result_file_path.ToString(), FileMode.Open, FileAccess.Read)) { using (BinaryReader rd = new BinaryReader(ifs)) { docstream.Write(rd.ReadBytes((int)rd.BaseStream.Length), 0, (int)rd.BaseStream.Length); rd.Close(); docstream.Seek(0, SeekOrigin.Begin); } } File.Delete(temp_file_path); File.Delete(dest_file_path); File.Delete(result_file_path.ToString()); /* succeeded */ return(true); } catch (Exception) { /* for debugging purposes */ throw; } #endif }
void ProcessFile(string filename, int cnt) { progress = Math.Abs((100 / filer.Count) * cnt); if (filename.Contains("~")) { return; } #region Kverk word-prosesser som henger.. // kill prosesser som ikke skal være der... Process[] procs = Process.GetProcessesByName("WINWORD"); if (procs.Length > 1) { foreach (Process process in procs) { process.Kill(); } } #endregion try { if (wordApplication != null) { if (wordApplication.Documents.Count > 0) { procs = Process.GetProcessesByName("WINWORD"); foreach (Process process in procs) { process.Kill(); } } } } catch { } try { if (wordApplication != null) { string title = wordApplication.Caption; } else { LogFromThread(progress, "Oppretter word-app.." + Environment.NewLine); CreateApplication(); } } catch { LogFromThread(progress, "Oppretter word-app.." + Environment.NewLine); CreateApplication(); } DateTime start = DateTime.Now; try { //LogFromThread(progress, "(" + (cnt+1).ToString() + " av " + filer.Count + ") ..." + filename.Substring(filename.Length - 15) + " - "); #region Sjekk på tom fil if (new FileInfo(filename).Length == 0) // empty file -> continue.. { FileLog.LogWrite("Filen " + filename + " var tom. Hoppet over.", FileLog.logType.Info); LogFromThread(progress, " Fil er tom. Går videre. " + Environment.NewLine); empty++; return; } #endregion #region Opprettelse av filnavn for pdf string outfile = string.Empty; ut_sti = ut_sti.ToLower(); string tmpFil = Path.GetFileName(filename); if (ut_sti == "") { outfile = Path.ChangeExtension(filename, ".pdf"); } else { string newPath = Path.GetFullPath(filename).Replace(inn_sti, ut_sti); newPath = Path.ChangeExtension(newPath, ".pdf"); outfile = newPath; } if (File.Exists(outfile) && !chkOverwrite.Checked) // file exists, and not overwrite -> continue.. { LogFromThread(progress, " Eksisterer. Går videre. " + Environment.NewLine); exists++; return; } else if (File.Exists(outfile)) { LogFromThread(progress, " Overskriver. "); } #endregion #region Åpning av fil og passordhåndtering string pwMatch = ""; string key = Path.GetFileName(filename); if (passwordList.ContainsKey(key.ToLower())) { pwMatch = passwordList[key.ToLower()].ToString(); } if (pwMatch != "") { // åpne kilde med passord try { wordDocument = wordApplication.Documents.OpenNoRepairDialog( filename, ref paramMissing, false, ref paramMissing, pwMatch, ref paramMissing, ref paramMissing, pwMatch, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing); if (wordDocument.ProtectionType != WdProtectionType.wdNoProtection) { wordDocument.Protect(WdProtectionType.wdNoProtection, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing); } passwordprotected++; currentPassword = pwMatch; } catch (Exception ex) { LogFromThread(progress, "Finner ingen måte å åpne dokumentet på. Går videre. " + Environment.NewLine); FileLog.LogWrite("Fant ingen måte å åpne '" + filename + "' på. Hopper videre." + ex.Message, FileLog.logType.Info); StreamWriter sw = File.CreateText(outfile + ".errorlog"); sw.WriteLine("Fant ingen måte å åpne fila på. Enten er fila skadet, passord manglet i passordfil, eller en annen feil har oppstått:" + Environment.NewLine + ex.Message); sw.Close(); if (chkCopyOriginalOnError.Checked) { File.Copy(filename, Path.Combine(Path.GetDirectoryName(outfile), Path.GetFileName(filename))); } FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); error++; return; } LogFromThread(progress, " Passord:" + pwMatch); } else { try { // åpne kilde med passord "mypass" to force continue. wordDocument = wordApplication.Documents.OpenNoRepairDialog( filename, ref paramMissing, false, ref paramMissing, "mypass", ref paramMissing, ref paramMissing, "mypass", ref paramMissing, ref paramMissing, 28591, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing); } catch (Exception ex) { LogFromThread(progress, "Finner ingen måte å åpne dokumentet på. Går videre. " + Environment.NewLine); FileLog.LogWrite("Fant ingen måte å åpne '" + filename + "' på. Hopper videre." + ex.Message, FileLog.logType.Info); StreamWriter sw = File.CreateText(outfile + ".errorlog"); sw.WriteLine("Fant ingen måte å åpne fila på. Enten er fila skadet, passord manglet i passordfil, eller en annen feil har oppstått:" + Environment.NewLine + ex.Message); sw.Close(); if (chkCopyOriginalOnError.Checked) { File.Copy(filename, Path.Combine(Path.GetDirectoryName(outfile), Path.GetFileName(filename))); } FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); error++; return; } } Thread.Sleep(int.Parse(txtWaitProcess.Text)); if (filtype == "txt") { wordDocument.PageSetup.LeftMargin = 1.0f; wordDocument.PageSetup.RightMargin = 1.0f; wordDocument.PageSetup.TopMargin = 1.0f; wordDocument.PageSetup.BottomMargin = 1.0f; wordApplication.Selection.Document.Content.Select(); wordApplication.Selection.Font.Shrink(); wordApplication.Selection.Font.Shrink(); } #endregion #region Ekspandering av sub-dokumenter try { //Thread.Sleep(int.Parse(txtWaitProcess.Text)); if (wordDocument.IsMasterDocument) { bool missingFiles = false; foreach (Subdocument s in wordDocument.Subdocuments) { retry: //stygt.. men dog.. if (!File.Exists(s.Name)) { string p = Directory.GetParent(Path.GetDirectoryName(s.Name)).ToString(); string[] files = Directory.GetFiles(p, Path.GetFileName(s.Name)); if (files.Count() == 0) { missingFiles = true; FileLog.LogWrite(filename.Substring(filename.Length - 15) + " ble ikke konvertert. FileNotFound ved sjekk av " + s.Name + ".", FileLog.logType.Info); LogFromThread(progress, " Fant ikke subdokumenter '" + s.Name + "'. Går videre." + Environment.NewLine); } else if (files.Count() == 1) { File.Copy(files[0], s.Name); FileLog.LogWrite(filename.Substring(filename.Length - 15) + " ble ikke konvertert. Subdokument funnet på annen plassering. kopiert til " + s.Name + ".", FileLog.logType.Info); LogFromThread(progress, " Fant subdokument ('" + s.Name + "' plassert på '" + files[0] + "') med feil plassering. Kopiert til riktig." + Environment.NewLine); goto retry; } else { missingFiles = true; FileLog.LogWrite(filename.Substring(filename.Length - 15) + " ble ikke konvertert. Ett eller flere subdokumenter mangler. For mange matchende alternativer funnet.", FileLog.logType.Info); LogFromThread(progress, "For mange matchende alternative subdokumenter funnet. Går videre." + Environment.NewLine); } } } if (!missingFiles) { int retryCounter = 0; retry: //stygt.. men dog.. try { retryCounter++; wordDocument.ActiveWindow.ActivePane.View.Type = WdViewType.wdOutlineView; wordApplication.ActiveWindow.View.Type = WdViewType.wdMasterView; Thread.Sleep(int.Parse(txtWaitProcess.Text)); wordDocument.Subdocuments.Expanded = true; Thread.Sleep(int.Parse(txtWaitProcess.Text)); } catch (Exception ex) { if (retryCounter < 10) { logg1.Log(".", Logg.LogType.Info); goto retry; } FileLog.LogWrite(filename.Substring(filename.Length - 15) + " ble ikke konvertert. Feil ved ekspansjon. Error:" + ex.Message, FileLog.logType.Info); LogFromThread(progress, " Feil ved eksp. av subdoks. Går videre." + Environment.NewLine); FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); error++; CloseDocument(); return; } } else { FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); error++; CloseDocument(); return; } } } catch (Exception ex) { FileLog.LogWrite("Filen '..." + filename.Substring(filename.Length - 15) + "' ble ikke konvertert. Subdokument-feil." + ex.Message, FileLog.logType.Info); FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); LogFromThread(progress, "...Feil oppstått " + ex.Message + Environment.NewLine); error++; CloseDocument(); return; } #endregion #region MailMerge string mergeFile = Path.ChangeExtension(filename.ToLower(), "rtf"); if (mergeFile != filename.ToLower() && File.Exists(mergeFile)) { // Det finnes en korresponderende rtf-fil. Sannsynligvis en data-merge-fil. LogFromThread(progress, " Fletter... "); mm = wordDocument.MailMerge; string mergefil = Path.ChangeExtension(filename.ToLower(), "rtf"); mm.OpenDataSource(mergefil, ref paramMissing, false, true, ref paramMissing, false, currentPassword, currentPassword); mm.Destination = WdMailMergeDestination.wdSendToNewDocument; mm.Execute(); Thread.Sleep(4000); if (!saveDocument(wordApplication.Documents[1], outfile)) // lagre dok i nytt vindu { FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); error++; } else { FileLog.LogWrite(filename, FileLog.logType.Filliste_konvertert); } } else { // Export it in the specified format. if (!saveDocument(wordDocument, outfile)) { FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); error++; } else { FileLog.LogWrite(filename, FileLog.logType.Filliste_konvertert); } } #endregion Thread.Sleep(int.Parse(txtWaitProcess.Text)); // Close and release the Document object. CloseDocument(); TimeSpan elapsed = DateTime.Now - start; LogFromThread(progress, " (" + elapsed.Seconds + "." + elapsed.Milliseconds + " s)" + Environment.NewLine); } catch (Exception ex) { error++; FileLog.LogWrite("FEIL! Feil ved konvertering av " + filename + "." + Environment.NewLine + "Feilen var :" + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace, FileLog.logType.Info); LogFromThread(progress, "FEIL! Feil ved konvertering av " + filename.Substring(filename.Length - 15) + "." + Environment.NewLine + "Se info.log for beskrivelse." + Environment.NewLine); CloseDocument(); CloseApplication(); } }
private void CheckGenderButton_Click(object sender, RibbonControlEventArgs e) { SearchWordsForm statusForm = null; try { ThisAddIn.MyApplication.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone; Word.Document document = ThisAddIn.MyApplication.ActiveDocument; if (!RemoveGenderingFields()) { return; } statusForm = new SearchWordsForm(); statusForm.Show(); XmlDocument genderingTable = GenderingEngine.GetGenderingTable(); List <string> words = GetWords(genderingTable); List <Word.Range> foundRanges = GetFoundRanges(statusForm, document, words); bool switchToFormFillIn = false; foreach (Word.Range foundRange in foundRanges) { List <string> alternatives = GetAlternatives(genderingTable, foundRange.Text.ToLowerInvariant()); Trace.WriteLine(foundRange.Start); Trace.WriteLine(foundRange.End); bool alreadyGendered = false; foreach (string alternative in alternatives) { if (IsAlreadyGendered(document, foundRange, alternative)) { alreadyGendered = true; break; } } if (alternatives.Count != 0 && !alreadyGendered) { CreateDropDown(document, foundRange, alternatives); switchToFormFillIn = true; } } if (switchToFormFillIn && Is97(document)) { document.Protect(WdProtectionType.wdAllowOnlyFormFields); } } catch (Exception exception) { MessageBox.Show(exception.Message, "Fehler", MessageBoxButtons.OK); } finally { if (statusForm != null) { statusForm.Close(); } ThisAddIn.MyApplication.DisplayAlerts = Word.WdAlertLevel.wdAlertsMessageBox; } }
void ProcessFile(string filename, int cnt) { progress = Math.Abs((100 / filer.Count) * cnt); if (filename.Contains("~")) return; #region Kverk word-prosesser som henger.. // kill prosesser som ikke skal være der... Process[] procs = Process.GetProcessesByName("WINWORD"); if (procs.Length > 1) foreach (Process process in procs) { process.Kill(); } #endregion try { if (wordApplication.Documents.Count > 0) { procs = Process.GetProcessesByName("WINWORD"); foreach (Process process in procs) process.Kill(); } } catch { } try { string title = wordApplication.Caption; } catch { LogFromThread(progress, "Oppretter word-app.." + Environment.NewLine); CreateApplication(); } DateTime start = DateTime.Now; try { LogFromThread(progress, "(" + (cnt+1).ToString() + " av " + filer.Count + ") ..." + filename.Substring(filename.Length - 15) + " - "); #region Sjekk på tom fil if (new FileInfo(filename).Length == 0) // empty file -> continue.. { FileLog.LogWrite("Filen " + filename + " var tom. Hoppet over.", FileLog.logType.Info); LogFromThread(progress, " Fil er tom. Går videre. " + Environment.NewLine); empty++; return; } #endregion #region Opprettelse av filnavn for pdf string outfile = string.Empty; ut_sti = ut_sti.ToLower(); string tmpFil = Path.GetFileName(filename); if (ut_sti == "") outfile = Path.ChangeExtension(filename, ".pdf"); else { string newPath = Path.GetFullPath(filename).Replace(inn_sti, ut_sti); newPath = Path.ChangeExtension(newPath, ".pdf"); outfile = newPath; } if (File.Exists(outfile) && !chkOverwrite.Checked) // file exists, and not overwrite -> continue.. { LogFromThread(progress, " Eksisterer. Går videre. " + Environment.NewLine); exists++; return; } else if (File.Exists(outfile)) { LogFromThread(progress, " Overskriver. "); } #endregion #region Åpning av fil og passordhåndtering string pwMatch = ""; string key = Path.GetFileName(filename); if (passwordList.ContainsKey(key.ToLower())) { pwMatch = passwordList[key.ToLower()].ToString(); } if (pwMatch != "") { // åpne kilde med passord try { wordDocument = wordApplication.Documents.OpenNoRepairDialog( filename, ref paramMissing, false, ref paramMissing, pwMatch, ref paramMissing, ref paramMissing, pwMatch, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing); if (wordDocument.ProtectionType != WdProtectionType.wdNoProtection) wordDocument.Protect(WdProtectionType.wdNoProtection, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing); passwordprotected++; currentPassword = pwMatch; } catch (Exception ex) { LogFromThread(progress, "Finner ingen måte å åpne dokumentet på. Går videre. " + Environment.NewLine); FileLog.LogWrite("Fant ingen måte å åpne '" + filename + "' på. Hopper videre." + ex.Message, FileLog.logType.Info); FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); error++; return; } LogFromThread(progress, " Passord:" + pwMatch); } else { try { // åpne kilde uten passord. wordDocument = wordApplication.Documents.OpenNoRepairDialog( filename, ref paramMissing, false, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, 28591, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing); } catch (Exception ex) { LogFromThread(progress, "Finner ingen måte å åpne dokumentet på. Går videre. " + Environment.NewLine); FileLog.LogWrite("Fant ingen måte å åpne '" + filename + "' på. Hopper videre." + ex.Message, FileLog.logType.Info); FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); error++; return; } } Thread.Sleep(int.Parse(txtWaitProcess.Text)); if (filtype == "txt") { wordDocument.PageSetup.LeftMargin = 1.0f; wordDocument.PageSetup.RightMargin = 1.0f; wordDocument.PageSetup.TopMargin = 1.0f; wordDocument.PageSetup.BottomMargin = 1.0f; wordApplication.Selection.Document.Content.Select(); wordApplication.Selection.Font.Shrink(); wordApplication.Selection.Font.Shrink(); } #endregion #region Ekspandering av sub-dokumenter try { //Thread.Sleep(int.Parse(txtWaitProcess.Text)); if (wordDocument.IsMasterDocument) { bool missingFiles = false; foreach (Subdocument s in wordDocument.Subdocuments) { retry: //stygt.. men dog.. if (!File.Exists(s.Name)) { string p = Directory.GetParent(Path.GetDirectoryName(s.Name)).ToString(); string[] files = Directory.GetFiles(p, Path.GetFileName(s.Name)); if (files.Count() == 0) { missingFiles = true; FileLog.LogWrite(filename.Substring(filename.Length - 15) + " ble ikke konvertert. FileNotFound ved sjekk av " + s.Name + ".", FileLog.logType.Info); LogFromThread(progress, " Fant ikke subdokumenter '" + s.Name + "'. Går videre." + Environment.NewLine); } else if (files.Count() == 1) { File.Copy(files[0], s.Name); FileLog.LogWrite(filename.Substring(filename.Length - 15) + " ble ikke konvertert. Subdokument funnet på annen plassering. kopiert til " + s.Name + ".", FileLog.logType.Info); LogFromThread(progress, " Fant subdokument ('" + s.Name + "' plassert på '" + files[0] + "') med feil plassering. Kopiert til riktig." + Environment.NewLine); goto retry; } else { missingFiles = true; FileLog.LogWrite(filename.Substring(filename.Length - 15) + " ble ikke konvertert. Ett eller flere subdokumenter mangler. For mange matchende alternativer funnet.", FileLog.logType.Info); LogFromThread(progress, "For mange matchende alternative subdokumenter funnet. Går videre." + Environment.NewLine); } } } if (!missingFiles) { int retryCounter = 0; retry: //stygt.. men dog.. try { retryCounter++; wordDocument.ActiveWindow.ActivePane.View.Type = WdViewType.wdOutlineView; wordApplication.ActiveWindow.View.Type = WdViewType.wdMasterView; Thread.Sleep(int.Parse(txtWaitProcess.Text)); wordDocument.Subdocuments.Expanded = true; Thread.Sleep(int.Parse(txtWaitProcess.Text)); } catch (Exception ex) { if (retryCounter < 10) { logg1.Log(".", Logg.LogType.Info); goto retry; } FileLog.LogWrite(filename.Substring(filename.Length - 15) + " ble ikke konvertert. Feil ved ekspansjon. Error:" + ex.Message, FileLog.logType.Info); LogFromThread(progress, " Feil ved eksp. av subdoks. Går videre." + Environment.NewLine); FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); error++; CloseDocument(); return; } } else { FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); error++; CloseDocument(); return; } } } catch (Exception ex) { FileLog.LogWrite("Filen '..." + filename.Substring(filename.Length - 15) + "' ble ikke konvertert. Subdokument-feil." + ex.Message, FileLog.logType.Info); FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); LogFromThread(progress, "...Feil oppstått " + ex.Message + Environment.NewLine); error++; CloseDocument(); return; } #endregion #region MailMerge string mergeFile = Path.ChangeExtension(filename.ToLower(), "rtf"); if (mergeFile != filename.ToLower() && File.Exists(mergeFile)) { // Det finnes en korresponderende rtf-fil. Sannsynligvis en data-merge-fil. LogFromThread(progress, " Fletter... "); mm = wordDocument.MailMerge; string mergefil = Path.ChangeExtension(filename.ToLower(), "rtf"); mm.OpenDataSource(mergefil, ref paramMissing, false, true, ref paramMissing, false, currentPassword, currentPassword); mm.Destination = WdMailMergeDestination.wdSendToNewDocument; mm.Execute(); Thread.Sleep(4000); if (!saveDocument(wordApplication.Documents[1], outfile)) // lagre dok i nytt vindu { FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); error++; } else FileLog.LogWrite(filename, FileLog.logType.Filliste_konvertert); } else { // Export it in the specified format. if (!saveDocument(wordDocument, outfile)) { FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); error++; } else FileLog.LogWrite(filename, FileLog.logType.Filliste_konvertert); } #endregion Thread.Sleep(int.Parse(txtWaitProcess.Text)); // Close and release the Document object. CloseDocument(); TimeSpan elapsed = DateTime.Now - start; LogFromThread(progress, " (" + elapsed.Seconds + "." + elapsed.Milliseconds + " s)" + Environment.NewLine); } catch (Exception ex) { error++; FileLog.LogWrite("FEIL! Feil ved konvertering av " + filename + "." + Environment.NewLine + "Feilen var :" + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace, FileLog.logType.Info); LogFromThread(progress, "FEIL! Feil ved konvertering av " + filename.Substring(filename.Length - 15) + "." + Environment.NewLine + "Se info.log for beskrivelse." + Environment.NewLine); CloseDocument(); CloseApplication(); } }
/// <summary> /// Метод, который создает документ Word, в котором содержится информация о текущих пользователях. /// </summary> /// <param name="path">Абсолютный путь к создаваемому файлу.</param> /// <param name="wordDocumentName">Название создаваемого файла.</param> /// <param name="openFileAfterCreate">Необязательный параметр. Отвечает за открытие файла после его создания.</param> public async static void CreateWordUserList(String path, String wordDocumentName, Bool openFileAfterCreate = false) { String fullPath; if (!wordDocumentName.EndsWith(".docx")) { wordDocumentName += ".docx"; } //Проверка на окончание пути. _ = path.EndsWith("\\") ? fullPath = path + wordDocumentName : fullPath = path + "\\" + wordDocumentName; //Так как создание документа затрачивает много времени, этот алгоритм вынесен в отдельный поток. await Task.Run(() => { //Создаем процесс Word. Word.Application appToDo = new Word.Application(); //Создаем документ. Связываем его с созданным ранее процессом. appToDo.Documents.Add(); Word.Document mainDocument = appToDo.Documents[1]; //Производим запись в файл. for (int i = 0; i < ActualProfiles.Count; i++) { /* * <——————————————————————————————————————————————————————————————————————————————————————————————————> * | !Запись в Файл! | * |——————————————————————————————————————————————————————————————————————————————————————————————————| * | В данном регионе кода происходит наполнение Word-файла. Разберем этот алгоритм по пунктам: | * |——————————————————————————————————————————————————————————————————————————————————————————————————| * | I. Создание Колонтитулов. | * |——————————————————————————————————————————————————————————————————————————————————————————————————| * | 1. Создаем экземпляр интерфейса "HeaderFooter". Связываем его с текущей секцией документа. | * | 2. При инициализации указываем, что это Верхний Колонтитул. | * | 3. Настраиваем его свойства: шрифт, стиль, выравнивание. Задаем текст с именем пользователя. | * | 4. Аналогично создаем еще один экземпляр интерфейса, но теперь прописываем номер страницы. | * | 5. У второго колонтитула также изменяем стиль чисел, отвечающих за нумерацию страниц. | * |——————————————————————————————————————————————————————————————————————————————————————————————————| * | II. Создание Параграфов. | * |——————————————————————————————————————————————————————————————————————————————————————————————————| * | 1. Создаем экземпляр класса Word.Paragraph, связываем его с документом и добавляем сам параграф. | * | 2. Далее используя "Range" мы задаем текст и его свойства. | * | 3. Далее используем функцию ".InsertParagraphAfter()", чтобы завершить параграф. | * | 4. Если следующий параграф не последний, то используем метод "InsertParagraphBefore()", чтобы -> | * | -> красиво расположить текст, создав пробел между строками. | * |——————————————————————————————————————————————————————————————————————————————————————————————————| * | III. Завершение. | * |——————————————————————————————————————————————————————————————————————————————————————————————————| * | 1. Выполняем проверку на длину файла, чтобы не создавать лишние страницы. | * | 2. Если проверка пройдена, используем метод "Sections.Add()", чтобы создать новую страницу. | * <——————————————————————————————————————————————————————————————————————————————————————————————————> */ #region Область Кода: Заполнение Файла. //Добавляем и настраиваем Верхний Колонтитул с именем текущего пользователя. Word.HeaderFooter currentHeader = appToDo.ActiveDocument.Sections[i + 1].Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary]; currentHeader.Range.Font.Bold = 0; currentHeader.LinkToPrevious = false; currentHeader.Range.Font.Name = "Georgia"; currentHeader.Range.Text = ActualProfiles[i].Name; currentHeader.Range.Paragraphs.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //Добавляем и настраиваем Нижний Колонтитул с номером текущей страницы. Word.HeaderFooter currentFooter = appToDo.ActiveDocument.Sections[i + 1].Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary]; currentFooter.Range.Font.Bold = 0; currentFooter.LinkToPrevious = false; currentFooter.Range.Font.Name = "Georgia"; currentFooter.Range.Text = (i + 1).ToString(); currentFooter.PageNumbers.NumberStyle = Word.WdPageNumberStyle.wdPageNumberStyleHanjaRead; currentFooter.Range.Paragraphs.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //Запись свойства: "Имя Пользователя.". Word.Paragraph userName = mainDocument.Content.Paragraphs.Add(); userName.Range.InsertParagraphBefore(); userName.Range.Text = "Имя Пользователя: " + ActualProfiles[i].Name + ';'; userName.Range.Font.Name = "Georgia"; userName.Range.Font.Bold = 0; userName.Range.InsertParagraphAfter(); //Запись свойства: "Количество побед.". Word.Paragraph userWins = mainDocument.Content.Paragraphs.Add(); userWins.Range.InsertParagraphBefore(); userWins.Range.Text = "Количество побед: " + ActualProfiles[i].Wins + ';'; userWins.Range.Font.Name = "Georgia"; userName.Range.Font.Bold = 0; userWins.Range.InsertParagraphAfter(); //Запись свойства: "Количество игр.". Word.Paragraph userGames = mainDocument.Content.Paragraphs.Add(); userGames.Range.InsertParagraphBefore(); userGames.Range.Text = "Количество игр: " + ActualProfiles[i].AllGames + ';'; userGames.Range.Font.Name = "Georgia"; userName.Range.Font.Bold = 0; userGames.Range.InsertParagraphAfter(); //Заголовок — "Количество побегов.". Word.Paragraph userLeaves = mainDocument.Content.Paragraphs.Add(); userLeaves.Range.InsertParagraphBefore(); userLeaves.Range.Text = "Количество побегов: " + ActualProfiles[i].Leaves + ';'; userLeaves.Range.Font.Name = "Georgia"; userName.Range.Font.Bold = 0; userLeaves.Range.InsertParagraphAfter(); //Заголовок — "Пол пользователя.". Word.Paragraph userGender = mainDocument.Content.Paragraphs.Add(); userGender.Range.InsertParagraphBefore(); userGender.Range.Text = "Пол пользователя: " + ActualProfiles[i].GetStringGender() + ';'; userGender.Range.Font.Name = "Georgia"; userName.Range.Font.Bold = 0; userGender.Range.InsertParagraphAfter(); //Заголовок — "Дата рождения.". Word.Paragraph userBirthTime = mainDocument.Content.Paragraphs.Add(); userBirthTime.Range.InsertParagraphBefore(); userBirthTime.Range.Text = "Дата рождения: " + ActualProfiles[i].BirthTime.ToString("dd.MM.yyyy!"); userBirthTime.Range.Font.Name = "Georgia"; userName.Range.Font.Bold = 0; //Проверка на длину файла. Создана для того, чтобы не создавать лишние страницы. if ((i + 1) < ActualProfiles.Count) { appToDo.ActiveDocument.Sections.Add(); } #endregion } //Защищаем документ от изменений: mainDocument.Protect(Word.WdProtectionType.wdAllowOnlyReading, true, "Checkers!"); //Сохраняем созданный файл по указанному адресу. mainDocument.SaveAs(fullPath); //Описание завершения работы: if (!openFileAfterCreate) { /* * <——————————————————————————————————————————————————————————————————————————————————————————————————> * | !ОЧЕНЬ ВАЖНЫЙ МОМЕНТ! | * |——————————————————————————————————————————————————————————————————————————————————————————————————| * | Здесь происходит завершение процесса "WORD.exe": | * | 1. Сначала мы закрываем сам "Документ" (файл); | * | 2. Затем, через метод Quit() мы завершаем работу процесса. | * |——————————————————————————————————————————————————————————————————————————————————————————————————| * | Если работу процесса не завершить, он останется работать на фоне, даже после закрытия программы. | * <——————————————————————————————————————————————————————————————————————————————————————————————————> */ mainDocument.Close(); appToDo.Quit(); } //Однако если пользователь решил развернуть программу, то завершать процесс принудительно не нужно. else { appToDo.Visible = true; } }); }