示例#1
0
        public static void Merge(string[] filesToMerge, string outputFilename, bool insertPageBreaks, string documentTemplate)
        {
            object defaultTemplate = documentTemplate;
            object missing         = System.Type.Missing;
            object pageBreak       = Word.WdBreakType.wdPageBreak;
            object outputFile      = outputFilename;

            Word._Application wordApplication = new Word.Application();

            try
            {
                Word._Document wordDocument = wordApplication.Documents.Add(ref defaultTemplate, ref missing, ref missing, ref missing);
                Word.Selection selection    = wordApplication.Selection;

                foreach (string file in filesToMerge)
                {
                    //selection.InsertFile(file, ref missing, ref missing, ref missing, ref missing);
                    selection.InsertFile(file);

                    if (insertPageBreaks)
                    {
                        selection.InsertBreak(ref pageBreak);
                    }
                }

                wordDocument.SaveAs(ref outputFile, 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);

                wordDocument = null;
            }
            catch (Exception ex)
            {
                //TODO
                throw ex;
            }
            finally
            {
                wordApplication.Quit(ref missing, ref missing, ref missing);
            }
        }
        public static bool Merge(string[] filesToMerge, string outputFilename, bool insertPageBreaks, string documentTemplate, out string errorString)
        {
            errorString = string.Empty;
            object defaultTemplate = documentTemplate;
            object missing         = System.Type.Missing;
            object oTrue           = true;
            object oFalse          = false;
            //object pageBreak = Word.WdBreakType.wdPageBreak;
            object pageBreak  = Word.WdBreakType.wdSectionBreakNextPage;
            object outputFile = outputFilename;


            if (filesToMerge.Length == 0)
            {
                return(true);
            }


            for (int i = 0; i < filesToMerge.Length - 1; i++)
            {
                if (Path.GetExtension(filesToMerge[i]).ToUpper() == ".PDF")
                {
                    errorString = "MultiDocumentMerger.Merge() should be given word docs to merge, but pdf file sent in.";
                    return(false);
                }
            }


            if (filesToMerge.Length == 1)
            {
                if (Path.GetExtension(outputFilename).ToUpper() == ".PDF")
                {
                    string _errorString = null;
                    FormatConverter.WordToPDF(filesToMerge[0], outputFilename, out _errorString);
                    if (_errorString != string.Empty)
                    {
                        errorString = _errorString;
                        return(false);
                    }
                }
                else
                {
                    System.IO.File.Copy(filesToMerge[0], outputFilename);
                }

                return(true);
            }



            // Create  a new Word application
            Word._Application wordApplication = new Word.Application();

            try
            {
                // Create a new file based on our template
                object template = (documentTemplate == null) ? missing : defaultTemplate;

                // this doesnt keep the header info and the formatting (and background images) are all screwed up
                //Word._Document wordDocument = wordApplication.Documents.Add(ref template, ref missing, ref missing, ref missing);

                // for some reason this is placed at the end of the documents, so put the last doc in, then below add first up to 2nd last doc
                object         lastFile     = filesToMerge[filesToMerge.Length - 1];
                Word._Document wordDocument = wordApplication.Documents.Add(ref lastFile, ref missing, ref missing, ref missing);

                // Make a Word selection object.
                Word.Selection selection = wordApplication.Selection;

                // Loop thru each of the Word documents
                for (int i = 0; i < filesToMerge.Length - 1; i++)
                {
                    // Insert the files to our template
                    selection.InsertFile(
                        filesToMerge[i]
                        , ref missing
                        , ref missing
                        , ref missing
                        , ref missing);

                    //Do we want page breaks added after each documents?
                    if (i < (filesToMerge.Length - 1) && insertPageBreaks)
                    {
                        selection.InsertBreak(ref pageBreak);
                    }
                }

                // Save the document to it's output file.
                object fileFormat = System.IO.Path.GetExtension(outputFile.ToString()).ToUpper() == ".PDF" ? Word.WdSaveFormat.wdFormatPDF : missing;
                wordDocument.SaveAs(
                    ref outputFile
                    , ref fileFormat
                    , 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);

                // Clean up!
                wordDocument.Close(ref oFalse, ref missing, ref missing);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDocument);
                wordDocument = null;


                return(true);
            }
            catch (System.Exception ex)
            {
                errorString = ex.Message;
            }
            finally
            {
                //RELEASE WORD ITSELF
                wordApplication.Quit(ref missing, ref missing, ref missing);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApplication);
                wordApplication = null;

                GC.Collect();
            }

            return(false);
        }
