Exemple #1
0
        private void ShowHiddenBtn_Click(object sender, RibbonControlEventArgs e)
        {
            Microsoft.Office.Interop.Word._Application app = Globals.ThisAddIn.Application;
            Microsoft.Office.Interop.Word.Shape        tBox;
            Microsoft.Office.Interop.Word.View         currentView = app.ActiveWindow.View;

            foreach (Microsoft.Office.Interop.Word.Shape s in app.ActiveDocument.Shapes)
            {
                if (s.Name == "MLStatus")
                {
                    tBox = s;
                    if (tBox.Visible == MsoTriState.msoTrue)
                    {
                        tBox.Visible = MsoTriState.msoFalse;
                        currentView.ShowHiddenText = false;
                    }
                    else
                    {
                        tBox.Visible = MsoTriState.msoTrue;
                        currentView.ShowHiddenText = true;
                    }
                    break;
                }
            }
        }
        private void btn_AcceptFormatting_Click(object sender, RibbonControlEventArgs e)
        {
            Word.Document doc  = Globals.ThisAddIn.Application.ActiveDocument;
            Word.Window   win  = Globals.ThisAddIn.Application.ActiveWindow;
            Word.View     view = win.View;

            view.ShowComments               = false;
            view.ShowInkAnnotations         = false;
            view.ShowInsertionsAndDeletions = false;

            doc.AcceptAllRevisionsShown();

            view.ShowComments               = true;
            view.ShowInkAnnotations         = true;
            view.ShowInsertionsAndDeletions = true;
            MessageBox.Show("Formatting changes have been accepted.");
        }
        public void AcceptChanges()
        {
            Word.Document doc  = Globals.ThisAddIn.Application.ActiveDocument;
            Word.Window   win  = Globals.ThisAddIn.Application.ActiveWindow;
            Word.View     view = win.View;

            view.ShowComments               = false;
            view.ShowInkAnnotations         = false;
            view.ShowInsertionsAndDeletions = false;

            doc.AcceptAllRevisionsShown();

            view.ShowComments               = true;
            view.ShowInkAnnotations         = true;
            view.ShowInsertionsAndDeletions = true;
            //MessageBox.Show("Formatting changes have been accepted.");
        }
Exemple #4
0
        public void buildIfEmptyField(Word.Range rngTarget, object PageString, object textString, string data)
        {
            string sQ = '"'.ToString();

            Word.Field fldIf = null;
            Word.View  vw    = Doc.ActiveWindow.View;
            rngTarget.Text = " ";
            rngTarget.End  = rngTarget.Start;
            bool   bViewFldCodes = false;
            string sFieldCode;
            string pageVar = "{PAGE  \\* ARABIC}";
            string docVar  = "{DOCVARIABLE " + sQ + "edocs_Page" + pageVar + "_page" + sQ + "\\* MERGEFORMAT}";

            if (data == "page")
            {
                docVar = pageVar;
            }
            string fullPageVar = "{DOCVARIABLE " + sQ + "edocs_Page" + docVar + "_" + data + sQ + "}";
            string ifVar       = "IF" + fullPageVar + "=" + sQ + "Error!*" + sQ + " " + sQ + "eDoc Empty Field" + sQ + fullPageVar;

            System.Diagnostics.Debug.WriteLine("String - " + ifVar);

            bViewFldCodes = vw.ShowFieldCodes;
            //Finding text in a field codes requires field codes to be shown
            if (!bViewFldCodes)
            {
                vw.ShowFieldCodes = true;
            }


            fldIf      = rngTarget.Fields.Add(rngTarget, Word.WdFieldType.wdFieldEmpty, ifVar, false);
            sFieldCode = GenerateNestedField(fldIf, fullPageVar, true);
            sFieldCode = GenerateNestedField(fldIf, fullPageVar, false);
            if (data != "page")
            {
                sFieldCode = GenerateNestedField(fldIf, docVar, true);
                sFieldCode = GenerateNestedField(fldIf, docVar, false);
            }
            sFieldCode = GenerateNestedField(fldIf, pageVar, true);
            sFieldCode = GenerateNestedField(fldIf, pageVar, false);
            rngTarget.Fields.Update();
            vw.ShowFieldCodes = bViewFldCodes;
        }
