Exemple #1
0
        //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);
        }
Exemple #2
0
        public static bool unprotect(Word.Document myDoc)
        {
            object psd = (object)"jwsj";

            myDoc.Unprotect(ref psd);
            return(true);
        }
Exemple #3
0
        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);
            }
        }
Exemple #4
0
        public int TurnOffProtection(string password)
        {
            if (_document == null || _document.ProtectionType == WordOM.WdProtectionType.wdNoProtection)
            {
                return((int)WordOM.WdProtectionType.wdNoProtection);
            }

            WordOM.WdProtectionType oldType = _document.ProtectionType;
            _document.Unprotect(password);
            return((int)oldType);
        }
        private bool RemoveGenderingFields()
        {
            Word.Document document = ThisAddIn.MyApplication.ActiveDocument;

            if (Is97(document))
            {
                if (!document.ProtectionType.Equals((object)WdProtectionType.wdNoProtection))
                {
                    try
                    {
                        document.Unprotect();
                    }
                    catch (COMException e)
                    {
                        if (e.ErrorCode == -2146822803)
                        {
                            MessageBox.Show("Zum Anbieten von Gendering-Vorschlägen wird der Dokumentschutz-Modus 'Felder ausfüllen' ohne Kennwort verwendet."
                                            + " Der bestehende Dokumentschutz konnte nicht aufgehoben werden, möglicherweise wurde ein Kennwort vergeben. Es liegt folgendes Problem vor: "
                                            + e.Message, "Fehler", MessageBoxButtons.OK);

                            return(false);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }

                foreach (FormField field in document.FormFields)
                {
                    if (field.Type == WdFieldType.wdFieldFormDropDown && field.Name == GenderingFieldName)
                    {
                        string text  = field.Result;
                        Range  range = field.Range.Duplicate;
                        range.InsertAfter(text);
                        field.Delete();
                    }
                }
            }
            else
            {
                foreach (Word.ContentControl contcontrol in document.ContentControls)
                {
                    if (contcontrol.Tag == GenderingFieldName)
                    {
                        contcontrol.Range.HighlightColorIndex = Word.WdColorIndex.wdNoHighlight;
                        contcontrol.Delete();
                    }
                }
            }

            return(true);
        }
Exemple #6
0
 public void ClosePwd(Microsoft.Office.Interop.Word.Document Doc, string DocPassword)
 {
     try
     {
         object Pwd = DocPassword;
         Doc.Unprotect(ref Pwd);
     }
     catch (Exception closeException)
     {
     }
 }
Exemple #7
0
        public bool unsecure_for_edit()
        {
            object password = settings.doc_password;

            try
            {
                Doc.Unprotect(ref password);
            }
            catch
            {
                return(false);
            }
            return(true);
        }
Exemple #8
0
        public bool unsecure_for_edit(Word.Document DocToUnSecure)
        {
            object password = settings.doc_password;

            try
            {
                DocToUnSecure.Unprotect(ref password);
            }
            catch
            {
                return(false);
            }
            return(true);
        }
Exemple #9
0
        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;
            }
        }
