Example #1
0
        /// <summary>
        /// 设置文档格式并添加内容
        /// </summary>
        /// <param name="filePath">文件名</param>
        /// <returns></returns>
        public static bool AddContent(string filePath)
        {
            try
            {
                Object oMissing = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word._Application WordApp = new Application();
                WordApp.Visible = true;
                object filename = filePath;
                Microsoft.Office.Interop.Word._Document WordDoc = WordApp.Documents.Open(ref filename, 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);

                //设置居左
                WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;

                //设置文档的行间距
                WordApp.Selection.ParagraphFormat.LineSpacing = 15f;
                //插入段落
                //WordApp.Selection.TypeParagraph();
                Microsoft.Office.Interop.Word.Paragraph para;
                para = WordDoc.Content.Paragraphs.Add(ref oMissing);
                //正常格式
                para.Range.Text = "This is paragraph 1";
                //para.Range.Font.Bold = 2;
                //para.Range.Font.Color = WdColor.wdColorRed;
                //para.Range.Font.Italic = 2;
                para.Range.InsertParagraphAfter();

                para.Range.Text = "This is paragraph 2";
                para.Range.InsertParagraphAfter();

                //插入Hyperlink
                Microsoft.Office.Interop.Word.Selection mySelection = WordApp.ActiveWindow.Selection;
                mySelection.Start = 9999;
                mySelection.End   = 9999;
                Microsoft.Office.Interop.Word.Range myRange = mySelection.Range;

                Microsoft.Office.Interop.Word.Hyperlinks myLinks = WordDoc.Hyperlinks;
                object linkAddr = @"http://www.cnblogs.com/lantionzy";
                Microsoft.Office.Interop.Word.Hyperlink myLink = myLinks.Add(myRange, ref linkAddr,
                                                                             ref oMissing);
                WordApp.ActiveWindow.Selection.InsertAfter("\n");

                //落款
                WordDoc.Paragraphs.Last.Range.Text = "文档创建时间:" + DateTime.Now.ToString();
                WordDoc.Paragraphs.Last.Alignment  = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;

                //保存
                WordDoc.Save();
                WordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                WordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                return(false);
            }
        }