示例#3
0
        /// <summary>
        /// A function that merges Microsoft Word Documents that uses a template specified by the user
        /// </summary>
        /// <param name="filesToMerge">An array of files that we want to merge</param>
        /// <param name="outputFilename">The filename of the merged document</param>
        /// <param name="insertPageBreaks">Set to true if you want to have page breaks inserted after each document</param>
        /// <param name="documentTemplate">The word document you want to use to serve as the template</param>
        public static void Merge(string[] filesToMerge, string outputFilename, bool insertPageBreaks, string documentTemplate)
        {
            object defaultTemplate = documentTemplate;
            object missing         = System.Type.Missing;
            object pageBreak       = Word.WdBreakType.wdPageBreak;
            object outputFile      = outputFilename;

            // Create  a new Word application
            Word._Application wordApplication = new Word.Application();

            try
            {
                // Create a new file based on our template
                Word._Document wordDocument = wordApplication.Documents.Add(
                    ref defaultTemplate
                    , ref missing
                    , ref missing
                    , ref missing);

                // Make a Word selection object.
                Word.Selection selection = wordApplication.Selection;

                // Loop thru each of the Word documents
                foreach (string file in filesToMerge)
                {
                    // Insert the files to our template
                    selection.InsertFile(
                        file
                        , ref missing
                        , ref missing
                        , ref missing
                        , ref missing);

                    //Do we want page breaks added after each documents?
                    if (insertPageBreaks)
                    {
                        selection.InsertBreak(ref pageBreak);
                    }
                }

                // Save the document to it's output file.
                wordDocument.SaveAs(
                    ref outputFile
                    , 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);

                // Clean up!
                wordDocument = null;
            }
            catch (Exception ex)
            {
                //I didn't include a default error handler so i'm just throwing the error
                throw ex;
            }
            finally
            {
                // Finally, Close our Word application
                wordApplication.Quit(ref missing, ref missing, ref missing);
            }
        }
        private void MergeWordDocs(string[] filesToMerge, string outputFilename, bool insertPageBreaks)
        {
            object missing    = System.Type.Missing;
            object pageBreak  = MSWord.WdBreakType.wdSectionBreakNextPage;
            object outputFile = outputFilename;
            object template   = @"Normal.dot";

            try
            {
                // Create a new file based on our template
                MSWord.Document wordDocument = winword.Documents.Add(
                    ref missing
                    , ref missing
                    , ref missing
                    , ref missing);

                // Make a Word selection object.
                MSWord.Selection selection = winword.Selection;

                //Count the number of documents to insert;
                int documentCount = filesToMerge.Length;

                //A counter that signals that we shoudn't insert a page break at the end of document.
                int breakStop = 0;

                // Loop thru each of the Word documents
                foreach (string file in filesToMerge)
                {
                    breakStop++;
                    // Insert the files to our template
                    selection.InsertFile(
                        file
                        , ref missing
                        , ref missing
                        , ref missing
                        , ref missing);

                    //Do we want page breaks added after each documents?
                    if (insertPageBreaks && breakStop != documentCount)
                    {
                        selection.InsertBreak(ref pageBreak);
                    }
                }

                // Save the document to it's output file.
                wordDocument.SaveAs(
                    ref outputFile
                    , 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);

                // Clean up!
                wordDocument = null;
            }
            catch (Exception ex)
            {
                //I didn't include a default error handler so i'm just throwing the error
                throw ex;
            }
            finally
            {
                // Finally, Close our Word application
                winword.Quit(ref missing, ref missing, ref missing);
            }
        }