Exemple #5
0
        //########################The following declarations and methods are different in .NET 3.5######################//

        private void XLantWordRibbon_Load(object sender, RibbonUIEventArgs e)
        {
            try
            {
                Microsoft.Office.Interop.Word.View currentView = Globals.ThisAddIn.Application.ActiveWindow.View;

                if (currentView.ShowHiddenText)
                {
                    ShowHiddenBtn.Checked = true;
                }
                else
                {
                    ShowHiddenBtn.Checked = false;
                }
            }
            catch (Exception ex)
            {
                XLtools.LogException("No document loaded", ex.Message);
            }
        }
Exemple #6
0
        private static bool Replace(Word.Document oDoc, MacrosVerbCollection macrosCollection)
        {
            Word.Comment comment;
            Word.Range   range;
            for (int i = oDoc.Comments.Count; i > 0; i--)
            {
                comment = oDoc.Comments[i];
                KeyValuePair <string, int> key = new KeyValuePair <string, int>(comment.Range.Text, 1);
                if (macrosCollection.ContainsKey(key))
                {
                    range = comment.Scope;
                    comment.Delete();
                    range.Text = macrosCollection[key];
                    object name = (object)key.Key;
                    oDoc.Comments.Add(range, ref name);
                }
            }
            Word.View view = oDoc.Application.ActiveWindow.View;
            view.ShowComments = false;

            return(true);
        }
        private void btn_ProperNouns_Click(object sender, RibbonControlEventArgs e)
        {
            Word.Document    doc      = Globals.ThisAddIn.Application.ActiveDocument;
            HashSet <string> wordlist = new HashSet <string>();

            foreach (Word.Range rng in TextHelpers.GetText(doc))
            {
                string     txt   = rng.Text;
                Word.Style style = rng.get_Style();
                if (style != null)
                {
                    Regex re_heading = new Regex(@"(?i)(heading|title|date|toc)");
                    Match m          = re_heading.Match(style.NameLocal);
                    if (m.Success)
                    {
                        continue;
                    }
                }

                HashSet <string> propers = new HashSet <string>();
                propers = TextHelpers.ProperNouns(txt);
                wordlist.UnionWith(propers);
            }

            //Produce the groupings
            HashSet <string> capped = TextHelpers.KeepCaps(wordlist);

            //DoubleMetaphone
            Dictionary <ushort, List <string> > mpgroups = new Dictionary <ushort, List <string> >();
            //Dictionary<string, List<string>> mpgroups = new Dictionary<string, List<string>>();
            ShortDoubleMetaphone sdm = new ShortDoubleMetaphone();

            //HashSet<string> tested = new HashSet<string>();

            foreach (string word in capped)
            {
                /*
                 * if (tested.Contains(word))
                 * {
                 *  continue;
                 * }
                 * else
                 * {
                 *  tested.Add(word);
                 * }
                 */
                sdm.computeKeys(word);
                ushort pri = sdm.PrimaryShortKey;
                ushort alt = sdm.AlternateShortKey;
                if (mpgroups.ContainsKey(pri))
                {
                    mpgroups[pri].Add(word);
                }
                else
                {
                    List <string> node = new List <string>();
                    node.Add(word);
                    mpgroups[pri] = node;
                }
                if (mpgroups.ContainsKey(alt))
                {
                    mpgroups[alt].Add(word);
                }
                else
                {
                    List <string> node = new List <string>();
                    node.Add(word);
                    mpgroups[alt] = node;
                }
            }

            //Edit Distance
            List <string> dtested = new List <string>();
            int           mindist;

            int.TryParse(Properties.Settings.Default.mindist, out mindist);
            if (mindist == 0)
            {
                mindist = 2;
            }
            Dictionary <string, List <string> > distgroups = new Dictionary <string, List <string> >();

            foreach (string word1 in capped)
            {
                if (dtested.Contains(word1))
                {
                    continue;
                }
                else
                {
                    dtested.Add(word1);
                }

                if (word1.Length <= mindist)
                {
                    continue;
                }

                foreach (string word2 in capped)
                {
                    if (word2.Length <= mindist)
                    {
                        continue;
                    }
                    int dist = TextHelpers.EditDistance(word1, word2);
                    //int percent = (int)Math.Round((dist / word1.Length) * 100.0);
                    if ((dist > 0) && (dist <= mindist))
                    //if ((dist > 0) && (percent <= distpercent))
                    {
                        dtested.Add(word2);
                        if (distgroups.ContainsKey(word1))
                        {
                            distgroups[word1].Add(word2);
                        }
                        else
                        {
                            List <string> node = new List <string>();
                            node.Add(word2);
                            distgroups[word1] = node;
                        }
                    }
                }
            }

            //Create new document
            Word.Document newdoc = Globals.ThisAddIn.Application.Documents.Add();
            Word.View     view   = Globals.ThisAddIn.Application.ActiveWindow.View;
            view.DisplayPageBoundaries = false;
            Word.Paragraph pgraph;

            //Intro text
            pgraph = newdoc.Content.Paragraphs.Add();
            pgraph.set_Style(newdoc.Styles["Heading 1"]);
            pgraph.Range.Text = "Proper Noun Checker\n";
            pgraph            = newdoc.Content.Paragraphs.Add();
            pgraph.set_Style(newdoc.Styles["Normal"]);
            pgraph.Range.Text = "This tool only looks at words that start with a capital letter. It then uses phonetic comparison and edit distance to find other proper nouns that are similar. Words in all caps (acronyms) are not included.\n";
            pgraph            = newdoc.Content.Paragraphs.Add();
            pgraph.Range.Text = "The system tries to ignore words at the beginning of sentences and in headers. This means some errors may go unseen, so use multiple tools!\n";
            pgraph            = newdoc.Content.Paragraphs.Add();
            pgraph.Range.Text = "Most of what you see here are false positives! That's unavoidable. But it still catches certain otherwise-hard-to-find misspellings.\n";

            pgraph = newdoc.Content.Paragraphs.Add();
            pgraph.Range.InsertBreak(Word.WdBreakType.wdSectionBreakContinuous);
            Word.Section sec = newdoc.Sections[2];
            sec.PageSetup.TextColumns.SetCount(2);
            sec.PageSetup.TextColumns.LineBetween = -1;

            //Distance
            pgraph = newdoc.Content.Paragraphs.Add();
            pgraph.set_Style(newdoc.Styles["Heading 2"]);
            //pgraph.KeepWithNext = 0;
            pgraph.Range.Text = "Edit Distance (" + mindist + ")\n";

            foreach (string key in distgroups.Keys)
            {
                List <string> group = distgroups[key];
                pgraph = newdoc.Content.Paragraphs.Add();
                pgraph.set_Style(newdoc.Styles["Normal"]);
                pgraph.Range.Text = key + ", " + string.Join(", ", group) + "\n";
            }

            pgraph.Range.InsertBreak(Word.WdBreakType.wdPageBreak);
            //pgraph = newdoc.Content.Paragraphs.Add();
            //pgraph.Range.InsertBreak(Word.WdBreakType.wdSectionBreakContinuous);
            //Word.InlineShape line = pgraph.Range.InlineShapes.AddHorizontalLineStandard();
            //line.Height = 2;
            //line.Fill.Solid();
            //line.HorizontalLineFormat.NoShade = true;
            //line.Fill.ForeColor.RGB = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
            //line.HorizontalLineFormat.PercentWidth = 90;
            //line.HorizontalLineFormat.Alignment = WdHorizontalLineAlignment.wdHorizontalLineAlignCenter;
            //sec = newdoc.Sections[3];
            //sec.PageSetup.TextColumns.SetCount(2);
            //sec.PageSetup.TextColumns.LineBetween = -1;

            //Metaphone
            pgraph = newdoc.Content.Paragraphs.Add();
            pgraph.set_Style(newdoc.Styles["Heading 2"]);
            //pgraph.KeepWithNext = 0;
            pgraph.Range.Text = "Phonetic Comparisons\n";

            foreach (ushort key in mpgroups.Keys)
            {
                if (key == 65535)
                {
                    continue;
                }
                List <string> group = mpgroups[key];
                if (group.Count > 1)
                {
                    pgraph = newdoc.Content.Paragraphs.Add();
                    pgraph.set_Style(newdoc.Styles["Normal"]);
                    pgraph.Range.Text = string.Join(", ", group) + "\n";
                }
            }

            //pgraph = newdoc.Content.Paragraphs.Add();
            //pgraph.Range.InsertBreak(Word.WdBreakType.wdSectionBreakContinuous);
            newdoc.GrammarChecked = true;
        }