Example #2
0
        private ICollection <FileInfo> GetInlineShapesLinks()
        {
            List <FileInfo> attachments = new List <FileInfo>();

            try
            {
                foreach (Word.InlineShape shape in document.InlineShapes)
                {
                    bool isLinkShape = shape.Type == Word.WdInlineShapeType.wdInlineShapeLinkedOLEObject || shape.Type == Word.WdInlineShapeType.wdInlineShapeLinkedPicture || shape.Type == Word.WdInlineShapeType.wdInlineShapeLinkedPictureHorizontalLine;
                    if (isLinkShape && shape.LinkFormat != null && shape.LinkFormat.Type != Word.WdLinkType.wdLinkTypePicture)
                    {
                        FileInfo file = UriToFile(shape.LinkFormat.SourceFullName);
                        if (file != null)
                        {
                            attachments.Add(file);
                        }
                    }
                }
                foreach (Word.Shape shape in document.Shapes)
                {
                    if (shape.Hyperlink != null)
                    {
                        Word.Hyperlink link = shape.Hyperlink;
                        if (link.Address != null)
                        {
                            FileInfo file = UriToFile(link.Address);
                            if (file != null)
                            {
                                attachments.Add(file);
                            }
                        }
                    }
                }

                foreach (Word.InlineShape shape in document.InlineShapes)
                {
                    if (shape.Hyperlink != null)
                    {
                        Word.Hyperlink link = shape.Hyperlink;
                        if (link.Address != null)
                        {
                            FileInfo file = UriToFile(link.Address);
                            if (file != null)
                            {
                                attachments.Add(file);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                try
                {
                    WBOffice4.OfficeApplication.WriteError(e);
                }
                catch { }
            }
            return(attachments);
        }
        public void Add(Word.Hyperlink link, string message)
        {
            if (_links.ContainsKey(link))
            {
                return;
            }

            _links.Add(link, message);
        }
Example #4
0
 private static void CreateWordDocument(string Link, string FilePath = "")
 {
     try
     {
         Microsoft.Office.Interop.Word._Application MSWORD = new Microsoft.Office.Interop.Word.Application();
         MSWORD.Visible = false;
         object missing = Type.Missing;
         Microsoft.Office.Interop.Word._Document MSWORDdoc = MSWORD.Documents.Add(ref missing, ref missing, ref missing, ref missing);
         Microsoft.Office.Interop.Word.Paragraph TEXTBLOCK = MSWORDdoc.Paragraphs.Add(ref missing);
         object style_name = "Heading 1";
         TEXTBLOCK.Range.set_Style(ref style_name);
         TEXTBLOCK.Range.InsertParagraphAfter();
         if (string.IsNullOrEmpty(FilePath))
         {
             TEXTBLOCK.Range.Text = RandomString_Contents(randLength.Next(5, 999));
         }
         else
         {
             TEXTBLOCK.Range.Text = RandomString_Words(FilePath);
         }
         TEXTBLOCK.Range.InsertParagraphAfter();
         object filename  = Directory.GetCurrentDirectory() + "\\" + RandomString_Contents(randLength.Next(3, 12)) + ".doc";
         string PREV_FONT = TEXTBLOCK.Range.Font.Name;
         TEXTBLOCK.Range.Font.Name = "Courier New";
         TEXTBLOCK.Range.InsertParagraphAfter();
         TEXTBLOCK.Range.Font.Name = PREV_FONT;
         Microsoft.Office.Interop.Word.Hyperlinks myLinks = MSWORDdoc.Hyperlinks;
         if (Link.Contains("http") == false && Link.Contains("https") == false)
         {
             Link = "http://" + Link;
         }
         object linkAddr = Link;
         Microsoft.Office.Interop.Word.Selection mySelection = MSWORDdoc.ActiveWindow.Selection;
         mySelection.Start = 9999;
         mySelection.End   = 9999;
         Microsoft.Office.Interop.Word.Range     myRange = mySelection.Range;
         Microsoft.Office.Interop.Word.Hyperlink myLink  = myLinks.Add(myRange, ref linkAddr, ref missing);
         MSWORDdoc.ActiveWindow.Selection.InsertAfter("\n");
         MSWORDdoc.SaveAs(ref filename, 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);
         object save_changes = false;
         MSWORDdoc.Close(ref save_changes, ref missing, ref missing);
         MSWORD.Quit(ref save_changes, ref missing, ref missing);
         Console.WriteLine("App done! .Doc created!");
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message);
         Console.WriteLine(e.StackTrace);
     }
 }
Example #5
0
        public static void RemoveAllHyperlinks(Word.Application wordApp)
        {
            Word.Document doc = wordApp.ActiveDocument;
            if (wordApp.ActiveDocument == null ||
                wordApp.ActiveDocument.Hyperlinks == null ||
                wordApp.ActiveDocument.Hyperlinks.Count == 0)
            {
                return;
            }

            wordApp.ScreenUpdating = false;
            Word.UndoRecord ur = wordApp.UndoRecord;
            ur.StartCustomRecord("Remove all URL Hyperlinks");
            try
            {
                // It needs a copy of the list, because I can't remove anything from the original while iterating it
                Word.Hyperlink[] links = new Word.Hyperlink[doc.Hyperlinks.Count];
                for (int i = 0; i < doc.Hyperlinks.Count; i++)
                {
                    links[i] = doc.Hyperlinks[i + 1];
                }

                for (int i = 0; i < links.Length; i++)
                {
                    string address;
                    try
                    {
                        address = links[i].Address;
                    }
                    catch (Exception e) // for this same reason as above
                    {
                        address = null;
                    }
                    if (!String.IsNullOrWhiteSpace(address) &&
                        (address.StartsWith("http://") || address.StartsWith("https://")))
                    {
                        links[i].Delete();
                    }
                }
            }
            catch (Exception e) { }
            finally // The whole thing is only needed to make sure this runs (ScreenUpdate can get stuck)
            {
                wordApp.ScreenUpdating = true;
                ur.EndCustomRecord();
            }
        }
Example #6
0
        /// <summary>
        /// Inserts the details as HTML.
        /// </summary>
        /// <param name="attachments">The attachments.</param>
        /// <param name="range">The range.</param>
        /// <param name="positionBeforeAdd">The position before add.</param>
        /// <param name="mailItem">The mail item.</param>
        /// <param name="numberFailedAttachments">The number failed attachments.</param>
        /// <returns></returns>
        private int InsertDetailsAsHtml(List <Utilities.PreferredFileInformation> attachments, Word.Range range, int positionBeforeAdd, OfficeOutlook.MailItem mailItem, out int numberFailedAttachments)
        {
            numberFailedAttachments = 0;
            if (this.insertAsCopy)
            {
                for (int n = 0; n < attachments.Count; n++)
                {
                    Utilities.PreferredFileInformation fileInfo = attachments[n];
                    try
                    {
                        mailItem.Attachments.Add(fileInfo.LocalPath, OfficeOutlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);
                    }
                    catch (System.Runtime.InteropServices.COMException ex)
                    {
                        if (ex.Message.ToUpperInvariant() == attachmentWarning.ToUpperInvariant())
                        {
                            numberFailedAttachments++;
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            }

            if (this.insertAsLink)
            {
                // Adding the attachments resets the Range to the top of the document, so we need to move the range
                // to were the user's cursor was when they started the process
                range.SetRange(positionBeforeAdd, positionBeforeAdd);

                for (int n = 0; n < attachments.Count; n++)
                {
                    Utilities.PreferredFileInformation fileInfo = attachments[n];
                    Word.Hyperlink hyperlink = range.Hyperlinks.Add(range, fileInfo.Url, Type.Missing, Type.Missing, fileInfo.ToString());
                    range.SetRange(hyperlink.Range.End, hyperlink.Range.End);
                    range.InsertAfter(Environment.NewLine);
                    range.SetRange(range.End, range.End);
                }

                return(range.End);
            }

            return(0);
        }
Example #7
0
        private void uxArticlesInsertIntoArticleById_Click(object sender, EventArgs e)
        {
            if (uxRelatedArticleID.Text == "")
            {
                MessageBox.Show(@"Please enter an article number");
                return;
            }

            Object address = _scTree.GetArticleUrl(uxRelatedArticleID.Text);

            if (address.ToString() == "")
            {
                MessageBox.Show(@"Article number does not exist!");
                return;
            }

            //string tooltip = _scTree.GetArticleDynamicUrl(uxRelatedArticleID.Text);

            var app = Globals.SitecoreAddin.Application;

            app.Selection.TypeText("[A#");
            Word.Range     hyperlinkRange = app.ActiveDocument.Range(app.Selection.Start, app.Selection.End);
            Word.Hyperlink hyperlink      = app.ActiveDocument.Hyperlinks.Add(hyperlinkRange, ref address, null, null, uxRelatedArticleID.Text);
            Word.Range     range          = hyperlink.Range;

            app.Selection.Start = range.End;
            app.Selection.End   = range.End;
            app.Selection.Text  = "]";

            range.Start = range.End + 1;
            range.End   = range.Start;

            //trying to give document focus; have not found solution
            app.Selection.Select();
            range.Select();
        }
        private void btn_LinkText_Click(object sender, RibbonControlEventArgs e)
        {
            Word.Hyperlinks myLinks = Globals.ThisAddIn.Application.ActiveDocument.Hyperlinks;
            string          anchor  = InputDialog.ShowDialog("What text do you want linked (case sensitive)?", "Link Text");

            if (!String.IsNullOrEmpty(anchor))
            {
                string link     = InputDialog.ShowDialog("Where do you want the link to point (leave blank to remove link)?", "Link Text");
                object findText = anchor;
                Globals.ThisAddIn.Application.Selection.Find.Execute(findText, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true, Word.WdFindWrap.wdFindAsk, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                if (Globals.ThisAddIn.Application.Selection.Find.Found)
                {
                    while (Globals.ThisAddIn.Application.Selection.Find.Found)
                    {
                        if (String.IsNullOrEmpty(link))
                        {
                            if (Globals.ThisAddIn.Application.Selection.Hyperlinks.Count > 0)
                            {
                                DialogResult result = MessageBox.Show("You entered a blank link. Do you wish to remove existing links? Click Yes to continue. Click No to ignore this one instance. Click Cancel to abort the whole linking process.", "Link Text: Confirm Removal", MessageBoxButtons.YesNoCancel);
                                if (result == DialogResult.Yes)
                                {
                                    Debug.WriteLine("Removing link from the anchor '" + anchor + "'.");
                                    foreach (Word.Hyperlink objLink in Globals.ThisAddIn.Application.Selection.Hyperlinks)
                                    {
                                        objLink.Delete();
                                    }
                                }
                                else if (result == DialogResult.No)
                                {
                                    Debug.WriteLine("Skipping this instance of the anchor.");
                                }
                                else
                                {
                                    Debug.WriteLine("Aborting!");
                                    break;
                                }
                            }
                        }
                        else
                        {
                            if (Globals.ThisAddIn.Application.Selection.Hyperlinks.Count > 0)
                            {
                                DialogResult result = MessageBox.Show("This instance of the text is already linked. Do you want to update this link to '" + link + "'? Click Yes to proceed. Click No to skip this one instance. Click Cancel to abort the whole linking process.", "Link Text: Confirm Link", MessageBoxButtons.YesNoCancel);
                                if (result == DialogResult.Yes)
                                {
                                    Debug.WriteLine("Updating link to the anchor '" + anchor + "', pointing to '" + link + "'.");
                                    foreach (Word.Hyperlink objLink in Globals.ThisAddIn.Application.Selection.Hyperlinks)
                                    {
                                        objLink.Delete();
                                    }
                                    Word.Hyperlink mylink = myLinks.Add(Globals.ThisAddIn.Application.Selection.Range, link);
                                }
                                else if (result == DialogResult.No)
                                {
                                    Debug.WriteLine("Skipping this instance of the anchor.");
                                }
                                else
                                {
                                    Debug.WriteLine("Aborting!");
                                    break;
                                }
                            }
                            else
                            {
                                DialogResult result = MessageBox.Show("Do you wish to link the selected text? It will point to the following URL: '" + link + "'. Click Yes to proceed. Click No to skip this one instance. Click Cancel to abort the whole linking process.", "Link Text: Confirm Link", MessageBoxButtons.YesNoCancel);
                                if (result == DialogResult.Yes)
                                {
                                    Debug.WriteLine("Adding link to the anchor '" + anchor + "', pointing to '" + link + "'.");
                                    Word.Hyperlink mylink = myLinks.Add(Globals.ThisAddIn.Application.Selection.Range, link);
                                }
                                else if (result == DialogResult.No)
                                {
                                    Debug.WriteLine("Skipping this instance of the anchor.");
                                }
                                else
                                {
                                    Debug.WriteLine("Aborting!");
                                    break;
                                }
                            }
                        }
                        Globals.ThisAddIn.Application.Selection.Find.Execute(findText, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true, Word.WdFindWrap.wdFindAsk, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                    }
                    MessageBox.Show("Linking process complete.");
                }
                else
                {
                    MessageBox.Show("No instances of '" + anchor + "' found. Remember that the search is case sensitive and, if text is selected, will only search inside that text.");
                }
            }
        }
Example #9
0
    public static bool Merge(string sourceTemplatePath, string outputDocPath, DataSet sourceData, string[,] tblInfo, int tableNbr, bool startAtRow2, bool isDoubleSidedPrinting, string[] extraPages, bool addExtraPagesAtEnd, string invlinkAtEndOfDoc, out string errorString)
    {
        errorString = "";
        object oMissing = System.Reflection.Missing.Value;
        object oFalse   = false;
        object oTrue    = true;
        //object oPageBreak = Word.WdBreakType.wdPageBreak;
        object oPageBreak          = Word.WdBreakType.wdSectionBreakNextPage;
        object oSourceTemplatePath = sourceTemplatePath;
        object oOutputDocPath      = outputDocPath;
        object sectionStart        = (object)Microsoft.Office.Interop.Word.WdSectionStart.wdSectionNewPage;


        ApplicationClass myWordApp = null;    // our application
        Document         myWordDoc = null;    // our document

        try
        {
            myWordApp = new ApplicationClass();
            myWordDoc = new Document();

            myWordApp.Visible = false;  // tell word not to show itself


            if (oSourceTemplatePath != null)
            {
                // load the template and check how many fields there are to replace
                myWordDoc = myWordApp.Documents.Add(            // load the template into a document workspace
                    ref oSourceTemplatePath,                    // and reference it through our myWordDoc
                    ref oMissing,
                    ref oMissing,
                    ref oMissing);
            }
            else
            {
                myWordDoc = myWordApp.Documents.Add(             // add new document
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing);
            }


            if (sourceData != null)
            {
                // iterate through the fields collection and update
                foreach (Field myMergeField in myWordDoc.Fields)
                {
                    Word.Range rngFieldCode = myMergeField.Code;
                    String     fieldText    = rngFieldCode.Text;

                    // only get the mailmerge fields
                    if (fieldText.StartsWith(" MERGEFIELD") && fieldText.IndexOf("\\") != -1)
                    {
                        // THE TEXT COMES IN THE FORMAT OF
                        // MERGEFIELD MyFieldName \\* MERGEFORMAT
                        // THIS HAS TO BE EDITED TO GET ONLY THE FIELDNAME "MyFieldName"
                        Int32  endMerge        = fieldText.IndexOf("\\");
                        Int32  fieldNameLength = fieldText.Length - endMerge;
                        String fieldName       = fieldText.Substring(11, endMerge - 11);
                        //Logger.LogMailMerge("fieldName:" + fieldName);

                        // GIVES THE FIELDNAMES AS THE USER HAD ENTERED IN .dot FILE
                        // field names with spaces in them have quotes on either end, so strip those
                        fieldName = fieldName.Trim().Replace("\"", "");
                        Log("Found word template field: " + fieldName);

                        //find a matching dataset column
                        foreach (DataColumn col in sourceData.Tables[0].Columns)
                        {
                            string key   = col.ColumnName;
                            string value = sourceData.Tables[0].Rows[0][key].ToString();

                            // **** FIELD REPLACEMENT IMPLEMENTATION GOES HERE ****//
                            // THE PROGRAMMER CAN HAVE HIS OWN IMPLEMENTATIONS HERE
                            if (fieldName == key)
                            {
                                Log("Setting value: " + value);

                                myMergeField.Select();
                                myWordApp.Selection.TypeText(value);
                            }
                        }
                    }
                }
            }



            if (tblInfo != null)
            {
                Log("MailMergeWebApp:MergeInvoice() adding to table: " + sourceTemplatePath);

                // Fill the table with data.
                Word.Table tbl       = myWordDoc.Tables[tableNbr]; // starts at "1"
                Object     beforeRow = Type.Missing;

                for (int row = 0; row < tblInfo.GetLength(0); row++)
                {
                    tbl.Rows.Add(ref beforeRow);
                    for (int col = 0; col < tblInfo.GetLength(1); col++)
                    {
                        bool isAlignRight   = false;
                        bool isBold         = false;
                        bool isUnderline    = false;
                        bool invpaymentlink = false;
                        if (tblInfo[row, col].StartsWith("<align=right>") && tblInfo[row, col].EndsWith("</align>"))
                        {
                            tblInfo[row, col] = tblInfo[row, col].Substring(13, tblInfo[row, col].Length - 21);
                            isAlignRight      = true;
                        }
                        if (tblInfo[row, col].StartsWith("<b>") && tblInfo[row, col].EndsWith("</b>"))
                        {
                            tblInfo[row, col] = tblInfo[row, col].Substring(3, tblInfo[row, col].Length - 7);
                            isBold            = true;
                        }
                        if (tblInfo[row, col].StartsWith("<u>") && tblInfo[row, col].EndsWith("</u>"))
                        {
                            tblInfo[row, col] = tblInfo[row, col].Substring(3, tblInfo[row, col].Length - 7);
                            isUnderline       = true;
                        }
                        if (tblInfo[row, col].StartsWith("<invpaymentlink>") && tblInfo[row, col].EndsWith("</invpaymentlink>"))
                        {
                            tblInfo[row, col] = tblInfo[row, col].Substring(16, tblInfo[row, col].Length - 33);
                            invpaymentlink    = true;
                        }


                        if (tbl.Rows.Count >= row + 1 + (startAtRow2 ? 1 : 0) && tbl.Columns.Count >= col + 1)
                        {
                            if (invpaymentlink)
                            {
                                //Word.Selection wrdSelection = myWordApp.Selection;
                                //string StrToAdd = "If you would like to pay online, please ";
                                //wrdSelection.TypeText(StrToAdd);

                                Word.Range     range = tbl.Cell(row + 1 + (startAtRow2 ? 1 : 0), col + 1).Range;
                                Word.Hyperlink hl    = myWordDoc.Hyperlinks.Add(range, tblInfo[row, col], ref oMissing, ref oMissing, "Web Pay", ref oMissing);
                            }
                            else
                            {
                                tbl.Cell(row + 1 + (startAtRow2 ? 1 : 0), col + 1).Range.Text                      = tblInfo[row, col]; // first cell is (1,1), not (0,0) -- if start on 2nd row after headings, use (2,1)
                                tbl.Cell(row + 1 + (startAtRow2 ? 1 : 0), col + 1).Range.Font.Bold                 = isBold ? 1 : 0;
                                tbl.Cell(row + 1 + (startAtRow2 ? 1 : 0), col + 1).Range.Font.Underline            = isUnderline ? Word.WdUnderline.wdUnderlineWords : Word.WdUnderline.wdUnderlineNone;
                                tbl.Cell(row + 1 + (startAtRow2 ? 1 : 0), col + 1).Range.ParagraphFormat.Alignment = isAlignRight ? WdParagraphAlignment.wdAlignParagraphRight : WdParagraphAlignment.wdAlignParagraphLeft;
                            }
                        }
                    }
                }
            }


            if (invlinkAtEndOfDoc != null)
            {
                foreach (Field myMergeField in myWordDoc.Fields)
                {
                    Word.Range rngFieldCode = myMergeField.Code;
                    String     fieldText    = rngFieldCode.Text;

                    // only get the mailmerge fields
                    if (fieldText.StartsWith(" MERGEFIELD") && fieldText.IndexOf("\\") != -1)
                    {
                        // THE TEXT COMES IN THE FORMAT OF
                        // MERGEFIELD MyFieldName \\* MERGEFORMAT
                        // THIS HAS TO BE EDITED TO GET ONLY THE FIELDNAME "MyFieldName"
                        Int32  endMerge        = fieldText.IndexOf("\\");
                        Int32  fieldNameLength = fieldText.Length - endMerge;
                        String fieldName       = fieldText.Substring(11, endMerge - 11);
                        //Logger.LogMailMerge("fieldName:" + fieldName);

                        // GIVES THE FIELDNAMES AS THE USER HAD ENTERED IN .dot FILE
                        // field names with spaces in them have quotes on either end, so strip those
                        fieldName = fieldName.Trim().Replace("\"", "");
                        Log("Found word template field: " + fieldName);

                        if (fieldName == "inv_pay_online_link")
                        {
                            myMergeField.Select();

                            //invlinkAtEndOfDoc = invlinkAtEndOfDoc.Replace("https://portal.mediclinic.com.au", "http://localhost:88");

                            Word.Selection wrdSelection = myWordApp.Selection;
                            string         StrToAdd     = "If you would like to pay online, please ";
                            wrdSelection.TypeText(StrToAdd);

                            Word.Range     range = myWordApp.Selection.Range;
                            Word.Hyperlink hl    = myWordDoc.Hyperlinks.Add(range, invlinkAtEndOfDoc, ref oMissing, ref oMissing, "Click Here", ref oMissing);
                        }
                    }
                }



                if (false)
                {
                    /*
                     * Word.Selection wrdSelection = myWordApp.Selection;;
                     *
                     * // Go to the end of the document.
                     * Object oConst1 = Word.WdGoToItem.wdGoToLine;
                     * Object oConst2 = Word.WdGoToDirection.wdGoToLast;
                     * //myWordApp.Selection.GoTo(ref oConst1, ref oConst2, ref oMissing, ref oMissing);
                     *
                     * myWordApp.Selection.TypeParagraph();
                     * myWordApp.Selection.TypeParagraph();
                     *
                     * // Create a string and insert it into the document.
                     * string StrToAdd = "If you would like to pay online, please follow this link: ";
                     * wrdSelection.TypeText(StrToAdd);
                     *
                     * // Insert a hyperlink to the Web page.
                     * Object oAddress = invlinkAtEndOfDoc;
                     * Object oRange = wrdSelection.Range;
                     * wrdSelection.Hyperlinks.Add(oRange, ref oAddress, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                     *
                     * string newText = "......";
                     * wrdSelection.TypeText(newText);
                     */

                    // Go to the end of the document.
                    // oConst1 = Word.WdGoToItem.wdGoToLine;
                    // oConst2 = Word.WdGoToDirection.wdGoToLast;
                    //myWordApp.Selection.GoTo(ref oConst1, ref oConst2, ref oMissing, ref oMissing);
                    //myWordDoc.GoTo(ref oConst1, ref oConst2, ref oMissing, ref oMissing);



                    // now make start to point to the end of the content of the first document
                    //Object end = myWordApp.ActiveDocument.Content.End - 1;
                    // create another range object with the new value for start
                    //Range range = myWordDoc.Range(ref end, ref oMissing);



                    //invlinkAtEndOfDoc = invlinkAtEndOfDoc.Replace("https://portal.mediclinic.com.au", "http://localhost:88");

                    //Word.Selection wrdSelection = myWordApp.Selection;
                    //string StrToAdd = "If you would like to pay online, please ";
                    //wrdSelection.TypeText(StrToAdd);

                    //Word.Range range = myWordApp.Selection.Range;
                    //Word.Hyperlink hl = myWordDoc.Hyperlinks.Add(range, invlinkAtEndOfDoc, ref oMissing, ref oMissing, "Click Here", ref oMissing);
                }
            }


            if (oSourceTemplatePath != null && addExtraPagesAtEnd && isDoubleSidedPrinting) // make sure so far, even nbr of pages
            {
                int nPages = myWordDoc.ComputeStatistics(Word.WdStatistic.wdStatisticPages, ref oMissing);
                if (nPages % 2 == 1)
                {
                    Word.Paragraph paragraph = myWordDoc.Content.Paragraphs.Add(ref oMissing);
                    paragraph.Range.InsertParagraphBefore();
                    paragraph.Range.Text = string.Empty;
                    paragraph.Range.InsertBreak(ref oPageBreak);
                    paragraph.Range.InsertParagraphAfter();
                }
            }


            Log("Adding pages");

            if (extraPages != null)
            {
                for (int i = 0; i < extraPages.Length; i++)
                {
                    string text = Environment.NewLine + Environment.NewLine +
                                  Environment.NewLine + Environment.NewLine +
                                  Environment.NewLine + Environment.NewLine + extraPages[i];

                    Word.Paragraph paragraph;

                    //if (oSourceTemplatePath != null || i > 0)  // if not blank doc OR not first extra page -- add page break first
                    //{
                    //    paragraph = myWordDoc.Content.Paragraphs.Add(ref oMissing);
                    //    paragraph.Range.InsertParagraphBefore();
                    //    paragraph.Range.Text = string.Empty;
                    //    paragraph.Range.InsertBreak(ref oPageBreak);
                    //    paragraph.Range.InsertParagraphAfter();
                    //}

                    //paragraph = myWordDoc.Content.Paragraphs.Add(ref oMissing);
                    //paragraph.Range.InsertParagraphBefore();
                    //paragraph.Range.Text = text;
                    //paragraph.Range.InsertParagraphAfter();

                    paragraph = myWordDoc.Content.Paragraphs.Add(ref oMissing);
                    if ((oSourceTemplatePath != null && addExtraPagesAtEnd) || i > 0)  // if not blank doc OR not first extra page -- add page break first
                    {
                        paragraph.Range.InsertBreak(ref oPageBreak);
                    }
                    paragraph.Range.InsertBefore(text);
                }
            }


            // but put it at the end of all notes
            if (isDoubleSidedPrinting) // make sure so far, even nbr of pages
            {
                int nPages = myWordDoc.ComputeStatistics(Word.WdStatistic.wdStatisticPages, ref oMissing);
                if (nPages % 2 == 1)
                {
                    Word.Paragraph paragraph = myWordDoc.Content.Paragraphs.Add(ref oMissing);
                    paragraph.Range.InsertParagraphBefore();
                    paragraph.Range.Text = string.Empty;
                    paragraph.Range.InsertBreak(ref oPageBreak);
                    paragraph.Range.InsertParagraphAfter();
                }
            }


            object fileFormat = System.IO.Path.GetExtension(oOutputDocPath.ToString()).ToUpper() == ".PDF" ? Word.WdSaveFormat.wdFormatPDF : oMissing;
            myWordDoc.SaveAs(
                ref oOutputDocPath,
                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);



            //CLOSE THE FINAL DOC
            myWordDoc.Close(ref oFalse, ref oMissing, ref oMissing);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(myWordDoc);
            myWordDoc = null;


            Log("Merge complete");

            return(true);
        }
        catch (System.Exception ex)
        {
            errorString = ex.ToString(); //.Message;
        }
        finally
        {
            //RELEASE WORD ITSELF
            try{ myWordApp.Quit(ref oFalse, ref oMissing, ref oMissing); } catch (Exception) { }
            try{ System.Runtime.InteropServices.Marshal.ReleaseComObject(myWordApp); } catch (Exception) { }
            try{ myWordApp = null; } catch (Exception) { }
            GC.Collect();
        }

        return(false);
    }
        public static void RemoveAllHyperlinks(Word.Application wordApp)
        {
            Word.Document doc = wordApp.ActiveDocument;
            if (wordApp.ActiveDocument == null ||
                wordApp.ActiveDocument.Hyperlinks == null ||
                wordApp.ActiveDocument.Hyperlinks.Count == 0)
                return;

            wordApp.ScreenUpdating = false;
            Word.UndoRecord ur = wordApp.UndoRecord;
            ur.StartCustomRecord("Remove all URL Hyperlinks");
            try
            {
                // It needs a copy of the list, because I can't remove anything from the original while iterating it
                Word.Hyperlink[] links = new Word.Hyperlink[doc.Hyperlinks.Count];
                for(int i = 0; i < doc.Hyperlinks.Count; i++)
                    links[i] = doc.Hyperlinks[i+1];

                for (int i = 0; i < links.Length; i++)
                {
                    string address;
                    try
                    {
                        address = links[i].Address;
                    }
                    catch (Exception e) // for this same reason as above
                    {
                        address = null;
                    }
                    if (!String.IsNullOrWhiteSpace(address) &&
                        (address.StartsWith("http://") || address.StartsWith("https://")))
                        links[i].Delete();
                }
            }
            catch (Exception e) { }
            finally // The whole thing is only needed to make sure this runs (ScreenUpdate can get stuck)
            {
                wordApp.ScreenUpdating = true;
                ur.EndCustomRecord();
            }
        }
Example #11
0
        /// <summary>
        /// Inserts the details as rich text.
        /// </summary>
        /// <param name="attachments">The attachments.</param>
        /// <param name="range">The range.</param>
        /// <param name="mailItem">The mail item.</param>
        /// <param name="numberFailedAttachments">The number failed attachments.</param>
        /// <returns></returns>
        private int InsertDetailsAsRichText(List <Utilities.PreferredFileInformation> attachments, Word.Range range, OfficeOutlook.MailItem mailItem, out int numberFailedAttachments)
        {
            List <KeyValuePair <int, int> > ranges = new List <KeyValuePair <int, int> >();
            int startIndex = range.Start;
            int endIndex   = range.End;

            range.SetRange(endIndex, endIndex);
            int itemCounter = 0;

            numberFailedAttachments = 0;
            range.InsertAfter("\n");
            range.InsertAfter("\n");

            foreach (Utilities.PreferredFileInformation fileInfo in attachments)
            {
                endIndex = range.End;

                if (this.insertAsCopy)
                {
                    range.InsertAfter("\n");
                    endIndex = range.End;

                    try
                    {
                        OfficeOutlook.Attachment attachment = mailItem.Attachments.Add(
                            fileInfo.LocalPath,
                            OfficeOutlook.OlAttachmentType.olByValue,
                            endIndex,
                            Type.Missing);

                        endIndex = attachment.Position + 30;
                    }
                    catch (System.Runtime.InteropServices.COMException ex)
                    {
                        if (ex.Message.ToUpperInvariant() == attachmentWarning.ToUpperInvariant())
                        {
                            numberFailedAttachments++;
                        }
                        else
                        {
                            throw;
                        }
                    }
                }

                range.SetRange(endIndex, endIndex);
                endIndex = range.End;

                if (this.insertAsLink)
                {
                    range.InsertAfter("\n");

                    int tempIndexStart = range.End;
                    range.InsertAfter(fileInfo.NameNoExtension);

                    int tempIndexEnd = range.End;
                    endIndex = tempIndexEnd;

                    range.SetRange(tempIndexStart, tempIndexEnd);
                    ranges.Add(new KeyValuePair <int, int>(range.Start, range.End));
                }

                itemCounter++;

                if (itemCounter < attachments.Count)
                {
                    range.InsertAfter("\n");
                    range.InsertAfter("\n");
                    range.InsertAfter("\n");
                    endIndex = range.End;
                }
            }

            if (this.insertAsLink)
            {
                int counter = 0;

                List <Utilities.PreferredFileInformation> pairs = new List <Utilities.PreferredFileInformation>();

                foreach (Utilities.PreferredFileInformation value in attachments)
                {
                    pairs.Insert(pairs.Count, value);
                }

                pairs.Reverse();
                ranges.Reverse();

                foreach (Utilities.PreferredFileInformation value in pairs)
                {
                    range.SetRange(ranges[counter].Key, ranges[counter].Value);
                    string         s         = range.Text;
                    Word.Hyperlink hyperlink = range.Hyperlinks.Add(range, value.Url, Type.Missing, Type.Missing, value.ToString());
                    endIndex = hyperlink.Range.End;
                    counter++;
                }
            }

            return(endIndex);
        }