示例#5
0
        private void btnCreateDoc_Click(object sender, RoutedEventArgs e)
        {
            if (CheckForm() == false)
            {
                return;
            }

            bool failed = false;

            btnCreateDoc.IsEnabled = false;
            btnCreateDoc.Content   = "Working";
            //Everything has to be an object(COM) to pass to word.
            object strFileName = txtPath.Text + "\\" + txtAssignment.Text + " - " + txtStudent.Text + ".doc";

            try
            {
                File.Copy(txtPath.Text + "\\GradingTemplate.doc", (string)strFileName, true);
            }
            catch
            {
                failed = true;
                MessageBox.Show("Error can't access " + strFileName);
            }

            if (failed == false)
            {
                word.Application wordApp = new word.Application();
                wordApp.Visible     = WatchWordWork;
                wordApp.WindowState = word.WdWindowState.wdWindowStateNormal;

                object missing   = System.Reflection.Missing.Value;
                object readOnly  = false;
                object isVisible = true;

                word.Document doc = wordApp.Documents.Open(ref strFileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible);
                // Activate the document so it shows up in front
                doc.Activate();

                //I don't know how to search header of word doc. Works in old word files, not docx
                //SearchReplace("#1", strCourseName, wordApp);
                //SearchReplace("#2", cmbProfessor.Text, wordApp);
                SearchReplace("#3", txtStudent.Text, wordApp);
                SearchReplace("#4", txtAssignment.Text, wordApp);

                //This magic lets me use the checkbox name as the ms word field name
                //You can just add a checkbox to the form and a spot on the template
                //and it will automatically detect it with no code changes.
                foreach (var control in this.GetChildren())
                {
                    if (control is CheckBox)
                    {
                        CheckBox chkBox = control as CheckBox;
                        if (chkBox.IsChecked == true && chkBox != chkAppend)
                        {
                            string newText = chkBox.Content.ToString();

                            //late checkbox is special
                            if (chkBox == chkLate)
                            {
                                newText += " " + howLate.ToString() + " days";
                            }

                            SearchReplace(magicspace + chkBox.Content.ToString(), magicx + newText, wordApp);
                        }
                    }
                }

                //this is a terrible way to do this...
                //but I'm short on time, I have Physics to do.
                SearchReplace("#5", txtMemoryLeak.Text, wordApp);
                SearchReplace("#6", txtIncorrectStatement.Text, wordApp);
                SearchReplace("#7", txtRedundantCode.Text, wordApp);
                SearchReplace("#8", txtBasemember.Text, wordApp);
                SearchReplace("#9", txtDestructor.Text, wordApp);
                SearchReplace("#10", txtOperatorEq.Text, wordApp);
                SearchReplace("#11", txtCopyConstructor.Text, wordApp);
                SearchReplace("#12", txtConstructor.Text, wordApp);
                SearchReplace("#13", txtNotSeperatehcpp.Text, wordApp);

                //commenting section
                SearchAndType("#14", txtMissingFunctionality.Text.ToString(), wordApp);
                SearchAndType("#15", txtRuntimeCrash.Text.ToString(), wordApp);
                SearchAndType("#16", txtLogicError.Text.ToString(), wordApp);
                SearchAndType("#17", txtComment.Text.ToString(), wordApp);

                //insert the comments at the end.
                //wordApp.Selection.EndKey(word.WdUnits.wdStory, ref missing);
                //wordApp.Selection.TypeText("\r\n\r\nComments: " + txtComment.Text);

                doc.Save();

                //Merge to one doc
                if (chkAppend.IsChecked == true)
                {
                    doc.Close();
                    object masterFile = txtPath.Text + "\\" + strCourseName + " - " + txtAssignment.Text + ".doc";

                    if (!File.Exists((string)masterFile))
                    {
                        File.Copy((string)strFileName, (string)masterFile);
                    }
                    else
                    {
                        word.Document  d         = wordApp.Documents.Open(ref masterFile, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible);
                        word.Selection selection = wordApp.Selection;

                        //should put this in function.
                        //Go to end of page.
                        Object toWhat  = word.WdGoToItem.wdGoToLine;
                        Object toWhich = word.WdGoToDirection.wdGoToLast;
                        wordApp.Selection.GoTo(toWhat, toWhich, ref missing, ref missing);
                        wordApp.Selection.EndKey(word.WdUnits.wdStory, ref missing);

                        object pageBreak = word.WdBreakType.wdPageBreak;
                        selection.InsertBreak(ref pageBreak);

                        selection.InsertFile((string)strFileName);
                        d.Save();

                        d.Close();
                        //delete old student templated file.
                        File.Delete((string)strFileName);
                    }
                }

                if (!WatchWordWork)
                {
                    wordApp.Quit();
                }
            }

            Clear();
            btnCreateDoc.Content   = "Create Doc";
            btnCreateDoc.IsEnabled = true;
        }
