Exemple #1
0
        private void addPages(string docLoc, Word.Table oTable)
        {
            Microsoft.Office.Interop.Word.Application word = null;
            word = new Microsoft.Office.Interop.Word.Application();

            object inputFile          = docLoc;
            object confirmConversions = false;
            object readOnly           = true;
            object visible            = false;
            object missing            = Type.Missing;

            // Open the document...
            Microsoft.Office.Interop.Word.Document tempDoc = null;
            tempDoc = word.Documents.Open(
                ref inputFile, ref confirmConversions, ref readOnly, ref missing,
                ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref visible,
                ref missing, ref missing, ref missing, ref missing);
            tempDoc.Activate();

            string           tempPageString       = "";
            string           tempPageRevisionText = "";
            string           tempPageDateText     = "";
            List <multiLOEP> pageMultiLOEP        = new List <multiLOEP>();

            for (int i = 1; i <= GetPageNumber(tempDoc); i++)
            {
                tempPageString       = getString(tempDoc, "edocs_Page" + i + "_page");
                tempPageRevisionText = getString(tempDoc, "edocs_Page" + tempPageString + "_rev");
                tempPageDateText     = getString(tempDoc, "edocs_Page" + tempPageString + "_date");
                if (pageMultiLOEP.Count == 0)
                {
                    pageMultiLOEP.Add(new multiLOEP(tempPageString, tempPageRevisionText, tempPageDateText));
                }
                else if (pageMultiLOEP[pageMultiLOEP.Count - 1].rev != tempPageRevisionText)
                {
                    if (addRows(oTable.Rows[oTable.Rows.Count], pageMultiLOEP[pageMultiLOEP.Count - 1]))
                    {
                        oTable.Rows.Add();
                    }
                    pageMultiLOEP.Add(new multiLOEP(tempPageString, tempPageRevisionText, tempPageDateText));
                }
                else
                {
                    pageMultiLOEP[pageMultiLOEP.Count - 1].endPage = tempPageString;
                }
            }
            addRows(oTable.Rows[oTable.Rows.Count], pageMultiLOEP[pageMultiLOEP.Count - 1]);
            tempDoc.Close(null, null, null);
            word.Quit(null, null, null);
            word = null;
            GC.Collect();
            System.Diagnostics.Debug.WriteLine("Finish Multi");
        }
        private bool CrearPDF()
        {
            try
            {
                rutaCarpeta = rutaCarpeta.Replace("\\bin\\Debug", "");

                CrearWord();
                Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();

                object oMissing = System.Reflection.Missing.Value;
                word.Visible        = false;
                word.ScreenUpdating = false;

                FileInfo wordFile = new FileInfo(rutaCarpeta + nombreDocumento);
                Object   filename = (Object)wordFile.FullName;

                Microsoft.Office.Interop.Word.Document doc = word.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);
                doc.Activate();

                object outputFileName = wordFile.FullName.Replace(".docx", ".pdf");
                object fileFormat     = WdSaveFormat.wdFormatPDF;

                // Save document into PDF Format
                doc.SaveAs(ref outputFileName,
                           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);

                object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
                ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing);
                doc = null;


                ((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing);
                word = null;
                Process.Start(outputFileName.ToString());
                return(true);
            }
            catch (Exception ex)
            {
                return(true);

                throw new Exception(ex.Message);
            }
        }
Exemple #3
0
        public ProcWord()
        {
            app = new Word.Application();
            //app.Visible = true;
            //app.DefaultSaveFormat = "";  //Word 文档 ""

            object template     = Missing;
            object newTemplate  = Missing;
            object documentType = Missing;

            document = app.Documents.Add(ref template, ref newTemplate,
                                         ref documentType, ref Visible);
            document.Activate();

            //app.ShowStartupDialog = false;
        }