Exemple #8
0
        /// <summary>
        /// Convert a Word file to PDF
        /// </summary>
        /// <param name="inputFile">Full path of the input Word file</param>
        /// <param name="outputFile">Full path of the output PDF</param>
        /// <returns></returns>
        public static new int Convert(String inputFile, String outputFile, Hashtable options)
        {
            Boolean running = (Boolean)options["noquit"];

            Microsoft.Office.Interop.Word.Application word = null;
            object oMissing = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word.Template tmpl;
            String           temporaryStorageDir = null;
            float            wordVersion         = 0;
            List <AppOption> wordOptionList      = new List <AppOption>();

            try
            {
                String  filename           = (String)inputFile;
                Boolean hasSignatures      = WordConverter.hasDigitalSignatures(filename);
                Boolean visible            = !(Boolean)options["hidden"];
                Boolean openAndRepair      = !(Boolean)options["word_no_repair"];
                Boolean nowrite            = (Boolean)options["readonly"];
                Boolean includeProps       = !(Boolean)options["excludeprops"];
                Boolean includeTags        = !(Boolean)options["excludetags"];
                Boolean bitmapMissingFonts = !(Boolean)options["word_ref_fonts"];
                Boolean autosave           = options.ContainsKey("IsTempWord") && (Boolean)options["IsTempWord"];
                bool    pdfa          = (Boolean)options["pdfa"] ? true : false;
                String  writePassword = "";
                String  readPassword  = "";
                int     maxPages      = 0;

                WdExportOptimizeFor     quality    = WdExportOptimizeFor.wdExportOptimizeForPrint;
                WdExportItem            showMarkup = WdExportItem.wdExportDocumentContent;
                WdExportCreateBookmarks bookmarks  = (Boolean)options["bookmarks"] ?
                                                     WdExportCreateBookmarks.wdExportCreateHeadingBookmarks :
                                                     WdExportCreateBookmarks.wdExportCreateNoBookmarks;
                Microsoft.Office.Interop.Word.Options   wdOptions      = null;
                Microsoft.Office.Interop.Word.Documents documents      = null;
                Microsoft.Office.Interop.Word.Template  normalTemplate = null;

                tmpl = null;
                try
                {
                    word = (Microsoft.Office.Interop.Word.Application)Marshal.GetActiveObject("Word.Application");
                }
                catch (System.Exception)
                {
                    int tries = 10;
                    word    = new Microsoft.Office.Interop.Word.Application();
                    running = false;
                    while (tries > 0)
                    {
                        try
                        {
                            // Try to set a property on the object
                            word.ScreenUpdating = false;
                        }
                        catch (COMException)
                        {
                            // Decrement the number of tries and have a bit of a snooze
                            tries--;
                            Thread.Sleep(500);
                            continue;
                        }
                        // Looks ok, so bail out of the loop
                        break;
                    }
                    if (tries == 0)
                    {
                        Converter.releaseCOMObject(word);
                        return((int)ExitCode.ApplicationError);
                    }
                }

                wdOptions          = word.Options;
                word.DisplayAlerts = WdAlertLevel.wdAlertsNone;
                // Issue #48 - we should allow control over whether the history is lost
                if (!(Boolean)options["word_keep_history"])
                {
                    word.DisplayRecentFiles = false;
                }
                word.DisplayDocumentInformationPanel = false;
                word.FeatureInstall = Microsoft.Office.Core.MsoFeatureInstall.msoFeatureInstallNone;
                wordVersion         = (float)System.Convert.ToDecimal(word.Version, new CultureInfo("en-US"));

                // Set the Word options in a way that allows us to reset the options when we finish
                try
                {
                    wordOptionList.Add(new AppOption("AlertIfNotDefault", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("AllowReadingMode", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("PrecisePositioning", true, ref wdOptions));
                    wordOptionList.Add(new AppOption("UpdateFieldsAtPrint", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("UpdateLinksAtPrint", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("UpdateLinksAtOpen", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("UpdateFieldsWithTrackedChangesAtPrint", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("WarnBeforeSavingPrintingSendingMarkup", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("BackgroundSave", true, ref wdOptions));
                    wordOptionList.Add(new AppOption("SavePropertiesPrompt", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("DoNotPromptForConvert", true, ref wdOptions));
                    wordOptionList.Add(new AppOption("PromptUpdateStyle", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("ConfirmConversions", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("CheckGrammarAsYouType", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("CheckGrammarWithSpelling", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("CheckSpellingAsYouType", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("DisplaySmartTagButtons", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("EnableLivePreview", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("ShowReadabilityStatistics", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("SuggestSpellingCorrections", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("AllowDragAndDrop", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("EnableMisusedWordsDictionary", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("ShowFormatError", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("StoreRSIDOnSave", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("SaveNormalPrompt", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("AllowFastSave", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("BackgroundOpen", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("ShowMarkupOpenSave", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("SaveInterval", 0, ref wdOptions));
                }
                catch (SystemException)
                {
                }

                // Set up the PDF output quality
                if ((Boolean)options["print"])
                {
                    quality = WdExportOptimizeFor.wdExportOptimizeForPrint;
                }
                if ((Boolean)options["screen"])
                {
                    quality = WdExportOptimizeFor.wdExportOptimizeForOnScreen;
                }

                if ((Boolean)options["markup"])
                {
                    showMarkup = WdExportItem.wdExportDocumentWithMarkup;
                }

                if (!String.IsNullOrEmpty((String)options["password"]))
                {
                    readPassword = (String)options["password"];
                }

                if (!String.IsNullOrEmpty((String)options["writepassword"]))
                {
                    writePassword = (String)options["writepassword"];
                }

                // Large Word files may simply not print reliably - if the word_max_pages
                // configuration option is set, then we must close up and forget about
                // converting the file.
                maxPages = (int)options[@"word_max_pages"];

                documents      = word.Documents;
                normalTemplate = word.NormalTemplate;

                // Check for password protection and no password
                if (Converter.IsPasswordProtected(inputFile) && String.IsNullOrEmpty(readPassword))
                {
                    normalTemplate.Saved = true;
                    Console.WriteLine("Unable to open password protected file");
                    return((int)ExitCode.PasswordFailure);
                }

                // Having signatures means we should open the document very carefully
                if (hasSignatures)
                {
                    nowrite       = true;
                    autosave      = false;
                    openAndRepair = false;
                }

                Microsoft.Office.Interop.Word.Document doc = null;
                try
                {
                    if ((bool)options["merge"] && !String.IsNullOrEmpty((string)options["template"]) &&
                        File.Exists((string)options["template"]) &&
                        System.Text.RegularExpressions.Regex.IsMatch((string)options["template"], @"^.*\.dot[mx]?$", System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                    {
                        // Create a new document based on a template
                        doc = documents.Add((string)options["template"]);
                        Object rStart = 0;
                        Object rEnd   = 0;
                        Range  range  = doc.Range(rStart, rEnd);
                        range.InsertFile(inputFile);
                        Converter.releaseCOMObject(range);
                        // Make sure we save the file with the original filename so
                        // filename fields update correctly
                        temporaryStorageDir = Path.GetTempFileName();
                        File.Delete(temporaryStorageDir);
                        Directory.CreateDirectory(temporaryStorageDir);
                        doc.SaveAs(Path.Combine(temporaryStorageDir, Path.GetFileName(inputFile)));
                    }
                    else
                    {
                        // Open the source document
                        doc = documents.OpenNoRepairDialog(FileName: filename, ReadOnly: nowrite, PasswordDocument: readPassword, WritePasswordDocument: writePassword, Visible: visible, OpenAndRepair: openAndRepair);
                    }
                }
                catch (System.Runtime.InteropServices.COMException)
                {
                    Console.WriteLine("Unable to open file");
                    return((int)ExitCode.FileOpenFailure);
                }

                // Check if there are signatures in the document which changes how we do things
                if (hasSignatures)
                {
                    // Add in a delay to allow signatures to load
                    Thread.Sleep(500);
                }
                else
                {
                    Microsoft.Office.Interop.Word.Window docWin     = null;
                    Microsoft.Office.Interop.Word.View   docWinView = null;

                    doc.Activate();
                    // Check if there are too many pages
                    if (maxPages > 0)
                    {
                        var pageCount = doc.ComputeStatistics(WdStatistic.wdStatisticPages, false);
                        doc.Saved = true;
                        if (pageCount > maxPages)
                        {
                            throw new Exception(String.Format("Too many pages to process ({0}). More than {1}", pageCount, maxPages));
                        }
                    }

                    // Prevent "property not available" errors, see http://blogs.msmvps.com/wordmeister/2013/02/22/word2013bug-not-available-for-reading/
                    docWin     = doc.ActiveWindow;
                    docWinView = docWin.View;
                    if (wordVersion >= 15)
                    {
                        docWinView.ReadingLayout = false;
                    }

                    // Sometimes the print view will not be available (e.g. for a blog post)
                    // Try and switch view
                    try
                    {
                        docWinView.Type = WdViewType.wdPrintPreview;
                    }
                    catch (Exception) { }

                    // Hide comments
                    try
                    {
                        docWinView.RevisionsView            = WdRevisionsView.wdRevisionsViewFinal;
                        docWinView.ShowRevisionsAndComments = false;
                    }
                    catch (SystemException) { }

                    // Try to avoid Word thinking any changes are happening to the document
                    doc.SpellingChecked = true;
                    doc.GrammarChecked  = true;

                    // Changing these properties may be disallowed if the document is protected
                    // and is not signed
                    if (doc.ProtectionType == WdProtectionType.wdNoProtection && !hasSignatures)
                    {
                        if (autosave)
                        {
                            doc.Save(); doc.Saved = true;
                        }
                        doc.TrackMoves      = false;
                        doc.TrackRevisions  = false;
                        doc.TrackFormatting = false;
                    }

                    normalTemplate.Saved = true;

                    // Hide the document window if need be
                    if ((Boolean)options["hidden"])
                    {
                        var activeWin = word.ActiveWindow;
                        activeWin.Visible     = false;
                        activeWin.WindowState = WdWindowState.wdWindowStateMinimize;
                        Converter.releaseCOMObject(activeWin);
                    }

                    // Check if we have a template file to apply to this document
                    // The template must be a file and must end in .dot, .dotx or .dotm
                    if (!String.IsNullOrEmpty((String)options["template"]) && !(bool)options["merge"])
                    {
                        string template = (string)options["template"];
                        if (File.Exists(template) && System.Text.RegularExpressions.Regex.IsMatch(template, @"^.*\.dot[mx]?$"))
                        {
                            doc.set_AttachedTemplate(template);
                            doc.UpdateStyles();
                            tmpl = doc.get_AttachedTemplate();
                        }
                        else
                        {
                            Console.WriteLine("Invalid template '{0}'", template);
                        }
                    }

                    // See if we have to update fields
                    if (!(Boolean)options["word_no_field_update"])
                    {
                        updateDocumentFields(doc, word, inputFile, options);
                    }

                    var pageSetup = doc.PageSetup;
                    if ((float)options["word_header_dist"] >= 0)
                    {
                        pageSetup.HeaderDistance = (float)options["word_header_dist"];
                    }
                    if ((float)options["word_footer_dist"] >= 0)
                    {
                        pageSetup.FooterDistance = (float)options["word_footer_dist"];
                    }
                    Converter.releaseCOMObject(pageSetup);
                    try
                    {
                        // Make sure we are not in a header footer view
                        docWinView.SeekView = WdSeekView.wdSeekPrimaryHeader;
                        docWinView.SeekView = WdSeekView.wdSeekPrimaryFooter;
                        docWinView.SeekView = WdSeekView.wdSeekMainDocument;
                    }
                    catch (Exception)
                    {
                        // We might fail when switching views
                    }

                    normalTemplate.Saved = true;
                    if (autosave)
                    {
                        doc.Save();
                    }
                    doc.Saved = true;
                    Converter.releaseCOMObject(docWinView);
                    Converter.releaseCOMObject(docWin);
                }

                doc.ExportAsFixedFormat(outputFile, WdExportFormat.wdExportFormatPDF, false,
                                        quality, WdExportRange.wdExportAllDocument,
                                        1, 1, showMarkup, includeProps, true, bookmarks, includeTags, bitmapMissingFonts, pdfa);

                if (tmpl != null)
                {
                    tmpl.Saved = true;
                }

                object saveChanges = autosave? WdSaveOptions.wdSaveChanges : WdSaveOptions.wdDoNotSaveChanges;
                if (nowrite)
                {
                    doc.Saved = true;
                }
                normalTemplate.Saved = true;
                ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing);

                // Reset options
                foreach (AppOption opt in wordOptionList)
                {
                    opt.resetValue(ref wdOptions);
                }

                Converter.releaseCOMObject(wdOptions);
                Converter.releaseCOMObject(documents);
                Converter.releaseCOMObject(doc);
                Converter.releaseCOMObject(tmpl);
                Converter.releaseCOMObject(normalTemplate);

                return((int)ExitCode.Success);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return((int)ExitCode.UnknownError);
            }
            finally
            {
                if (temporaryStorageDir != null && Directory.Exists(temporaryStorageDir))
                {
                    try
                    {
                        if (File.Exists(Path.Combine(temporaryStorageDir, Path.GetFileName(inputFile))))
                        {
                            File.Delete(Path.Combine(temporaryStorageDir, Path.GetFileName(inputFile)));
                        }
                        Directory.Delete(temporaryStorageDir);
                    }
                    catch (Exception) { }
                }
                if (word != null && !running)
                {
                    closeWordApplication(word);
                }
                Converter.releaseCOMObject(word);
            }
        }
Exemple #9
0
        public List <header> getHeadingArray(List <object> headingStyles)
        {
            List <header> PageHeader      = new List <header>();
            int           rngPageNumber   = 0;
            int           firstHeaderPage = 0;
            header        midHeader       = new header(0, "");

            Word.View vw = Doc.ActiveWindow.View;
            vw.MarkupMode    = Word.WdRevisionsMode.wdInLineRevisions;
            vw.RevisionsView = Word.WdRevisionsView.wdRevisionsViewFinal;
            int DocPageNumber = GetPageNumber(Doc);

            System.Diagnostics.Debug.WriteLine("DocPageNumber process doc - " + DocPageNumber);
            for (int i = 0; i < headingStyles.Count; i++)
            {
                if (headingStyles[i].Equals("Empty"))
                {
                    continue;
                }
                Word.Range rng = Doc.Content;
                rng.Find.set_Style(headingStyles[i]);
                midHeader.pageNum = 0;
                firstHeaderPage   = 0;
                while (rng.Find.Execute())
                {
                    if (IsAlert && settings.alert.worker.CancellationPending)
                    {
                        return(null);
                    }
                    rngPageNumber = GetPageNumberOfRange(rng);
                    if (rng.Text.Trim() != "" && rng.Text.Length > 3)
                    {
                        if (rngPageNumber > firstHeaderPage)
                        {
                            if (midHeader.pageNum != 0 && midHeader.pageNum < rngPageNumber)
                            {
                                PageHeader.Add(new header(midHeader.pageNum, midHeader.headingNum));
                                midHeader.pageNum = 0;
                            }
                            else
                            {
                                midHeader.pageNum = 0;
                            }
                            firstHeaderPage = rngPageNumber;
                            PageHeader.Add(new header(firstHeaderPage, getStringFromHeader(rng)));
                            Doc.Application.Selection.GoTo(ref What, ref Which, firstHeaderPage, ref missing);
                        }
                        else
                        {
                            midHeader.headingNum = getStringFromHeader(rng);
                            midHeader.pageNum    = rngPageNumber + 1;
                        }
                        rng.Start = rng.End;
                    }
                    else
                    {
                        rng.Start = rng.End;
                    }
                }
                if (midHeader.pageNum != 0)
                {
                    PageHeader.Add(new header(midHeader.pageNum, midHeader.headingNum));
                }
            }
            return(PageHeader);
        }
Exemple #10
0
        /// <summary>
        /// Save word document to images. The type of output images is png.
        /// </summary>
        /// <param name="directory">Specifies the directory for output images.</param>
        public void SaveToImages(string directory)
        {
            InteropWord.Windows windows = this.document.Windows;
            int windowCount             = windows.Count;

            for (var i = 1; i <= windowCount; i++)
            {
                InteropWord.Window win         = windows[i];
                InteropWord.View   windowsView = win.View;

                // Pages can only be retrieved in print layout view.
                windowsView.Type = InteropWord.WdViewType.wdPrintView;

                InteropWord.Panes panes = win.Panes;
                int paneCount           = panes.Count;
                for (var j = 1; j <= paneCount; j++)
                {
                    InteropWord.Pane pane = panes[j];
                    var pages             = pane.Pages;
                    var pageCount         = pages.Count;
                    for (var k = 1; k <= pageCount;)
                    {
                        InteropWord.Page p = null;

                        try {
                            p = pages[k];
                        }
                        catch
                        {
                            // pages[k] sometimes throws exception: 'System.Runtime.InteropServices.COMException: The requested member of the collection does not exist'.
                            // This is a workaround for this issue.
                            continue;
                        }

                        var bits   = p.EnhMetaFileBits;
                        var target = directory + string.Format(@"\{0}_image.doc", k);
                        using (var ms = new MemoryStream((byte[])(bits)))
                        {
                            var image       = System.Drawing.Image.FromStream(ms);
                            var imageTarget = Path.ChangeExtension(target, "png");
                            image.Save(imageTarget, ImageFormat.Png);
                        }

                        Marshal.ReleaseComObject(p);
                        p = null;

                        k++;
                    }

                    Marshal.ReleaseComObject(pages);
                    pages = null;

                    Marshal.ReleaseComObject(windowsView);
                    windowsView = null;

                    Marshal.ReleaseComObject(pane);
                    pane = null;
                }

                Marshal.ReleaseComObject(panes);
                panes = null;

                Marshal.ReleaseComObject(win);
                win = null;
            }

            Marshal.ReleaseComObject(windows);
            windows = null;
        }
 public static void UpdateCurrentView()
 {
     currentView = app.ActiveWindow.View;
 }