示例#6
0
        public static string MergeFiles(string[] filesToMerge, bool insertPageBreaks, string resultName)
        {
            object missing    = System.Type.Missing;
            object pageBreak  = Word.WdBreakType.wdPageBreak;
            object outputFile = null;

            if (resultName == null)
            {
                outputFile = Path.GetTempFileName();
            }
            else
            {
                outputFile = Path.Combine(Path.GetTempPath(), resultName);
                File.Move(Path.GetTempFileName(), outputFile.ToString());
            }

            Word._Application wordApplication = null;
            Word._Document    wordDocument    = null;
            try
            {
                wordApplication = new Word.Application();
                wordDocument    = wordApplication.Documents.Add(ref outputFile, ref missing, ref missing, ref missing);

                Word.Selection selection = wordApplication.Selection;
                foreach (string file in filesToMerge)
                {
                    selection.InsertFile(file, ref missing, ref missing, ref missing, ref missing);
                    if (insertPageBreaks)
                    {
                        selection.InsertBreak(ref pageBreak);
                    }
                }

                wordDocument.PageSetup.TopMargin    = 20;
                wordDocument.PageSetup.BottomMargin = 20;
                wordDocument.PageSetup.LeftMargin   = 50;
                //wordDocument.Paragraphs.CharacterUnitFirstLineIndent = 1.5F;

                wordDocument.SaveAs(ref outputFile);
                Console.WriteLine("Generated file after merge=" + outputFile);
                return(outputFile.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
                if (outputFile != null)
                {
                    File.Delete(outputFile.ToString());
                }
            }
            finally
            {
                if (wordDocument != null)
                {
                    wordDocument.Close();
                    wordDocument = null;
                }
                if (wordApplication != null)
                {
                    wordApplication.Quit();
                    wordApplication = null;
                }
                foreach (string path in filesToMerge)
                {
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                    }
                }
            }
            return(null);
        }
示例#7
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            bool failed = false;

            btnSave.Enabled = false;
            btnSave.Text    = "Working";
            //Everything has to be an object(COM) to pass to word.
            object strFileName = txtPath.Text + "\\" + cmboHomework.Text + " - " + cmboStudentName.Text + ".doc";

            try
            {
                File.Copy(txtPath.Text + "\\GradingTemplate.doc", (string)strFileName, true);
            }
            catch
            {
                failed = true;
                MessageBox.Show("Error can't access " + strFileName);
            }

            if (failed == false)
            {
                word.Application wordApp = new word.Application();
                wordApp.Visible     = chkMSWord.Checked;
                wordApp.WindowState = word.WdWindowState.wdWindowStateNormal;

                object missing   = System.Reflection.Missing.Value;
                object readOnly  = false;
                object isVisible = true;

                word.Document doc = wordApp.Documents.Open(ref strFileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible);
                // Activate the document so it shows up in front
                doc.Activate();


                SearchReplace("#1", cmboClass.Text, wordApp);
                SearchReplace("#2", cmboProfessor.Text, wordApp);
                SearchReplace("#3", cmboStudentName.Text, wordApp);
                SearchReplace("#4", cmboHomework.Text, wordApp);

                //This magic lets me use the checkbox name as the ms word field name
                //You can just add a checkbox to the form and a spot on the template
                //and it will automatically detect it with no code changes.
                foreach (var chkBox in Utility.GetAllChildren(this).OfType <CheckBox>())
                {
                    if (chkBox.Checked && chkBox != chkMSWord)
                    {
                        string newText = chkBox.Text;
                        if (chkBox.Text == "Late submission")
                        {
                            newText += " " + txtDaysLate.Text + " days";
                        }

                        SearchReplace(magicspace + chkBox.Text, magicx + newText, wordApp);
                    }
                }

                //insert the comments at the end.

                wordApp.Selection.EndKey(word.WdUnits.wdStory, ref missing);
                wordApp.Selection.TypeText("\r\n\r\nComments: " + txtComments.Text);

                doc.Save();

                //Merge to one doc
                if (chkSingleFile.Checked)
                {
                    doc.Close();
                    object masterFile = txtPath.Text + "\\" + cmboClass.Text + " - " + cmboHomework.Text + ".doc";
                    if (!File.Exists((string)masterFile))
                    {
                        File.Copy((string)strFileName, (string)masterFile);
                    }
                    else
                    {
                        word.Document  d         = wordApp.Documents.Open(ref masterFile, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible);
                        word.Selection selection = wordApp.Selection;

                        //should put this in function.
                        //Go to end of page.
                        Object toWhat  = word.WdGoToItem.wdGoToLine;
                        Object toWhich = word.WdGoToDirection.wdGoToLast;
                        wordApp.Selection.GoTo(toWhat, toWhich, ref missing, ref missing);
                        wordApp.Selection.EndKey(word.WdUnits.wdStory, ref missing);

                        object pageBreak = word.WdBreakType.wdPageBreak;
                        selection.InsertBreak(ref pageBreak);

                        selection.InsertFile((string)strFileName);
                        d.Save();

                        if (!chkMSWord.Checked)
                        {
                            d.Close();
                        }
                    }
                }

                //leave it open for inspection if chosen
                if (!chkMSWord.Checked)
                {
                    if (!chkSingleFile.Checked)
                    {
                        doc.Close();
                    }

                    wordApp.Quit();
                }
            }

            btnSave.Enabled = true;
            btnSave.Text    = "Save";
            btnClear_Click(this, null);
        }