Exemple #4
0
        private static void CrearPDF()
        {
            try
            {
                CrearWord();
                Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();

                object oMissing = System.Reflection.Missing.Value;
                word.Visible        = false;
                word.ScreenUpdating = false;

                FileInfo wordFile = new FileInfo("C:\\Users\\juanc\\projects\\Portafolio\\Escritorio\\S_ArriendoDepartamento\\Arriendo.Test\\plantilla\\WordGenerado.docx");
                Object   filename = (Object)wordFile.FullName;

                Microsoft.Office.Interop.Word.Document doc = word.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);
                doc.Activate();

                object outputFileName = wordFile.FullName.Replace(".docx", ".pdf");
                object fileFormat     = WdSaveFormat.wdFormatPDF;

                // Save document into PDF Format
                doc.SaveAs(ref outputFileName,
                           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);

                object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
                ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing);
                doc = null;


                ((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing);
                word = null;
                Process.Start(outputFileName.ToString());
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Exemple #5
0
        /// <summary>
        /// 通过Word模板标签生成word
        /// </summary>
        /// <param name="templateFileName">模板文件路径</param>
        /// <param name="exportFileName">新文件路径</param>
        /// <param name="info">需要导出的信息键值对,key为模板标签名,value为需要导出的信息</param>
        /// <param name="startPageIndex">word页数</param>
        public static bool ExportWord(string templateFileName, string exportFileName, Dictionary <string, WordExportInfo> info)
        {
            //生成documnet对象
            Word._Document doc = new Microsoft.Office.Interop.Word.Document();
            //生成word程序对象
            Word.Application app = new Word.Application();
            //模板文件
            //模板文件拷贝到新文件
            File.Copy(templateFileName, exportFileName);

            object Obj_FileName = exportFileName;
            object Visible      = false;
            object ReadOnly     = false;
            object missing      = System.Reflection.Missing.Value;

            try
            {
                //打开文件
                doc = app.Documents.Open(ref Obj_FileName, ref missing, ref ReadOnly, ref missing,
                                         ref missing, ref missing, ref missing, ref missing,
                                         ref missing, ref missing, ref missing, ref Visible,
                                         ref missing, ref missing, ref missing,
                                         ref missing);
                doc.Activate();

                #region 将文本或图片插入到模板中对应标签
                if (info.Count > 0)
                {
                    object what = Word.WdGoToItem.wdGoToBookmark;
                    object WordMarkName;
                    foreach (var item in info)
                    {
                        WordMarkName = item.Key;
                        //光标转到书签的位置
                        doc.ActiveWindow.Selection.GoTo(ref what, ref missing, ref missing, ref WordMarkName);
                        //插入的内容,插入位置是word模板中书签定位的位置
                        if (item.Value.ImagePath == null)
                        {
                            doc.ActiveWindow.Selection.TypeText(item.Value.Text);
                        }
                        else
                        {
                            //注意此处需要对应模板文件的图片处的书签
                            object   oStart           = doc.Bookmarks.get_Item("Image");
                            Object   linkToFile       = false;                                    //图片是否为外部链接
                            Object   saveWithDocument = true;                                     //图片是否随文档一起保存
                            object   range            = doc.Bookmarks.get_Item(ref oStart).Range; //图片插入位置
                            FileInfo filePhotoInfo    = new FileInfo(item.Value.ToString());
                            if (filePhotoInfo.Exists == false)
                            {
                                break;
                            }
                            doc.InlineShapes.AddPicture(item.Value.ImagePath, ref linkToFile, ref saveWithDocument, ref range);
                            doc.Application.ActiveDocument.InlineShapes[1].Width  = 60;  //设置图片宽度
                            doc.Application.ActiveDocument.InlineShapes[1].Height = 70;  //设置图片高度
                        }
                        //设置当前定位书签位置插入内容的格式,建议直接在模板中设置
                        //doc.ActiveWindow.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    }
                }
                #endregion

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
            finally
            {
                //输出完毕后关闭doc对象
                object IsSave = true;
                doc.Close(ref IsSave, ref missing, ref missing);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
                doc = null;
            }
        }
Exemple #6
0
        private void createWords()
        {
            int filesToCreateTemp = frm1.filesToCreate;             // avoid change in '#files to be created' during runtime

            try
            {
                string workingDir = frm1.workingDirectory + "officeSimulation_word\\";
                System.IO.Directory.CreateDirectory(workingDir);
                int    documentCount    = 0;
                string wordFileNameDate = frm1.wordFileName + DateTime.Now.ToString("dd-MM-yyyy_HH-mm");
                string wordFileNameDateFinal;

                // ~~~~~~~~~~~~~~~~~~~~~~~~~~ Word instance ~~~~~~~~~~~~~~~~~~~~~~~~~
                var winword = new Microsoft.Office.Interop.Word.Application();
                winword.ShowAnimation = false;
                winword.Visible       = false;
                object winWordMissing = System.Reflection.Missing.Value;
                // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

                while (documentCount < filesToCreateTemp)
                {
                    wordFileNameDateFinal = wordFileNameDate + "_" + documentCount;
                    // ~~~~~~ create word files (vary formatting)
                    try
                    {
                        if (frm1.varyFormatting)
                        {
                            //Selecting random lorem text length
                            Random r       = new Random(DateTime.Now.Millisecond);
                            int    rLorem1 = r.Next(0, 5);
                            int    rLorem2 = r.Next(0, 5);
                            int    rLorem3 = r.Next(0, 5);
                            int    rLorem4 = r.Next(0, 2);
                            int    rLorem5 = r.Next(0, 2);

                            //Create a new document
                            Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref winWordMissing, ref winWordMissing, ref winWordMissing, ref winWordMissing);

                            //Add header into the document
                            foreach (Microsoft.Office.Interop.Word.Section section in document.Sections)
                            {
                                //Get the header range and add the header details.
                                Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                                headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage);
                                headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                                headerRange.Font.ColorIndex           = Microsoft.Office.Interop.Word.WdColorIndex.wdBlue;
                                headerRange.Font.Size = 10;
                                headerRange.Text      = frm1.lorems[rLorem4];
                            }

                            //Add the footers into the document
                            foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections)
                            {
                                //Get the footer range and add the footer details.
                                Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                                footerRange.Font.ColorIndex           = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkRed;
                                footerRange.Font.Size                 = 10;
                                footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                                footerRange.Text = frm1.lorems[rLorem5];
                            }

                            //adding text to document
                            document.Content.SetRange(0, 0);
                            document.Content.Text = frm1.lorems[rLorem1] + "\r\n";
                            // adding some delay
                            if (frm1.addDelay)
                            {
                                Thread.Sleep(frm1.addDelaySec * 1000);
                            }
                            document.Content.Text = frm1.lorems[rLorem2] + "\r\n";
                            document.Content.Text = frm1.lorems[rLorem3];

                            //Add paragraph with Heading 1 style
                            Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref winWordMissing);
                            object styleHeading1 = "Heading 1";
                            para1.Range.set_Style(ref styleHeading1);
                            para1.Range.Text = frm1.lorems[rLorem1];
                            para1.Range.InsertParagraphAfter();

                            //Add paragraph with Heading 2 style
                            Microsoft.Office.Interop.Word.Paragraph para2 = document.Content.Paragraphs.Add(ref winWordMissing);
                            object styleHeading2 = "Heading 2";
                            para2.Range.set_Style(ref styleHeading2);
                            para2.Range.Text = frm1.lorems[rLorem2];
                            para2.Range.InsertParagraphAfter();

                            //Save the document
                            object filename = workingDir + wordFileNameDateFinal + ".docx";
                            //object filename = filePath + "\\" + fileName + ".docx";
                            document.SaveAs2(ref filename);
                            // Keeping a list of files created
                            frm1.listOfWordFiles.Add(filename.ToString());
                            document.Close(ref winWordMissing, ref winWordMissing, ref winWordMissing);
                            document = null;
                            if (document != null)
                            {
                                Marshal.ReleaseComObject(document);
                            }
                        }
                        else // ~~~~~~ create word files (NO formatting)
                        {
                            //adding text to document
                            Random r       = new Random(DateTime.Now.Millisecond);
                            int    rLorem1 = r.Next(0, 5);
                            int    rLorem2 = r.Next(0, 5);
                            int    rLorem3 = r.Next(0, 5);

                            //Create a new document
                            Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref winWordMissing, ref winWordMissing, ref winWordMissing, ref winWordMissing);

                            document.Content.SetRange(0, 0);
                            document.Content.Text = frm1.lorems[rLorem1] + "\r\n";
                            // adding some delay
                            if (frm1.addDelay)
                            {
                                Thread.Sleep(frm1.addDelaySec * 1000);
                            }
                            document.Content.Text = frm1.lorems[rLorem2] + "\r\n";
                            document.Content.Text = frm1.lorems[rLorem3];

                            //Save the document
                            object filename = workingDir + wordFileNameDateFinal + ".docx";
                            //object filename = filePath + "\\" + fileName + ".docx";
                            document.SaveAs2(ref filename);
                            // Keeping a list of files created
                            frm1.listOfWordFiles.Add(filename.ToString());
                            document.Close(ref winWordMissing, ref winWordMissing, ref winWordMissing);
                            document = null;
                            if (document != null)
                            {
                                Marshal.ReleaseComObject(document);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error creating Word file!");
                        Console.WriteLine(ex.Message);
                    }
                    documentCount++;
                }

                // ~~~~~~ copy some of the documents
                int i2 = 0;
                while (i2 < filesToCreateTemp)
                {
                    if (i2 % 4 == 0)
                    {
                        string filePathNoExtension = frm1.listOfWordFiles[i2].Substring(0, frm1.listOfWordFiles[i2].Length - 5);
                        string newFilePathCopy     = filePathNoExtension + "_copy" + ".docx";
                        try
                        {
                            var originalDocument = winword.Documents.Open(frm1.listOfWordFiles[i2]); // Open original document

                            originalDocument.ActiveWindow.Selection.WholeStory();                    // Select all in original document
                            var originalText = originalDocument.ActiveWindow.Selection;              // Copy everything to the variable

                            var newDocument          = new Word.Document();                          // Create new Word document
                            newDocument.Range().Text = originalText.Text;                            // Pasete everything from the variable
                            newDocument.SaveAs(newFilePathCopy);                                     // maybe SaveAs2??                  // Save the new document

                            originalDocument.Close(false);
                            newDocument.Close();

                            if (originalDocument != null)
                            {
                                Marshal.ReleaseComObject(originalDocument);
                            }
                            if (newDocument != null)
                            {
                                Marshal.ReleaseComObject(newDocument);
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error coping documents");
                            Console.WriteLine(ex.Message);
                        }
                    }
                    i2++;
                }

                // ~~~~~~ find-replace in some documents
                int i3 = 0;
                while (i3 < filesToCreateTemp)
                {
                    if (i3 % 3 == 0)
                    {
                        try
                        {
                            Microsoft.Office.Interop.Word.Document aDoc = winword.Documents.Open(frm1.listOfWordFiles[i3], ReadOnly: false, Visible: false);
                            aDoc.Activate();

                            winword.Selection.Find.Execute(frm1.textToSearch1, false, true, false, false, false, true, 1, false, frm1.textToReplace1, 2, false, false, false, false);
                            winword.Selection.Find.Execute(frm1.textToSearch2, false, true, false, false, false, true, 1, false, frm1.textToReplace2, 2, false, false, false, false);

                            aDoc.SaveAs2();

                            aDoc.Close(ref winWordMissing, ref winWordMissing, ref winWordMissing);
                            aDoc = null;
                            if (aDoc != null)
                            {
                                Marshal.ReleaseComObject(aDoc);
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error in find-replace");
                            Console.WriteLine(ex.Message);
                        }
                    }
                    i3++;
                }

                // ~~~~~~~~~~~~~~~~~~~~ Terminating Word instance ~~~~~~~~~~~~~~~~~~~
                winword.Quit(ref winWordMissing, ref winWordMissing, ref winWordMissing);
                winword.Quit();
                if (winword != null)
                {
                    Marshal.ReleaseComObject(winword);
                }
                winword        = null;
                winWordMissing = null;
                // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            }
            catch (Exception ex)
            {
                Console.WriteLine("backGroundWorker WordCreate Error");
                Console.WriteLine(ex.Message);
            }

            tskCreateWordsRunning = false;
            Console.WriteLine();
            Console.WriteLine("runEverything(): createWords() -> DONE");
        }
        public WordDocumentParser(string inputFilePath, EquationToLaTeXConverter form)
        {
            this.form = form;
            char[]   separator   = { '\\' };
            string[] directories = inputFilePath.Split(separator, StringSplitOptions.RemoveEmptyEntries);
            string   dir         = "";

            for (int i = 0; i < directories.Length - 1; i++)
            {
                dir += directories[i] + '\\';
            }
            this.inputFileDir  = dir;
            this.inputFileName = directories[directories.Length - 1];
            Console.WriteLine(inputFileName);
            this.app = new Word.Application();



            if (form.checkBox1.Checked == true)
            {
                this.app.Visible = true;
                Console.WriteLine("pokazuje");
                this.visible = true;
            }
            if (form.checkBox1.Checked == false)
            {
                this.app.Visible = false;
                //this.app.DisplayAlerts = 0;
                Console.WriteLine("nie pokazuje");
                this.visible = false;
            }



            this.docOpen = app.Documents.Open(inputFilePath, Visible: visible);



            this.myRange = docOpen.Range();

            packageDictionary.Add("AMS", @"\usepackage{amssymb}");
            packageDictionary.Add("INT", @"\usepackage{esint}");
            packageDictionary.Add("FDS", @"\usepackage{fdsymbol}");
            packageDictionary.Add("STX", @"\usepackage{stix}");
            packageDictionary.Add("TEX", @"\usepackage{textcomp}");
            packageDictionary.Add("GEN", @"\usepackage{gensymb}");
            packageDictionary.Add("COL", @"\usepackage{colonequals}");
            packageDictionary.Add("FRM", @"\usepackage{framed}");

            object isVisible = true;

            File.SetAttributes(inputFilePath, FileAttributes.Normal);
            this.second_file_path = this.inputFileDir + this.inputFileName.Substring(0, inputFileName.IndexOf('.')) + @"_converted.docx";
            docOpen.Activate();

            /*if(form.checkBox2.Checked == false)
             * {
             *  myRange.Copy();
             *  docOpen.Close();
             *
             *  this.docOpen = app.Documents.Open(second_file_path, Visible: visible, ReadOnly: false);
             *  docOpen.Range().Paste();
             *  docOpen.SaveAs();
             *  docOpen.Close();
             *
             *
             *  this.docOpen = app.Documents.Open(second_file_path, Visible: visible);
             *  this.myRange = docOpen.Range();
             * }*/
        }