Exemple #10
0
            public void FillOutCheckTemplate(string wordDocumentPath, AVCheckPrintingModel checkInfo)
            {
                Func <string, bool> isTemplate = (str) => str.Contains('{') && str.Contains('}');

                Word.Document document = null;
                try
                {
                    if (word == null)
                    {
                        word = new Word.Application {
                            Visible = false
                        };
                    }

                    document = word.Documents.Add(wordDocumentPath, true);

                    const string PASSWORD = "******";
                    if (document.ProtectionType != Word.WdProtectionType.wdNoProtection)
                    {
                        document.Unprotect(PASSWORD);
                    }

                    var range = document.Range(Start: 0);
                    range.Copy(); // Copy all to clipboard

                    int count = 1;
                    checkInfo.Memo   = "Marks 3 and 3";
                    checkInfo.Amount = 100.33m;
                    var data = new
                    {
                        // Property names here have significance in that they should match texbox tokens of same name in the Word template.
                        CheckNum          = checkInfo.CheckNumber,
                        RoutingNum        = checkInfo.RoutingNumber,
                        AccountNum        = checkInfo.AccountNumber,
                        BankName          = "Bank Of America", //checkInfo.BankName,
                        BankPhone         = "(408) 444-4444",  //checkInfo.BankPhone,
                        BankAddress       = "123 Bank Lane",   //checkInfo.BankAddress,
                        BankAddressLine1  = "",                //checkInfo.BankAddressLine1,
                        BankAddressLine2  = "",                //checkInfo.BankAddressLine2,
                        BankCity          = "Pune",            //checkInfo.BankCity,
                        BankState         = "CA",              //checkInfo.BankState,
                        BankZipCode       = "95050",           //checkInfo.BankZipCode,
                        BankCountry       = "USA",             //checkInfo.BankCountry,
                        JournalName       = checkInfo.JournalName,
                        PayeeName         = "InandOut",        //checkInfo.PayeeName,
                        PayorName         = "InandOut",        //checkInfo.PayorName,
                        PayorPhone        = "",                //checkInfo.PayorPhone,
                        PayorAddress      = "123 Burger Ave.", //checkInfo.PayorAddress,
                        PayorAddressLine1 = "",                //checkInfo.PayorAddressLine1,
                        PayorAddressLine2 = "",                //checkInfo.PayorAddressLine2,
                        PayorCity         = "San Jose",        //checkInfo.PayorCity,
                        PayorState        = "CA",              //checkInfo.PayorState,
                        PayorZipCode      = "95123",           //checkInfo.PayorZipCode,
                        PayorCountry      = "USA",             //checkInfo.PayorCountry,
                        Date          = DateTime.Today,        //checkInfo.Date,
                        Amount        = 100.00,                //checkInfo.Amount,
                        AmountInWords = checkInfo.AmountInWords,
                        PayeeAddress  = checkInfo.PayeeAddress,
                        For           = checkInfo.PayFor,
                        Memo          = // memo with prefix
                                        !String.IsNullOrWhiteSpace(checkInfo.Memo)
                                ? "Memo: " + checkInfo.Memo
                                : !String.IsNullOrWhiteSpace(checkInfo.PayFor)
                                ? "For: " + checkInfo.PayFor
                                : "",
                        MemoOnly  = checkInfo.Memo,
                        Summary   = checkInfo.Summary,
                        Signature = ""
                    };

                    foreach (Word.Shape shape in range.ShapeRange)
                    {
                        if (shape.Type != MsoShapeType.msoTextBox)
                        {
                            continue;
                        }

                        var fieldTemplate = "";
                        if (isTemplate(shape.AlternativeText))
                        {
                            // Get field template from shape's alternative text. In Word 2013 it is at:
                            // Format Shape > Shape Options > Layout & Properties > ALT TEXT > Description
                            fieldTemplate = shape.AlternativeText;
                            // In Word 97-2003 there are no separate fields for Title and Description. So
                            // when opening a document that was created in newer version of Word with Title
                            // and Description, in Word 97-2003 the Alt Text may show as
                            // "Title: {title} - Description: {description}". In this case we extract the
                            // description part:
                            const string descToken = "Description: ";
                            if (fieldTemplate.StartsWith("Title: ") && fieldTemplate.Contains(descToken))
                            {
                                fieldTemplate = fieldTemplate.SubstringAfter(descToken);
                            }
                            // Use it only if shape's text is not empty, otherwise discard ALT TEXT. Shape
                            // has to have a dummy text in it for it to not become hidden in the template.
                            if (String.IsNullOrWhiteSpace(shape.TextFrame.ContainingRange.Text))
                            {
                                fieldTemplate = "";
                            }
                        }
                        else
                        {
                            // If ALT TEXT does not look like a template then look for it in the TextBox text.
                            fieldTemplate = shape.TextFrame.ContainingRange.Text;
                            if (!isTemplate(fieldTemplate))
                            {
                                continue;
                            }
                        }

                        // If current template contains "{AmountInWords}" token, check if it needs ***padding***.
                        const string AmountInWordsToken = "{AmountInWords"; // intentionally not closed with '}'
                        if (fieldTemplate.Contains(AmountInWordsToken))
                        {
                            var text            = fieldTemplate.FormatSmart(data);
                            var trimmedTemplate = fieldTemplate.Trim();
                            // Pad with asterisks if any asterisk character appears around the template
                            if (trimmedTemplate.StartsWith("*") || trimmedTemplate.EndsWith("*"))
                            {
                                text = FixPadding(text);
                            }
                            shape.TextFrame.ContainingRange.Text = text;
                            continue;
                        }

                        //const string SignatureToken = "{Signature}";
                        //if (fieldTemplate.Contains(SignatureToken))
                        //{
                        //    const string imageMetaData = "data:image/png;base64,";
                        //    if (checkInfo.Base64SignatureImage.StartsWith(imageMetaData))
                        //    {
                        //        var base64Image = checkInfo.Base64SignatureImage.Substring(imageMetaData.Length);
                        //        var bytes = Convert.FromBase64String(base64Image);
                        //        Image image;
                        //        using (MemoryStream ms = new MemoryStream(bytes))
                        //        {
                        //            image = Image.FromStream(ms);
                        //        }
                        //        var imageFile = Path.GetTempPath() + "polaris_temp_image.png";
                        //        if (File.Exists(imageFile))
                        //        {
                        //            File.Delete(imageFile);
                        //        }
                        //        try
                        //        {
                        //            image.Save(imageFile);
                        //            var scaling = 1.0;
                        //            //points = pixels * 72 / 96
                        //            var w = scaling * image.Width * 0.75;
                        //            var h = scaling * image.Height * 0.75;
                        //            document.Shapes.AddPicture(
                        //                FileName: imageFile,
                        //                LinkToFile: false,
                        //                SaveWithDocument: true,
                        //                Left: shape.Left - (w - shape.Width) / 2,
                        //                Top: shape.Top - (h - shape.Height) / 2,
                        //                Width: w,
                        //                Height: h,
                        //                Anchor: range);
                        //        }
                        //        finally
                        //        {
                        //            if (File.Exists(imageFile))
                        //            {
                        //                File.Delete(imageFile);
                        //            }
                        //        }
                        //    }

                        //    shape.TextFrame.ContainingRange.Text = "";
                        //    continue;
                        //}

                        shape.TextFrame.ContainingRange.Text = fieldTemplate.FormatSmart(data);

                        // For some reason changing shape name will adversely affect the performance (makes it twice as slow). Commenting this out.
                        //// change shape's name to make sure it is not modified again
                        //shape.Name += "_" + count;
                    }


                    //word.Selection.EndKey(Word.WdUnits.wdStory); // Go to end of doc
                    //word.Selection.InsertBreak(Word.WdBreakType.wdPageBreak);
                    //document.Bookmarks[@"\EndOfDoc"].Range.Paste();

                    //range.SetRange(range.End, word.Selection.End);

                    //count++;

                    document.SaveAs("c:/users/dcamp/documents/AVCheckPrintingTest/test.doc", Word.WdSaveFormat.wdFormatDocument);
                    document.Close();
                    // Protect document with password to restrict editing.
                    //document.Protect(Word.WdProtectionType.wdAllowOnlyReading, Password: PASSWORD);

                    // Clear template from clipboard
                    //ServiceLocator.Current.GetInstance<IClipboardManager>().ClearClipboard();
                    //ClipboardManager clipBoard = new ClipboardManager();
                    //clipBoard.ClearClipboard();
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException(string.Format("Error on file {0}", wordDocumentPath), ex);
                }

                finally
                {
                    if (document != null)
                    {
                        Marshal.ReleaseComObject(document);
                    }
                }
            }
Exemple #11
0
 public int TurnOffProtection(string password)
 {
     WordOM.WdProtectionType oldType = _document.ProtectionType;
     _document.Unprotect(password);
     return((int)oldType);
 }