Exemplo n.º 1
1
        public static bool WordToPDF(string sourcePath, string targetPath)
        {
            bool result = false;
            Microsoft.Office.Interop.Word.WdExportFormat exportFormat = Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF;
            Microsoft.Office.Interop.Word.Application application = null;

            Microsoft.Office.Interop.Word.Document document = null;
            object unknow = System.Type.Missing;
            application = new Microsoft.Office.Interop.Word.Application();
            application.Visible = false;
            document = application.Documents.Open(sourcePath);
            document.SaveAs();
            document.ExportAsFixedFormat(targetPath, exportFormat, false);
            //document.ExportAsFixedFormat(targetPath, exportFormat);
            result = true;

            //application.Documents.Close(ref unknow, ref unknow, ref unknow);
            document.Close(ref unknow, ref unknow, ref unknow);
            document = null;
            application.Quit();
            //application.Quit(ref unknow, ref unknow, ref unknow);
            application = null;

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();

            return result;
        }
Exemplo n.º 2
0
 private void button1_Click(object sender, EventArgs e)
 {
     //закриває всі відкриті ворди
     String[] s = textBox1.Text.Split(new[] {"\r\n"}, StringSplitOptions.RemoveEmptyEntries);
     int step = (int) 100/s.Length;
     for (int i = 0; i < s.Length; i++)
     {
         try
         {
             Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
             var wordDocument = appWord.Documents.Open(s[i]);
             s[i] = s[i].Replace(".docx", ".pdf");
             s[i] = s[i].Replace(".doc", ".pdf");
             wordDocument.ExportAsFixedFormat(s[i], WdExportFormat.wdExportFormatPDF);
             wordDocument.Close();
             appWord.Quit();
         }
         catch{}
         progressBar1.Value += step;
     }
     progressBar1.Value = 100;
     MessageBox.Show("Готово", "Звіт про виконання", MessageBoxButtons.OK, MessageBoxIcon.Information);
     textBox1.Clear();
     progressBar1.Value = 0;
 }
Exemplo n.º 3
0
        // Usage:
        // using Word = Microsoft.Office.Interop.Word;
        // Action<Word.Application> f = w =>
        // {
        //      var d = w.Documents.Open(@"C:\Foo.docx");
        // };
        // Word1.With(f);
        internal static void With(Action<Word.Application> f)
        {
            Word.Application app = null;

            try
            {
                app = new Word.Application
                {
                    DisplayAlerts = Word.WdAlertLevel.wdAlertsNone,
                    Visible = true
                };
                f(app);
            }
            finally
            {
                if (app != null)
                {
                    if (0 < app.Documents.Count)
                    {
                        // Unlike Excel, Close(...) makes an error when app.Documents.Count == 0
                        // Unlike Excel, Close(...) without wdDoNotSaveChanges shows a prompt for a dirty document.
                        app.Documents.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
                    }

                    app.Quit();

                    // Both of the following are needed in some cases
                    // while none of them are needed in other cases.
                    Marshal.FinalReleaseComObject(app);
                    GC.Collect();
                }
            }
        }
    public static void Print2(string wordfile, string printer = null)
    {
        oWord.Application wordApp = new oWord.Application();
        wordApp.Visible = false;

        wordApp.Documents.Open(wordfile);
        wordApp.DisplayAlerts = oWord.WdAlertLevel.wdAlertsNone;

        System.Drawing.Printing.PrinterSettings settings = new System.Drawing.Printing.PrinterSettings();

        if (printer == null) // print to all installed printers
        {
            foreach (string p in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
            {
                try
                {
                    settings.PrinterName = p;
                    wordApp.ActiveDocument.PrintOut(false);
                }
                catch (Exception ex)
                {
                    Logger.LogException(ex, true);
                }
            }
        }
        else
        {
            settings.PrinterName = printer;
            wordApp.ActiveDocument.PrintOut(false);
        }

        wordApp.Quit(oWord.WdSaveOptions.wdDoNotSaveChanges);
    }
Exemplo n.º 5
0
        public void PasteTest()
        {
            var fileName = TestFileNames.SourceFile;
            var word = new Application { Visible = false };
            var doc = word.Documents.Open(fileName);

            try
            {
                // ReSharper disable UseIndexedProperty
                var range = doc.Bookmarks.get_Item("Bibliography").Range;
                // ReSharper restore UseIndexedProperty

                var html = Utils.GetHtmlClipboardText("Hello <i>World!</i>");
                Clipboard.SetText(html, TextDataFormat.Html);
                range.PasteSpecial(DataType: WdPasteDataType.wdPasteHTML);

                var destFileName = Path.Combine(Path.GetDirectoryName(fileName),
                    Path.GetFileNameWithoutExtension(fileName) + "-updated" + Path.GetExtension(fileName));
                word.ActiveDocument.SaveAs(destFileName);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.GetMessage());
            }
            finally
            {
                word.Quit(false);
            }
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            try
            {
                FileInfo file = new FileInfo(@args[0]);

                if (file.Extension.ToLower() == ".doc" || file.Extension.ToLower() == ".xml" || file.Extension.ToLower() == ".wml")
                {
                    Word._Application application = new Word.Application();
                    object fileformat = Word.WdSaveFormat.wdFormatXMLDocument;

                    object filename = file.FullName;
                    object newfilename = Path.ChangeExtension(file.FullName, ".docx");
                    Word._Document document = application.Documents.Open(filename);

                    document.Convert();
                    document.SaveAs(newfilename, fileformat);
                    document.Close();
                    document = null;

                    application.Quit();
                    application = null;
                }
            }
            catch (IndexOutOfRangeException e)
            {
                Console.WriteLine("Missing parameter: IndexOutOfRangeException {0}", e);
            }
        }
Exemplo n.º 7
0
        private void MenuItem_Click_SaveDogovor(object sender, RoutedEventArgs e)
        {
            Word.Application word     = null;
            Word.Document    document = null;

            try
            {
                word = new Word.Application();
                var template = (object)(Environment.CurrentDirectory + "\\template_dogovor.dotx");
                document = word.Documents.Add(ref template, ref oMissing, ref oMissing, ref oMissing);

                SetTemplate(document);

                var date         = $"{DateTime.Now.Day}.{DateTime.Now.Month}.{DateTime.Now.Year}";
                var time         = DateTime.Now.ToLongTimeString().Replace(":", ".");
                var documentName = Environment.CurrentDirectory + $"\\Документ от {date} {time}.docx";
                SaveToDisk(document, documentName);
                MessageBox.Show($"Документ создан под именем {documentName}");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Save Error");
            }
            finally
            {
                document?.Close(ref oMissing, ref oMissing, ref oMissing);
                word?.Quit(ref oMissing, ref oMissing, ref oMissing);
            }
        }
Exemplo n.º 8
0
    public static void CompareInWord(string fullpath, string newFullpath, string saveName, string saveDir, string author, bool save = false) {
      Object missing = Type.Missing;
      try {
        var wordapp = new Microsoft.Office.Interop.Word.Application();
        try {
          var doc = wordapp.Documents.Open(fullpath, ReadOnly: true);
          doc.Compare(newFullpath, author ?? missing);
          doc.Close(WdSaveOptions.wdDoNotSaveChanges); // Close the original document
          var dialog = wordapp.Dialogs[WdWordDialog.wdDialogFileSummaryInfo];
          // Pre-set the save destination by setting the Title in the save dialog.
          // This must be done through reflection, since "dynamic" is only supported in .NET 4
          dialog.GetType().InvokeMember("Title", BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty,
                                        null, dialog, new object[] {saveName});
          dialog.Execute();
          wordapp.ChangeFileOpenDirectory(saveDir);
          if (!save) {
            wordapp.ActiveDocument.Saved = true;
          }

          wordapp.Visible = true;
          wordapp.Activate();

          // Simple hack to bring the window to the front.
          wordapp.ActiveWindow.WindowState = WdWindowState.wdWindowStateMinimize;
          wordapp.ActiveWindow.WindowState = WdWindowState.wdWindowStateMaximize;
        } catch (Exception ex) {
          Logger.LogException(ex);
          ShowMessageBox("Word could not open these documents. Please edit the file manually.", "Error");
          wordapp.Quit();
        }
      } catch (Exception ex) {
        Logger.LogException(ex);
        ShowMessageBox("Could not start Microsoft Word. Office 2003 or higher is required.", "Could not start Word");
      }
    }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            FileInfo file = new FileInfo(@args[0]);

            if (file.Extension.ToLower() == ".docx")
            {
                Console.WriteLine("Starting file name extraction...");

                //Set the Word Application Window Title
                string wordAppId = "" + DateTime.Now.Ticks;

                Word.Application word = new Word.Application();
                word.Application.Caption = wordAppId;
                word.Application.Visible = true;
                int processId = GetProcessIdByWindowTitle(wordAppId);
                word.Application.Visible = false;

                try
                {
                    object filename = file.FullName;
                    Word._Document document = word.Documents.OpenNoRepairDialog(filename);
                    Console.WriteLine("Extracting file names from document '{0}'.", file);

                    //Console.WriteLine("Document has {0} shapes.", document.InlineShapes.Count);
                    if (document.InlineShapes.Count > 0)
                    {
                        foreach (Word.InlineShape shape in document.InlineShapes)
                        {
                            if (shape.Type == Word.WdInlineShapeType.wdInlineShapeEmbeddedOLEObject)
                            {
                                Console.WriteLine("Found file name: {0}", shape.OLEFormat.IconLabel);
                            }
                        }
                    }

                    document.Close();
                    document = null;

                    word.Quit();
                    word = null;
                    Console.WriteLine("Success, quitting Word.");
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error ocurred: {0}", e);
                }
                finally
                {
                    // Terminate Winword instance by PID.
                    Console.WriteLine("Terminating Winword process with the Windowtitle '{0}' and the Application ID: '{1}'.", wordAppId, processId);
                    Process process = Process.GetProcessById(processId);
                    process.Kill();
                }
            }
            else
            {
                Console.WriteLine("Only DOCX files possible.");
            }
        }
Exemplo n.º 10
0
        private void Button_GetDiploma_Click(object sender, RoutedEventArgs e)
        {
            Word._Application application = null;
            Word._Document    document    = null;
            Object            missingObj  = Missing.Value;
            Object            falseObj    = false;

            try
            {
                string         richText = new TextRange(StudentsTextBox.Document.ContentStart, StudentsTextBox.Document.ContentEnd).Text;
                List <Student> students = JsonConvert.DeserializeObject <List <Student> >(richText);

                //создаем обьект приложения word
                application = new Word.Application();
                // создаем путь к файлу
                Object templatePathObj = AppDomain.CurrentDomain.BaseDirectory + @"Diploma.dotx";

                int i = 1;
                foreach (var student in students)
                {
                    // если вылетим на этом этапе, приложение останется открытым
                    document = application.Documents.Add(ref templatePathObj, ref missingObj, ref missingObj, ref missingObj);

                    StringReplace(document, "%NAME%", student.Name);
                    StringReplace(document, "%STATUS%", student.Status);
                    StringReplace(document, "%GraduationDate%", student.GraduationDate.ToString("dd.MM.yyyy"));
                    StringReplace(document, "%GraduationPlace%", student.GraduationPlace);
                    Object pathToSaveObj = AppDomain.CurrentDomain.BaseDirectory + $@"student{i.ToString()}.docx";
                    document.SaveAs(ref pathToSaveObj, Word.WdSaveFormat.wdFormatDocumentDefault, ref missingObj,
                                    ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj,
                                    ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj,
                                    ref missingObj);
                    i++;


                    document.Close(ref falseObj, ref missingObj, ref missingObj);
                }

                application.Quit(ref missingObj, ref missingObj, ref missingObj);

                document    = null;
                application = null;
                StudentsTextBox.Document.Blocks.Clear();
                StudentsTextBox.AppendText("Done");
            }
            catch (Exception exception)
            {
                document?.Close(ref falseObj, ref missingObj, ref missingObj);
                application?.Quit(ref missingObj, ref missingObj, ref missingObj);
                document    = null;
                application = null;
                StudentsTextBox.Document.Blocks.Clear();
                StudentsTextBox.AppendText(exception.Message);
            }
        }
Exemplo n.º 11
0
        public void GetComDisplayNames()
        {
            var wordApp = new Word.Application();

            var docs = wordApp.Documents;

            var names =Impromptu.GetMemberNames(docs);

            Assert.AreEqual(4,names.Count());

            wordApp.Quit();
        }
Exemplo n.º 12
0
        public void GetComVar()
        {
            var wordApp = new Word.Application();

            var docs = wordApp.Documents;

            var count = Impromptu.InvokeGet(docs,"Count");

            Assert.AreEqual(0,count);

            wordApp.Quit();
        }
Exemplo n.º 13
0
        private static void ConvertPPTToDoc(Options options)
        {
            PPT.ApplicationClass pptApp = new PPT.ApplicationClass();
            pptApp.DisplayAlerts = PPT.PpAlertLevel.ppAlertsNone;

            // make copy so we don't change the original
            string tempPptFilePath = System.IO.Path.Combine(System.IO.Path.GetTempFileName());
            System.IO.File.Copy(options.InPath, tempPptFilePath, true);

            PPT.Presentation pptPresentation = pptApp.Presentations.Open(new FileInfo(tempPptFilePath).FullName, WithWindow: Microsoft.Office.Core.MsoTriState.msoFalse);

            DOC.Application docApp = new DOC.Application();
            var doc = docApp.Documents.Add();

            Console.WriteLine("Converting powerpoint to word");
            ProgressBar progress = new ProgressBar();

            try
            {
                string currentTitle = "";
                string currentSubTitle = "";

                for (int slideNr = 1; slideNr <= pptPresentation.Slides.Count; slideNr++)
                {
                    progress.Report(slideNr / (float)pptPresentation.Slides.Count, "Slide " + slideNr + "/" + pptPresentation.Slides.Count);
                    CopySlide(pptPresentation, doc, options, ref currentTitle, ref currentSubTitle, slideNr);
                }
            }
            finally
            {
                pptPresentation.Close();

                if (System.IO.File.Exists(tempPptFilePath))
                    System.IO.File.Delete(tempPptFilePath);
            }
            //docApp.Visible = true;
            doc.SaveAs(new FileInfo(options.Outpath).FullName);
            doc.Close();

            progress.Dispose();

            Console.WriteLine("Conversion complete, word file written to " + new FileInfo(options.Outpath).FullName);

            try
            {
                docApp.Quit();
                pptApp.Quit();
            }
            catch (Exception)
            {
            }
        }
Exemplo n.º 14
0
        public static void CreateNewDocument(string path, string[] content)
        {
            lock (interopProcessLockObject)
            {
                using (var comHelper = new COMObjectsHelper())
                {
                    Word.Application wordApp = null;
                    try
                    {
                        var isVisible = false;

                        wordApp         = comHelper.Register(() => new Word.Application());
                        wordApp.Visible = isVisible;

                        var documents = comHelper.Register(() => wordApp.Documents);

                        object readOnly     = false;
                        object isAppVisible = isVisible;
                        object documentType = Word.WdNewDocumentType.wdNewBlankDocument;

                        var document   = comHelper.Register(() => documents.Add(DocumentType: ref documentType, Visible: ref isAppVisible));
                        var docContent = comHelper.Register(() => document.Content);
                        docContent.Text = string.Join(Environment.NewLine, content);

                        var paragraphs    = comHelper.Register(() => document.Paragraphs);
                        var lastParagraph = comHelper.Register(() => paragraphs.Last);
                        var range         = comHelper.Register(() => lastParagraph.Range);
                        if (range.Text.Trim() == string.Empty)
                        {
                            range.Select();
                            var selection = comHelper.Register(() => wordApp.Selection);
                            selection.Delete();
                        }

                        object savePath = path.Clone();
                        document.SaveAs2(ref savePath);
                        document.Close();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Document creation failed with error: {ex.Message}. Exception: {ex}.");
                        throw;
                    }
                    finally
                    {
                        // Note: We always should manually quit from application,
                        // because Release() only decreases references counter.
                        wordApp?.Quit();
                    }
                }
            }
        }
Exemplo n.º 15
0
        private static void CreateDoc(DiplomProject work, HttpResponseBase response)
        {
            Microsoft.Office.Interop.Word.Application app = null;
            string tempfileName = null;
            object falseValue = false;
            var missing = Type.Missing;
            object save = WdSaveOptions.wdSaveChanges;
            object original = WdOriginalFormat.wdOriginalDocumentFormat;
            try
            {
                var url = string.Format("{0}.Export.tasklist.doc", Assembly.GetExecutingAssembly().GetName().Name);
                using (var templateStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(url))
                {
                    object tempdot = tempfileName = SaveToTemp(templateStream);

                    app = new Microsoft.Office.Interop.Word.Application();
                    var doc = app.Documents.Open(ref tempdot, 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);

                    if (doc == null)
                    {
                        throw new ApplicationException("Unable to open the word template! Try to add Launch and Activation permissions for Word DCOM component for current IIS user (IIS_IUSRS for example). Or set Identity to Interactive User.");
                    }

                    FillDoc(doc, work);
                    doc.Save();
                    doc.Close(ref save, ref original, ref falseValue);

                    SaveToResponse(tempfileName, response);
                }
            }
            finally
            {
                if (app != null)
                {
                    object dontSave = WdSaveOptions.wdDoNotSaveChanges;
                    app.Quit(ref dontSave, ref original, ref falseValue);
                }

                if (tempfileName != null)
                {
                    try
                    {
                        File.Delete(tempfileName);
                    }
                    catch (Exception)
                    {
                        //todo: log
                    }
                }
            }
        }
Exemplo n.º 16
0
        public static void CloneDocument(string FileName, string NewFileName, ProcessDocument ProcessDocumentIn)
        {
            try
            {

                File.Copy(FileName, NewFileName);

                object o = Missing.Value;
                object oFalse = false;
                object oTrue = true;

                Word._Application app = null;
                Word.Documents docs = null;
                Word.Document doc = null;

                object path = NewFileName;

                try
                {
                    app = new Word.Application();
                    app.Visible = false;
                    app.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;

                    docs = app.Documents;
                    doc = docs.Open(ref path, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o);
                    doc.Activate();

                    ProcessDocumentIn(ref doc);

                    doc.Save();
                    ((Word._Document)doc).Close(ref o, ref o, ref o);
                    app.Quit(ref o, ref o, ref o);
                }
                finally
                {
                    if (doc != null)
                        Marshal.FinalReleaseComObject(doc);

                    if (docs != null)
                        Marshal.FinalReleaseComObject(docs);

                    if (app != null)
                        Marshal.FinalReleaseComObject(app);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 17
0
        private void btnConvert_Click(object sender, EventArgs e)
        {
            List<string> list = new List<string>();
            SearchFiles(tbDirectory.Text, tbPostFix.Text, list);

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

            try
            {
                foreach (string fname in list)
                {
                    DoConvert(fname);
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                Word.Quit(ref Nothing, ref Nothing, ref Nothing);
                return;
            }

            Word.Quit(ref Nothing, ref Nothing, ref Nothing);
            MessageBox.Show("convert finish");
        }
Exemplo n.º 18
0
        private void buttonShow_Click(object sender, EventArgs e)
        {
            var app = new Word.Application();
            Word.Document doc = null;

            String path = System.Reflection.Assembly.GetEntryAssembly().Location;
            path = path.Remove(path.LastIndexOf('\\'), path.Length - path.LastIndexOf('\\')) + "\\Reports\\test.doc";

            // C# 4.0
            doc = app.Documents.Add(path);

            doc.Tables[1].Rows[1].Cells[2].Range.Text = _patient.Surname + " " + _patient.Name + " " + _patient.Patronymic + ", " + Data.DataPatient.GetDate(_patient.Birthday);
            doc.Tables[1].Rows[2].Cells[2].Range.Text = Data.DataPatient.GetDate(_patient.MilitaryCard.RecData);
            doc.Tables[1].Rows[2].Cells[4].Range.Text = _patient.StudyCard.StudyType;
            doc.Tables[1].Rows[2].Cells[6].Range.Text = "Not working yet";
            doc.Tables[1].Rows[3].Cells[1].Range.Text = _patient.MilitaryCard.RecruitPlace;
            foreach (Test test in _patient.Tests)
                doc.Tables[1].Rows[4].Cells[2].Range.Text += test.TestType + " , Дата: " + Data.DataPatient.GetDate(test.TestDate);
            doc.Tables[1].Rows[5].Cells[2].Range.Text = _patient.PsyCard.NPS;
            doc.Tables[1].Rows[6].Cells[2].Range.Text = _patient.PsyCard.NMB;
            doc.Tables[1].Rows[7].Cells[2].Range.Text = _patient.PsyCard.SuicideRisk;
            doc.Tables[1].Rows[8].Cells[2].Range.Text = _patient.PsyCard.Logic;
            doc.Tables[1].Rows[9].Cells[2].Range.Text = _patient.PsyCard.Memory;
            doc.Tables[1].Rows[10].Cells[2].Range.Text = _patient.PsyCard.Attention;
            doc.Tables[1].Rows[11].Cells[2].Range.Text = _patient.PsyCard.GCA;
            doc.Tables[1].Rows[12].Cells[2].Range.Text = _patient.PsyCard.CommSkill;
            doc.Tables[1].Rows[13].Cells[2].Range.Text = _patient.PsyCard.MoralNormativity;
            doc.Tables[1].Rows[14].Cells[2].Range.Text = _patient.PsyCard.ProfFitness;
            doc.Tables[1].Rows[15].Cells[2].Range.Text = _patient.PsyCard.ConflictTend;
            doc.Tables[1].Rows[16].Cells[2].Range.Text = _patient.PsyCard.ConflictOrient;
            doc.Tables[1].Rows[17].Cells[2].Range.Text = _patient.MedCard.HealthInfo;
            doc.Tables[1].Rows[18].Cells[2].Range.Text = _patient.MedCard.Illnesses.Count == 0 ? "Нет" : "Есть";
            doc.Tables[1].Rows[19].Cells[2].Range.Text = _patient.MedCard.BrainInjury == true ? "Есть" : "Нет";
            doc.Tables[1].Rows[21].Cells[1].Range.Text = _patient.PsyCard.PersonalityType.Name;
            doc.Tables[1].Rows[21].Cells[1].Range.Text += _patient.PsyCard.PersonalityType.DescriptionType;

            WordApp.FindAndReplace(app, "<date>", DateTime.Today.ToShortDateString());

            //doc.InlineShapes.AddChart(Microsoft.Office.Interop.Excel.XlChartType.xlPie, null);

            //Word.ChartData chartData = wdChart.ChartData;

            doc.Save();

            app.Quit();
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(app);
        }
Exemplo n.º 19
0
Arquivo: Form1.cs Projeto: GAHE/mo
        private void button1_Click(object sender, EventArgs e)
        {
            //*************************************** *******
            //来自博客http://blog.csdn.net/fujie724
            //**********************************************
            object oMissing = System.Reflection.Missing.Value;
            //创建一个Word应用程序实例
            Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application();
            //设置为不可见
            oWord.Visible = false;
           
            //模板文件地址,这里假设在X盘根目录
            object oTemplate = "D://template.dot";
            //以模板为基础生成文档
            Microsoft.Office.Interop.Word._Document oDoc = oWord.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);
            //声明书签数组
            object[] oBookMark = new object[5];
            //赋值书签名
            oBookMark[0] = "beizhu";
            oBookMark[1] = "name";
            oBookMark[2] = "sex";
            oBookMark[3] = "birthday";
            oBookMark[4] = "hometown";
            //赋值任意数据到书签的位置
            oDoc.Bookmarks.get_Item(ref oBookMark[0]).Range.Text = "使用模板实现Word生成";
            oDoc.Bookmarks.get_Item(ref oBookMark[1]).Range.Text = "李四";
            oDoc.Bookmarks.get_Item(ref oBookMark[2]).Range.Text = "女";
            oDoc.Bookmarks.get_Item(ref oBookMark[3]).Range.Text = "1987.06.07";
            oDoc.Bookmarks.get_Item(ref oBookMark[4]).Range.Text = "贺州";
            //弹出保存文件对话框,保存生成的Word
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Word Document(*.doc)|*.doc";
            sfd.DefaultExt = "Word Document(*.doc)|*.doc";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                object filename = sfd.FileName;

                oDoc.SaveAs(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);
                oDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                //关闭word
                oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
            }

        }
Exemplo n.º 20
0
 private void Button_Click_1(object sender, RoutedEventArgs e)
 {
     Microsoft.Office.Interop.Word.Application fileOpen = new Microsoft.Office.Interop.Word.Application();;
     try
     {
         var header = File.ReadAllLines(ExcelFilePath.Text).FirstOrDefault().Split(',');
         fileOpen.Visible        = false;
         fileOpen.ScreenUpdating = false;
         using (var reader = new StreamReader(ExcelFilePath.Text))
             using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
             {
                 var records = csv.GetRecords <dynamic>();
                 foreach (var line in records)
                 {
                     //Open a already existing word file into the new document created
                     Microsoft.Office.Interop.Word.Document document = fileOpen.Documents.Open(WordFilePath.Text, ReadOnly: true);
                     //Make the file visible
                     document.Activate();
                     //The FindAndReplace takes the text to find under any formatting and replaces it with the
                     //new text with the same exact formmating (e.g red bold text will be replaced with red bold text)
                     var path = SaveFormat.Text;
                     foreach (var heading in header)
                     {
                         var x = (((IDictionary <String, Object>)line)[heading]).ToString();
                         x = x.Replace("\n", "\n\r");
                         FindAndReplace(fileOpen, "$$" + heading + "$$", x);
                         path = path.Replace("$$" + heading + "$$", x);
                     }
                     var a = (object)Path.Combine(OutputFolder.Text, path + ".docx");
                     document.SaveAs2(ref a);
                     document.Close();
                 }
                 //Save the editted file in a specified location
                 //Can use SaveAs instead of SaveAs2 and just give it a name to have it saved by default
                 //to the documents folder
             }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
     finally
     {
         fileOpen?.Quit();
     }
 }
Exemplo n.º 21
0
        /// <summary>
        /// Предоставляет класса для создания Word файла по шаблону.
        /// </summary>
        /// <param name="templateFile">Файл шаблона</param>
        public WordFile(string templateFile)
        {
            try
            {
                Application               = new Word.Application();
                Application.Visible       = false;
                Application.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;

                Document = Application.Documents.Open(templateFile);
            }
            catch (Exception ex)
            {
                Document?.Close();
                Application?.Quit();
                throw ex;
            }
        }
Exemplo n.º 22
0
        public override string Read()
        {
            try
            {
                Word.Application app = new Word.Application();

                object missingValue = System.Reflection.Missing.Value;
                object readOnly = true;
                object filePath = FilePath;

                Word.Document docs = app.Documents.Open(ref filePath,
                                                   ref missingValue,
                                                   ref missingValue,
                                                   ref readOnly, // 4
                                                   ref missingValue,
                                                   ref missingValue,
                                                   ref missingValue,
                                                   ref missingValue, // 8
                                                   ref missingValue,
                                                   ref missingValue,
                                                   ref missingValue,
                                                   ref missingValue, // 12
                                                   ref missingValue,
                                                   ref missingValue,
                                                   ref missingValue,
                                                   ref missingValue);
                docs.Activate();

                string totalText = "";

                for (int i = 0; i < docs.Paragraphs.Count; i++)
                {
                    totalText += "\r\n" + docs.Paragraphs[i + 1].Range.Text.ToString();
                }

                docs.Close(missingValue,missingValue,missingValue);
                app.Quit(missingValue,missingValue,missingValue);

                return totalText;
            }
            catch (Exception e)
            {
                // not handle the exception in this method
                throw e;
            }
        }
Exemplo n.º 23
0
 /// <summary>
 /// Close the related application
 /// </summary>
 public void KillApp()
 {
     try
     {
         if (_oApp?.Documents.Count > 0)
         {
             _oApp?.Quit();
         }
         if (_oApp is not null)
         {
             Marshal.FinalReleaseComObject(_oApp);
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
     }
 }
Exemplo n.º 24
0
        public bool convertDocToTxt(string pSourcePath, string pDestinationPath)
        {
            object _missing = System.Reflection.Missing.Value;
            Word.Application wordApp = new Word.Application();
            Word.Document aDoc = null;
            try
            {
                if (File.Exists(@"" + pSourcePath))
                {

                    object readOnly = false;
                    object isVisible = false;
                    wordApp.Visible = false;

                    object path = @"" + pSourcePath;

                    aDoc = wordApp.Documents.Open(ref path, ref _missing,
                            ref readOnly, ref _missing, ref _missing, ref _missing,
                            ref _missing, ref _missing, ref _missing, ref _missing,
                            ref _missing, ref isVisible, ref _missing, ref _missing,
                            ref _missing, ref _missing);
                    string _content = aDoc.Content.Text;
                    _content = _content.Replace("/n", "/r/n");
                    _content = _content.Trim();
                    File.WriteAllText(@"" + pDestinationPath, _content);
                    return true;
                }
                else
                {
                    MessageBox.Show("File does not exist!", "DIIA", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                aDoc.Close();
                wordApp.Quit();
                GC.Collect();
            }
        }
		public void TestGetVersionNumber()
		{
			TestClassForOfficeApplicationVersion test = new TestClassForOfficeApplicationVersion();

			Word.Application myWord = new Word.Application();
			Assert.AreEqual(test.GetVersionFromAppType(testenum.AppWord, myWord), test.GetInstalledWordVersion(), "Versions are different for Word");
			myWord.Quit();
			Marshal.ReleaseComObject(myWord);

			PowerPoint.Application myPPT = new PowerPoint.Application();
			Assert.AreEqual(test.GetVersionFromAppType(testenum.AppPowerPoint, myPPT), test.GetInstalledPowerPointVersion(), "Versions are different for PowerPoint");
			Marshal.ReleaseComObject(myPPT);

			Excel.Application myExcel = new Excel.Application();
			Assert.AreEqual(test.GetVersionFromAppType(testenum.AppExcel, myExcel), test.GetInstalledExcelVersion(), "Versions are different for Excel");
			Marshal.ReleaseComObject(myExcel);

			GC.Collect();
		}
Exemplo n.º 26
0
 public static void ConvertWordDocumentToPdf(string srcFile, string dstFile)
 {
     Word.Application wordApp = null;
     Word.Document    wordDoc = null;
     try
     {
         wordApp = new Word.Application
         {
             DisplayAlerts = Word.WdAlertLevel.wdAlertsNone
         };
         wordDoc = wordApp.Documents.OpenNoRepairDialog(srcFile, true, false, false);
         wordDoc.ExportAsFixedFormat(dstFile, Word.WdExportFormat.wdExportFormatPDF);
     }
     finally
     {
         wordDoc?.Close(SaveChanges: false);
         wordApp?.Quit();
     }
 }
Exemplo n.º 27
0
        private void button1_Click(object sender, EventArgs e)
        {
            object oMissing = System.Reflection.Missing.Value;
            Object oFalse = false;

            //Start Word and create a new document.
            Word._Application oWord;
            Word._Document oDoc;
            oWord = new Word.Application();
            oWord.Visible = false;
            oWord.ScreenUpdating = false;
            oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
                ref oMissing, ref oMissing);

            ///////////////////////
            Word.Style style1 = oDoc.Styles.Add("MyHeading4");
            style1.set_BaseStyle("Heading 4"); //this is the ID of the style
            style1.Font.Size = 14;
            int num1 = style1.Creator;
            Word.Style style2 = oDoc.Styles.Add("MyHeading5");
            style2.set_BaseStyle("Heading 5"); //this is the ID of the style
            style2.Font.Bold = 1;
            int num2 = style1.Creator;
            /////////////////////////

            insertHtmlFile(ref oWord, ref oDoc, "c:/temp/word/merge.html", "Html Title", "Html Sub Title");

            insertFileLink(ref oWord, ref oDoc, "merge.pdf", "pdf title");

            /////////////////////////////////
            insertPageNumbers(ref oWord, ref oDoc, "Mission Name");

            ///////////////////////
            insertTableOfContents(ref oWord, ref oDoc);

               ///////////////////////
            saveAsPdf(ref oWord, ref oDoc, "c:/temp/word/test.pdf");

            oDoc.Close(ref oFalse, ref oMissing, ref oMissing);

            oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
        }
Exemplo n.º 28
0
        public static void Convert(string input, string output, string type)
        {
            Word.Application wordApp = null;
            try
            {
                Word.WdExportFormat format;
                if (type.Equals("xps"))
                {
                    format = Word.WdExportFormat.wdExportFormatXPS;
                }
                else if (type.Equals("pdf"))
                {
                    format = Word.WdExportFormat.wdExportFormatPDF;
                }
                else
                {
                    throw new ArgumentException("Invalid output file type");
                }

                wordApp = new Word.Application
                {
                    Visible = false
                };

                var wordDoc     = wordApp.Documents.Open(input, ReadOnly: true); // Open in readonly
                var viewQuality = Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen;
                wordDoc.ExportAsFixedFormat(output, format, false, viewQuality);
                wordDoc.Close(Word.WdSaveOptions.wdDoNotSaveChanges,
                              Word.WdOriginalFormat.wdOriginalDocumentFormat,
                              false); //Close document
            }
            catch (COMException e)
            {
                Console.WriteLine("Microsoft Word is not installed...");
                Console.WriteLine(e.Message);
            }
            finally
            {
                wordApp?.Quit();  //Important: When you forget this Word keeps running in the background
            }
        }
Exemplo n.º 29
0
        public Main()
        {
            //Prompt user to select the word document template they would like to use.
            Word.Application wordApp = OpenTemplate();

            //Prompt user to select CSV file and import the data from it.
            if (!_dataCollector.ImportCSV())
            {
                wordApp?.Quit();
                System.Environment.Exit(1);
            }

            List <ColumnValueCounter> columnValueCounters = _dataCollector.AssembleColumnValueCounters();

            _documentManipulator.ProcessDocument(wordApp, columnValueCounters);

            MessageBox.Show(new Form {
                TopMost = true
            }, "Template Processing Completed Successfully");
            System.Environment.Exit(0);
        }
Exemplo n.º 30
0
 private void MicrosoftWord()
 {
     var wordApp = new Word.Application();
     wordApp.Visible = false;
     try
     {
         if (!File.Exists(@PATH))
         {
             File.Create(@PATH);
         }
         var wordDocument = wordApp.Documents.Open(@PATH);
         Word.Table table;
         Word.Range range = wordDocument.Content;
         table = wordDocument.Tables.Add(range, 100, 10);
         table.Range.ParagraphFormat.SpaceAfter = 6;
         int r, c;
         string strText;
         for (r = 1; r <= 100; r++)
             for (c = 1; c <= 10; c++)
             {
                 strText = Guid.NewGuid().ToString();
                 table.Cell(r, c).Range.Text = strText;
             }
         table.Rows[1].Range.Font.Bold = 1;
         table.Rows[1].Range.Font.Italic = 1;
         table.Borders.Enable = 1;
         wordDocument.SaveAs(@SAVE_AS);
         wordApp.Visible = false;
         wordDocument.Close();
     }
     catch (Exception ex)
     {
         Console.WriteLine("System has found exception : " + ex);
     }
     finally
     {
         wordApp.Quit();
     }
 }
Exemplo n.º 31
0
        public static void CreateDocument(string title, string subtitle, string description, string author,
            string processImagePath, List<ScreenImage> images, string outputFileName, bool includeModules, bool format2003)
        {
            object template = GetTemplateDirectory(format2003);

            if (File.Exists(template.ToString()))
            {
                //Start Word and create a new document.
                Word._Application oWord = new Word.Application();
                Word._Document oDoc;
                object visible = true;

                oDoc = oWord.Documents.Add(ref template, ref oMissing, ref oMissing, ref visible);

                UpdateBookmark(subtitle, "processtitle", oDoc, 18, 1);
                UpdateBookmark(author, "author", oDoc, 16, 0);
                UpdateBookmark(subtitle, "processtitle2", oDoc, 18, 1);
                UpdateBookmark(description, "description", oDoc, 11, 0);
                UpdateBookmarkWithImage(processImagePath, "processimage", oDoc);

                foreach (ScreenImage si in images)
                {
                    UpdateBookmark(si.Title, oEndOfDoc, oDoc, 16, 1);
                    UpdateBookmark("URL: " + si.ApplicationURL, oEndOfDoc, oDoc, 11, 0);
                    UpdateBookmark("Path: " + si.Path, oEndOfDoc, oDoc, 11, 0);
                    UpdateBookmark(si.Notes, oEndOfDoc, oDoc, 11, 0);
                    UpdateBookmarkWithImage(si.Filename, oEndOfDoc, oDoc);
                    InsertPageBreak(oDoc);
                }

                object output = outputFileName;
                oDoc.SaveAs(ref output, 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);

                //oWord.Visible = true;
                oDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
            }
        }
Exemplo n.º 32
0
        private void ConvertDocument(string fileName)
        {
            object      m           = Missing.Value;
            object      oldFileName = fileName;
            object      readOnly    = false;
            Application ac          = null;

            try
            {
                // First, create a new Microsoft.Office.Interop.Word.ApplicationClass.
                ac = new Application();

                // Now we open the document.
                var doc = ac.Documents.Open(ref oldFileName, ref m, ref readOnly,
                                            ref m, ref m, ref m, ref m, ref m, ref m, ref m,
                                            ref m, ref m, ref m, ref m, ref m, ref m);

                // Create a temp file to save the HTML file to.
                TempFileName = GetTempFile("html");

                // Cast these items to object.  The methods we're calling
                // only take object types in their method parameters.
                object newFileName = TempFileName;

                // We will be saving this file as HTML format.
                object fileType = WdSaveFormat.wdFormatHTML;

                // Save the file.
                doc.SaveAs(ref newFileName, ref fileType,
                           ref m, ref m, ref m, ref m, ref m, ref m, ref m,
                           ref m, ref m, ref m, ref m, ref m, ref m, ref m);
            }
            finally
            {
                // Make sure we close the application class.
                ac?.Quit(ref readOnly, ref m, ref m);
            }
        }
Exemplo n.º 33
0
        private XpsDocument ConvertWordDocToXPSDoc(string wordDocName, string xpsDocName)
        {
            // Create a WordApplication and add Document to it
            Microsoft.Office.Interop.Word.Application
            wordApplication = new Microsoft.Office.Interop.Word.Application();
            wordApplication.Documents.Add(wordDocName);

            Document doc = wordApplication.ActiveDocument;

            try
            {
                doc.SaveAs(xpsDocName, WdSaveFormat.wdFormatXPS);
                wordApplication.Quit();

                XpsDocument xpsDoc = new XpsDocument(xpsDocName, System.IO.FileAccess.Read);
                return xpsDoc;
            }
            catch (Exception exp)
            {
                string str = exp.Message;
            }
            return null;
        }
        public void Open(string filepath, TextBox t)
        {
            Word._Application application = new Word.Application();

            Word._Document designDocument = application.Documents.Open(filepath, ConfirmConversions: false, ReadOnly: true, AddToRecentFiles: false, Revert: false, Visible: false, OpenAndRepair: false);

            WikiFeaturePageContent content = new WikiFeaturePageContent();

            int paragraphCount = designDocument.Paragraphs.Count;

            for (int i = 1; i <= paragraphCount; i++)
            {
                if (processDocument(designDocument, ref content, ref i))
                {
                    break;
                }
            }

            designDocument.Close(SaveChanges: false);
            application.Quit(SaveChanges: false);

            t.Text = content.Purpose + content.AssumptionsAndConstraints + content.DesignConcepts;
        }
        public void PrintLabel(Surplus surplus)
        {
            string savefolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            string wordFilename = savefolder + "\\surplus.docx";
            Word.Application wordApp = new Word.Application { Visible = false };
            wordApp.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
            Word.Document wordDoc = wordApp.Documents.Open(wordFilename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            wordDoc.Activate();

            FindAndReplace(wordApp, "{type}", surplus.Type);
            FindAndReplace(wordApp, "{court}", surplus.Court);
            FindAndReplace(wordApp, "{county}", surplus.County);
            FindAndReplace(wordApp, "{state}", surplus.State);
            FindAndReplace(wordApp, "{serial}", surplus.Serial);
            FindAndReplace(wordApp, "{make}", surplus.Make);
            FindAndReplace(wordApp, "{model}", surplus.Model);
            FindAndReplace(wordApp, "{useable_parts}", surplus.Useable_Parts);
            FindAndReplace(wordApp, "{reuseable}", surplus.Reuseable_Equipment);
            //FindAndReplace(wordApp, "{type}", surplus.Reason_for_Surplus);
            FindAndReplace(wordApp, "{date}", DateTime.Now.ToString("MM-dd-yyyy"));
            wordDoc.PrintOut();
            wordDoc.Close(SaveChanges: false);
            wordApp.Quit(Type.Missing, Type.Missing, Type.Missing);
        }
Exemplo n.º 36
0
        public TDS2(DataTDS2 Data, Client NewClient, BackgroundWorker bw, string owner, string location, string device)
        {
            try
            {
                Owner    = owner;
                Location = location;
                Device   = device;
                _client  = NewClient;
                #region start Word
                //Create an instance for word app
                _wordDocument = new Microsoft.Office.Interop.Word.Application();

                //Set animation status for word application
                //2013
                //_wordDocument.ShowAnimation = false;

                //Set status for word application is to be visible or not.
                _wordDocument.Visible = false;

                _missing = System.Reflection.Missing.Value;

                //Create a new document
                _document = _wordDocument.Documents.Add(ref _missing, ref _missing, ref _missing, ref _missing);
                //Поля
                _document.PageSetup.RightMargin = 35;
                _document.PageSetup.LeftMargin  = 35;
                _document.Paragraphs.Alignment  = WdParagraphAlignment.wdAlignParagraphJustify;
                _wordDocument.ActiveWindow.Selection.ParagraphFormat.LineSpacingRule = Microsoft.Office.Interop.Word.WdLineSpacing.wdLineSpaceSingle;
                _wordDocument.ActiveWindow.Selection.ParagraphFormat.SpaceAfter      = 0.0F;
                bw.ReportProgress(30);
                #endregion
                #region Header
                //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.wdBlack;
                    headerRange.Font.Name = "Times New Roman";
                    //headerRange.Font.ColorIndexBi =
                    headerRange.Font.Size = 14;
                    headerRange.Text      = "КГБУЗ «КМКБ №20 им. И. С. Берзона»\n" +
                                            "Дуплексное сканирование с ЦДК аорты и висцеральных ветвей";
                }

                _document.Content.SetRange(1, 1);
                #endregion
                Microsoft.Office.Interop.Word.Paragraph mainParagraph = _document.Content.Paragraphs.Add(ref _missing);
                mainParagraph.Range.Text      = "";
                mainParagraph.Range.Font.Size = 12;
                mainParagraph.Range.Font.Name = "Times New Roman";
                mainParagraph.Range.InsertParagraphAfter();
                #region InfoTable
                Table infotable = _document.Tables.Add(mainParagraph.Range, 3, 2, ref _missing, ref _missing);
                infotable.Rows.Alignment = WdRowAlignment.wdAlignRowCenter;

                infotable.Cell(1, 1).Range.Text = $"Дата {DateTime.Now.ToShortDateString()}";
                infotable.Cell(1, 2).Range.Text = $"Аппарат: {Device}";
                infotable.Cell(2, 1).Range.Text = $"Ф.И.О. {NewClient.Name}";
                infotable.Cell(2, 2).Range.Text = $"Условия локации: {Location}";
                infotable.Cell(3, 1).Range.Text = NewClient.HistoryNumber.Trim().Length != 0 ? $"№ истории болезни {NewClient.HistoryNumber}\tВозраст {NewClient.Age}" : $"Возраст {NewClient.Age}";
                infotable.Cell(3, 2).Range.Text = $"Врач: {Owner}";

                foreach (Row row in infotable.Rows)
                {
                    foreach (Cell cell in row.Cells)
                    {
                        cell.Range.Font.Size   = 12;
                        cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                        if (cell.ColumnIndex == 1)
                        {
                            cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;// WdParagraphAlignment.wdAlignParagraphCenter;
                        }
                        if (cell.ColumnIndex == 2)
                        {
                            cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;// WdParagraphAlignment.wdAlignParagraphCenter;
                        }
                    }
                }
                #endregion
                mainParagraph.Range.InsertParagraphAfter();
                bw.ReportProgress(20);

                Microsoft.Office.Interop.Word.Paragraph par1 = _document.Content.Paragraphs.Add(ref _missing);
                par1.Range.Font.Size = 12;
                par1.Range.Font.Name = "Times New Roman";
                par1.Range.Bold      = 1;
                par1.Range.Text      = $" Аорта";
                par1.Range.InsertParagraphAfter();
                par1.Range.InsertParagraphAfter();
                par1.Range.Bold = 0;

                par1.Range.Text = $" {Data.Paragraphs[0]}";
                par1.Range.InsertParagraphAfter();
                par1.Range.InsertParagraphAfter();

                par1.Range.Text = $" {Data.Paragraphs[1]}";
                par1.Range.InsertParagraphAfter();
                par1.Range.InsertParagraphAfter();

                par1.Range.Text = $" {Data.Paragraphs[2]}";
                par1.Range.InsertParagraphAfter();
                par1.Range.InsertParagraphAfter();

                par1.Range.Text = $" {Data.Paragraphs[3]}";
                par1.Range.InsertParagraphAfter();
                par1.Range.InsertParagraphAfter();

                if (Data.Paragraphs[4] != "")
                {
                    par1.Range.Text = $" Дополнительные данные: {Data.Paragraphs[4]}";
                    par1.Range.InsertParagraphAfter();
                    par1.Range.InsertParagraphAfter();
                }

                bw.ReportProgress(40);

                #region 1stTable
                //Table header
                Microsoft.Office.Interop.Word.Paragraph titleTable = _document.Content.Paragraphs.Add(ref _missing);
                titleTable.Range.Font.Size = 12;
                titleTable.Range.Font.Name = "Times New Roman";
                titleTable.Range.Font.Bold = 1;
                // titleTable.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; ;
                titleTable.Range.Text = "\t\tКоличественные характеристики кровотока в висцеральных аретриях";

                titleTable.Range.InsertParagraphAfter();
                titleTable.Range.InsertParagraphAfter();
                int   Table1NumRows = 5;
                int   Table1NumCols = 4;
                Table Table1        = _document.Tables.Add(mainParagraph.Range, Table1NumRows, Table1NumCols, ref _missing, ref _missing);

                Table1.Borders.Enable = 1;
                Table1.Rows.Alignment = WdRowAlignment.wdAlignRowCenter;

                for (int i = 0; i < Data.TableColumns.Count; i++)
                {
                    Table1.Cell(1, i + 1).Range.Text = Data.TableColumns[i];
                }

                for (int i = 0; i < Data.Table.Count; i++)
                {
                    Table1.Cell(i + 2, 1).Range.Text = Data.Table[i].Name;
                    var criterias = Data.Table[i].GetVluesList();
                    for (int j = 0; j < Table1NumCols - 1; j++)
                    {
                        Table1.Cell(i + 2, j + 2).Range.Text = criterias[j];
                    }
                }
                foreach (Row row in Table1.Rows)
                {
                    foreach (Cell cell in row.Cells)
                    {
                        cell.Range.Font.Size   = 11;
                        cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                        cell.Height            = 30;// WdRowHeightRule.wdRowHeightAtLeast;

                        if (cell.ColumnIndex == 1)
                        {
                            cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                            cell.Width = 120f;
                        }
                        else
                        {
                            cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                            cell.Width = 95f;
                        }
                    }
                }
                #endregion
                mainParagraph.Range.InsertParagraphAfter();
                bw.ReportProgress(60);

                if (Data.Paragraphs[4] != "")
                {
                    par1.Range.Text = $"Заключение: {Data.Paragraphs[5]}";
                    par1.Range.InsertParagraphAfter();
                }

                bw.ReportProgress(85);
                titleTable.Range.InsertParagraphAfter();

                bw.ReportProgress(90);
            }
            catch (Exception ex)
            {
                _wordDocument?.Quit(ref _missing, ref _missing, ref _missing);
                _wordDocument = null;
                // Compose a string that consists of three lines.
                string lines = ex.ToString();

                // Write the string to a file.
                System.IO.StreamWriter file = new System.IO.StreamWriter($@"{Directory.GetCurrentDirectory()}\err.txt");
                file.WriteLine(lines);

                file.Close();
            }
        }
Exemplo n.º 37
0
        private async Task <List <CockleFilePdf> > executePdfConversionForProof(
            IProgress <string> progress, CancellationToken cancellationToken, List <CockleFile> latestFiles)
        {
            bool exceptionThrownInAwait = false; // tracks excptn in await

            List <CockleFile> filesSelectedForConversion;
            bool convertAll = false;

            // get files from grid if null
            if (null == latestFiles)
            {
                filesSelectedForConversion = SelectedFiles;
            }
            else
            {
                convertAll = true; filesSelectedForConversion = latestFiles;
            }

            if (filesSelectedForConversion.Count < 1)
            {
                throw new Exception();
            }

            // begin AWAIT
            var filesToReturnFromTask = await Task.Run(() =>
            {
                //instantiate Word Application & Document
                Word.Application app = new Word.Application();
                app.Visible          = false; //true; // changed 9-7-17
                Word.Document doc    = null;

                //get original printer & prepare to create PDF
                var current_printer        = app.ActivePrinter;
                var konica_554_prn_printer = "554 Print to File";
                app.ActivePrinter          = konica_554_prn_printer;

                // collection of special class to track files
                var filesPrintedToPrnSuccessfully = new List <FilesPrintedToPrnSuccessfully>();
                // the Word file saved to scratch
                try
                {
                    // counter to track files printed
                    int i = 0;
                    // Q. copy all files to scratch?  A. cannot, because need tagline to read server drive



                    // loop through files
                    foreach (CockleFile fileSelected in filesSelectedForConversion)
                    {
                        // cancel if requested
                        try { cancellationToken.ThrowIfCancellationRequested(); }
                        catch (OperationCanceledException) { exceptionThrownInAwait = true; throw new OperationCanceledException(); }

                        // Open docx files in Word, clean up, and convert
                        try
                        {
                            doc = app.Documents.Open(FileName: fileSelected.LocalFullFilename, ReadOnly: true);
                        }
                        catch
                        {
                            System.Diagnostics.Debug.WriteLine($"{fileSelected.FullName} failed to open");
                        }

                        // cancel if requested
                        try { cancellationToken.ThrowIfCancellationRequested(); }
                        catch (OperationCanceledException) { exceptionThrownInAwait = true; throw new OperationCanceledException(); }

                        // print to pdf, reporting progress
                        var newPrnConvertedFromWord = string.Empty;
                        newPrnConvertedFromWord     = MicrosoftWordStaticClass.PrintToFileForProof(app, doc.FullName);

                        // halt process here: wait for COM background status to end
                        while (app.BackgroundPrintingStatus > 0 && app.BackgroundSavingStatus > 0)
                        {
                            try { cancellationToken.ThrowIfCancellationRequested(); }
                            catch (OperationCanceledException) { exceptionThrownInAwait = true; throw new OperationCanceledException(); }
                        }

                        // add to files_printed list
                        filesPrintedToPrnSuccessfully.Add(
                            new FilesPrintedToPrnSuccessfully
                        {
                            CockleFile  = fileSelected,
                            PrnFilename = newPrnConvertedFromWord,
                            Filetype    = fileSelected.FileType
                        });

                        // make sure file exists before closing
                        while (!System.IO.File.Exists(newPrnConvertedFromWord))
                        {
                            System.Diagnostics.Debug.WriteLine($"Waiting to print to pdf: {newPrnConvertedFromWord}");
                            // cancel if requested
                            try { cancellationToken.ThrowIfCancellationRequested(); }
                            catch (OperationCanceledException) { exceptionThrownInAwait = true; throw new OperationCanceledException(); }
                        }
                        // close document & delete temp file
                        doc.Close(SaveChanges: Word.WdSaveOptions.wdDoNotSaveChanges);
                        // increment counter
                        i++;
                    }// end for loop to convert each files
                }
                //catch (OperationCanceledException ex) { }
                catch { }
                finally
                {
                    app.ActivePrinter = current_printer;
                    app?.Quit();
                }
                if (exceptionThrownInAwait)
                {
                    // close app
                    app.ActivePrinter = current_printer;
                    app?.Quit();
                    // try to clean folder
                    filesPrintedToPrnSuccessfully.ForEach(f =>
                    {
                        if (System.IO.File.Exists(f.PrnFilename))
                        {
                            System.IO.File.Delete(f.PrnFilename);
                        }
                    });
                    return(null);
                }

                // block until all files exist
                while (filesPrintedToPrnSuccessfully?.Count != filesSelectedForConversion.Count)
                {
                    ;
                }

                // NOW, CHANGE NAMES OF FILES TO PS, AND USE GHOSTSCRIPT TO CONVERT TO PDF

                var filesPrintedSuccessfully = new List <FilePrintedSuccessfully>();

                foreach (var f in filesPrintedToPrnSuccessfully)
                {
                    var psFileName  = f.PrnFilename.Replace(".prn", ".ps");
                    var pdfFileName = f.PrnFilename.Replace(".prn", ".pdf");

                    System.IO.File.Move(f.PrnFilename, psFileName);
                    // block until successful
                    while (!System.IO.File.Exists(psFileName)) /*waiting for IO*/ } {
                    using (var processor = new Ghostscript.NET.Processor.GhostscriptProcessor())
                    {
                        List <string> switches = new List <string>();
                        switches.Add("-empty");
                        switches.Add("-dQUIET");
                        switches.Add("-dSAFER");
                        switches.Add("-dBATCH");
                        switches.Add("-dNOPAUSE");
                        switches.Add("-dNOPROMPT");
                        switches.Add("-sDEVICE=pdfwrite");
                        switches.Add("-o" + pdfFileName);
                        switches.Add("-q");
                        switches.Add("-f");
                        switches.Add(psFileName);

                        processor.StartProcessing(switches.ToArray(), null);
                    }

                    // make sure successful
                    while (!System.IO.File.Exists(pdfFileName)) /*waiting for IO*/ } {
                    filesPrintedSuccessfully.Add(
                        new FilePrintedSuccessfully
                    {
                        CockleFile    = f.CockleFile,
                        TempWordFile  = string.Empty,
                        PdfFilename   = pdfFileName,
                        Filetype      = SourceFileTypeEnum.Unrecognized, // may have to adjust type here
                        LengthOfCover = null
                    });

                    System.IO.File.Delete(psFileName);
            }

                                                       #region POINT OF NO RETURN IN CONVERSION
                                                       // convert files to CockleFilePdf
                                                       var cockleFilePdfsPrintedSuccessfully = new List <CockleFilePdf>();
                                                       foreach (var _f in filesPrintedSuccessfully)
                {
                    if (_f.LengthOfCover == null && _f.CockleFile == null)
                    {
                        cockleFilePdfsPrintedSuccessfully.Add(new CockleFilePdf(_f.PdfFilename, _f.Filetype));
                    }
                    else
                    {
                        cockleFilePdfsPrintedSuccessfully.Add(
                            new CockleFilePdf(_f.CockleFile, _f.PdfFilename, _f.LengthOfCover));
                    }
                }

                                                       // test whether all converted files have same ticket
                                                       bool allConvertedFilesSameTicket = cockleFilePdfsPrintedSuccessfully
                                                                                          .TrueForAll(f => f.TicketNumber ==
                                                                                                      cockleFilePdfsPrintedSuccessfully.First().TicketNumber);

                                                                                                                                                             // move files to unique folder
                                                       if ((allConvertedFilesSameTicket || IsSingleTicket) && cockleFilePdfsPrintedSuccessfully.Count() > 0) // PROBLEM HERE !!!
                {
                    var firstFile    = cockleFilePdfsPrintedSuccessfully.First();
                    string timeStamp = string.Format("({0} {1}, {2}, {3})", DateTime.Now.ToString("MMM") /*Oct*/,
                                                     DateTime.Now.ToString("dd") /*09*/, DateTime.Now.ToString("yyy") /*2015*/,
                                                     DateTime.Now.ToString("T").ToLower() /*10:58:44 AM*/ /*, len_text*/)
                                       .Replace(':', ' ');
                    var folderName      = $"{firstFile.TicketNumber} {firstFile.Attorney} {timeStamp}";
                    var scratchLocation = @"c:\scratch";

                    var newFolder = System.IO.Directory.CreateDirectory(System.IO.Path.Combine(scratchLocation, folderName));

                    foreach (var f in cockleFilePdfsPrintedSuccessfully)
                    {
                        try
                        {
                            var new_filename = System.IO.Path.Combine(newFolder.FullName, f.Filename);
                            System.IO.File.Move(f.FullName, new_filename);

                            // associate new location with CockleFilePdf
                            f.FullName = new_filename;
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine(ex);
                        }
                    }
                }

                                                       // set destination property
                                                       DestinationFolderConvertedFiles = System.IO.Path.GetDirectoryName(cockleFilePdfsPrintedSuccessfully.First().FullName);

                                                       // set ranks of pdfs before returning
                                                       setCockleFilePdfRanks(cockleFilePdfsPrintedSuccessfully);


                                                       if (convertAll)
                {
                    // 1. create imposed pdf files
                    Models.Imposition.ImposeFullConvertedTicket createImposedPdfiTextSharp = null;
                    try
                    {
                        var len_of_cover = cockleFilePdfsPrintedSuccessfully
                                           .Where(f => f.FileType == SourceFileTypeEnum.Cover).First().CoverLength ?? -1;

                        // prepare files for imposition
                        //var cockleFilePdfsPrintedSuccessfullyToCombine = cockleFilePdfsPrintedSuccessfully.ToList();
                        //cockleFilePdfsPrintedSuccessfullyToCombine.Remove(mergedCockleFile);

                        createImposedPdfiTextSharp =
                            new Models.Imposition.ImposeFullConvertedTicket(
                                DestinationFolderConvertedFiles,
                                cockleFilePdfsPrintedSuccessfully.ToList(),
                                len_of_cover,
                                TypeOfBindEnum.ProgramDecidesByPageCount);

                        // add imposed files to list of cocklefilepdf files
                        if (createImposedPdfiTextSharp.ImposedFilesCreated.All(f => System.IO.File.Exists(f.FullName)))
                        {
                            createImposedPdfiTextSharp.ImposedFilesCreated.ForEach(f =>
                            {
                                cockleFilePdfsPrintedSuccessfully.Add(
                                    new CockleFilePdf(
                                        f.FullName,
                                        filesSelectedForConversion.First().Attorney,
                                        filesSelectedForConversion.First().TicketNumber,
                                        SourceFileTypeEnum.Imposed_Cover_and_Brief,
                                        "pdf",
                                        null));
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        if (null != createImposedPdfiTextSharp.ImposedFilesCreated &&
                            createImposedPdfiTextSharp.ImposedFilesCreated.Count > 0)
                        {
                            createImposedPdfiTextSharp.ImposedFilesCreated.ForEach(x => System.IO.File.Delete(x.FullName));

                            foreach (var imposed_file in createImposedPdfiTextSharp.ImposedFilesCreated)
                            {
                                if (cockleFilePdfsPrintedSuccessfully.Contains(imposed_file))
                                {
                                    cockleFilePdfsPrintedSuccessfully.Remove(imposed_file);
                                }
                            }
                        }
                        System.Diagnostics.Debug.WriteLine(ex.Message);
                    }

                    // 2. combine files into single pdf
                    Models.MergePdf.CreateMergedPDFAcrobat createMergedPdfAcrobat = null;
                    CockleFilePdf mergedCockleFile = null;
                    try
                    {
                        createMergedPdfAcrobat = new Models.MergePdf.CreateMergedPDFAcrobat(
                            cockleFilePdfsPrintedSuccessfully, Models.MergePdf.TypeOfCombinedPdf.All, centerPdf: true);

                        // add combined file to list of cocklefilepdf files
                        if (System.IO.File.Exists(createMergedPdfAcrobat.CombinedPdfFilename))
                        {
                            mergedCockleFile =
                                new CockleFilePdf(
                                    createMergedPdfAcrobat.CombinedPdfFilename,
                                    filesSelectedForConversion.First().Attorney,
                                    filesSelectedForConversion.First().TicketNumber,
                                    SourceFileTypeEnum.Combined_Pdf,
                                    "pdf",
                                    null);
                            cockleFilePdfsPrintedSuccessfully.Add(mergedCockleFile);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (null != createMergedPdfAcrobat.CombinedPdfFilename &&
                            System.IO.File.Exists(createMergedPdfAcrobat.CombinedPdfFilename))
                        {
                            System.IO.File.Delete(createMergedPdfAcrobat.CombinedPdfFilename);
                        }
                        if (null != mergedCockleFile &&
                            cockleFilePdfsPrintedSuccessfully.Contains(mergedCockleFile))
                        {
                            cockleFilePdfsPrintedSuccessfully.Remove(mergedCockleFile);
                        }
                        System.Diagnostics.Debug.WriteLine(ex.Message);
                    }
                }
                                                       #endregion


                                                       return(cockleFilePdfsPrintedSuccessfully);
});

            if (exceptionThrownInAwait)
            {
                throw new OperationCanceledException();
            }
            return(filesToReturnFromTask);
        }
        private void sendIt_Click(object sender, RoutedEventArgs e)
        {
            File.Copy(@"C:\Users\Public\ReportManager\templateBackup.docx", @"C:\Users\Public\ReportManager\template.docx", true);
            int    totalMaquinado = 0, totalOficina = 0, totalSoldadura = 0, totalAlmacen = 0, total = 0, alm = 0, maq = 0, of = 0, sold = 0, completed = 0, pending = 0, waiting = 0, verify = 0, inStock = 0;
            string trackID = "", requestName = "OA -WAS-" + DateTime.Today.Month + "-" + DateTime.Today.Year;
            string connectionString = "server=localhost; database=receiptManagerDB; user=root; password=; Allow Zero Datetime=True; Convert Zero Datetime=True";

            if (requestList.Items.Count > 0)
            {
                DateTime init = DateTime.Today, end = DateTime.Today;
                for (int i = 0; i < requestList.Items.Count; i++)
                {
                    data dataObject = (data)requestList.Items[i];
                    DateTime.TryParse(dataObject.realDeliverDate.ToString(), out end);
                    trackID = dataObject.trackID;
                    if (end < init)
                    {
                        init = end;
                    }
                    switch (dataObject.department)
                    {
                    case "Maquinados":
                        totalMaquinado += int.Parse(dataObject.spentMoney);
                        maq            += 1;
                        break;

                    case "Oficina":
                        totalOficina += int.Parse(dataObject.spentMoney);
                        of           += 1;
                        break;

                    case "Soldadura":
                        totalSoldadura += int.Parse(dataObject.spentMoney);
                        sold           += 1;
                        break;

                    case "Almacen":
                        totalAlmacen += int.Parse(dataObject.spentMoney);
                        alm          += 1;
                        break;
                    }
                    switch (dataObject.status)
                    {
                    case "Completada":
                        completed += 1;
                        break;

                    case "Pendiente Importar":
                        pending += 1;
                        break;

                    case "En espera de llegada":
                        waiting += 1;
                        break;

                    case "Verificar Informacion":
                        verify += 1;
                        break;

                    case "En planta":
                        inStock += 1;
                        break;
                    }
                    MySqlCommand    cmd;
                    MySqlDataReader reader;
                    using (MySqlConnection conn = new MySqlConnection(connectionString))
                    {
                        try
                        {
                            conn.Open();
                            cmd             = conn.CreateCommand();
                            cmd.CommandText = "UPDATE `requests` SET `status`='Completada' WHERE `requestOrder`='" + dataObject.requestID + "';";
                            //UPDATE `requestsinfo` SET `status`='something' WHERE id
                            reader = cmd.ExecuteReader();
                            conn.Close();
                        }
                        catch (MySqlException ex)
                        {
                            MessageBox.Show("Conection error with the DB " + ex.Message.ToString(), "Warning", MessageBoxButton.OK);
                        }
                    }
                }
                total = totalMaquinado + totalOficina + totalSoldadura + totalAlmacen;
                Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
                Microsoft.Office.Interop.Word.Document    wordDoc = wordApp.Documents.Open(@"C:\Users\Public\ReportManager\template.docx", Visible: false);
                string   classtype = "Excel.Chart.8";
                Bookmark bkm       = wordDoc.Bookmarks["trackID"];
                Microsoft.Office.Interop.Word.Range rng = bkm.Range;
                rng.Text = trackID;
                bkm      = wordDoc.Bookmarks["managerName"];
                rng      = bkm.Range;
                rng.Text = name;
                bkm      = wordDoc.Bookmarks["requestOrder"];
                rng      = bkm.Range;
                rng.Text = requestName;
                bkm      = wordDoc.Bookmarks["initDate"];
                rng      = bkm.Range;
                rng.Text = init.Date.Day + "/" + init.Date.Month + "/" + init.Date.Year;
                bkm      = wordDoc.Bookmarks["endDate"];
                rng      = bkm.Range;
                rng.Text = end.Date.Day + "/" + end.Date.Month + "/" + end.Date.Year;
                bkm      = wordDoc.Bookmarks["creationDate"];
                rng      = bkm.Range;
                rng.Text = DateTime.Today.Day + "/" + DateTime.Today.Month + "/" + DateTime.Today.Year;
                //////CHARTS PIE
                bkm = wordDoc.Bookmarks.get_Item("pieChart");
                Microsoft.Office.Interop.Word.InlineShape wrdInlineShape = wordDoc.InlineShapes.AddOLEObject(classtype);
                object oEndOfDoc = "pieChart";
                if (wrdInlineShape.OLEFormat.ProgID == "Excel.Chart.8")
                {
                    object verb = Microsoft.Office.Interop.Word.WdOLEVerb.wdOLEVerbHide;
                    wrdInlineShape.OLEFormat.DoVerb(ref verb);
                    Microsoft.Office.Interop.Excel.Workbook  obook = (Microsoft.Office.Interop.Excel.Workbook)wrdInlineShape.OLEFormat.Object;
                    Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)obook.Worksheets["Sheet1"];

                    obook.Application.Visible = false;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[1, 1]).Value = "Departamentos";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[2, 1]).Value = "Almacen";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[3, 1]).Value = "Maquinado";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[4, 1]).Value = "Oficinas";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[5, 1]).Value = "Soldadura";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[6, 1]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[7, 1]).ClearContents();

                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[1, 2]).Value = "Costos";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[2, 2]).Value = totalAlmacen;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[3, 2]).Value = totalMaquinado;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[4, 2]).Value = totalOficina;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[5, 2]).Value = totalSoldadura;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[6, 2]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[7, 2]).ClearContents();

                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[1, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[2, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[3, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[4, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[5, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[6, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[7, 3]).ClearContents();

                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[1, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[2, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[3, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[4, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[5, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[6, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[7, 4]).ClearContents();

                    wrdInlineShape.Width = 400;

                    obook.ActiveChart.ChartType = Microsoft.Office.Interop.Excel.XlChartType.xl3DPie;
                    Microsoft.Office.Interop.Word.Range wrdRng = wordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                    object oRng = wordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                    wrdRng = wordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                    sheet.UsedRange.Copy();
                    wordDoc.SetDefaultTableStyle("Light List - Accent 4", false);
                    wrdRng.PasteExcelTable(true, true, false);
                    wrdInlineShape.ConvertToShape();
                    obook.Close();
                }
                //baaars chart
                bkm            = wordDoc.Bookmarks.get_Item("barChart");
                wrdInlineShape = wordDoc.InlineShapes.AddOLEObject(classtype);
                oEndOfDoc      = "barChart";
                if (wrdInlineShape.OLEFormat.ProgID == "Excel.Chart.8")
                {
                    object verb = Microsoft.Office.Interop.Word.WdOLEVerb.wdOLEVerbHide;
                    wrdInlineShape.OLEFormat.DoVerb(ref verb);
                    Random rn = new Random();
                    Microsoft.Office.Interop.Excel.Workbook  obook = (Microsoft.Office.Interop.Excel.Workbook)wrdInlineShape.OLEFormat.Object;
                    Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)obook.Worksheets["Sheet1"];

                    obook.Application.Visible = false;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[1, 1]).Value = "Departamentos";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[2, 1]).Value = "Almacen";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[3, 1]).Value = "Maquinado";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[4, 1]).Value = "Oficinas";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[5, 1]).Value = "Soldadura";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[6, 1]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[7, 1]).ClearContents();

                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[1, 2]).Value = "Total de requerimientos";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[2, 2]).Value = alm;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[3, 2]).Value = maq;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[4, 2]).Value = of;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[5, 2]).Value = sold;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[6, 2]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[7, 2]).ClearContents();

                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[1, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[2, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[3, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[4, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[5, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[6, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[7, 3]).ClearContents();

                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[1, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[2, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[3, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[4, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[5, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[6, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[7, 4]).ClearContents();
                    wrdInlineShape.Width = 400;

                    obook.ActiveChart.ChartType = Microsoft.Office.Interop.Excel.XlChartType.xl3DLine;
                    Microsoft.Office.Interop.Word.Range wrdRng = wordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                    object oRng = wordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                    wrdRng = wordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                    sheet.UsedRange.Copy();
                    wordDoc.SetDefaultTableStyle("Light List - Accent 4", false);
                    wrdRng.PasteExcelTable(true, true, false);
                    wrdInlineShape.ConvertToShape();
                    obook.Close();
                }
                //Lines chart
                bkm            = wordDoc.Bookmarks.get_Item("linesChart");
                wrdInlineShape = wordDoc.InlineShapes.AddOLEObject(classtype);
                oEndOfDoc      = "linesChart";
                if (wrdInlineShape.OLEFormat.ProgID == "Excel.Chart.8")
                {
                    object verb = Microsoft.Office.Interop.Word.WdOLEVerb.wdOLEVerbHide;
                    wrdInlineShape.OLEFormat.DoVerb(ref verb);
                    Microsoft.Office.Interop.Excel.Workbook  obook = (Microsoft.Office.Interop.Excel.Workbook)wrdInlineShape.OLEFormat.Object;
                    Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)obook.Worksheets["Sheet1"];

                    obook.Application.Visible = false;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[1, 1]).Value = "Estatus";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[2, 1]).Value = "Completada";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[3, 1]).Value = "Pendiente Importar";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[4, 1]).Value = "En espera de llegada";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[5, 1]).Value = "Verificar Informacion";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[6, 1]).Value = "En planta";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[7, 1]).ClearContents();

                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[1, 2]).Value = "Cantidad de requerimientos";
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[2, 2]).Value = completed;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[3, 2]).Value = pending;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[4, 2]).Value = waiting;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[5, 2]).Value = verify;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[6, 2]).Value = inStock;
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[7, 2]).ClearContents();

                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[1, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[2, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[3, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[4, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[5, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[6, 3]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[7, 3]).ClearContents();

                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[1, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[2, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[3, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[4, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[5, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[6, 4]).ClearContents();
                    ((Microsoft.Office.Interop.Excel.Range)sheet.Cells[7, 4]).ClearContents();

                    wrdInlineShape.Width = 400;

                    obook.ActiveChart.ChartType = Microsoft.Office.Interop.Excel.XlChartType.xl3DBarStacked;
                    Microsoft.Office.Interop.Word.Range wrdRng = wordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                    object oRng = wordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                    wrdRng = wordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                    sheet.UsedRange.Copy();
                    wordDoc.SetDefaultTableStyle("Light List - Accent 4", false);
                    wrdRng.PasteExcelTable(true, true, false);
                    wrdInlineShape.ConvertToShape();
                    obook.Close();
                }
                object fileName = @"C:\Users\Public\ReportManager\Reportes\Request_Report #" + requestName + ".docx";
                try
                {
                    wordDoc.SaveAs2(fileName);
                    MessageBox.Show("Se creó el archivo satisfactoriamente", "¡Listo!", MessageBoxButton.OK);
                }
                catch (Exception exc)
                {
                    MessageBox.Show("Hubo un error con el archivo" + exc.Message.ToString(), "¡ERROR!", MessageBoxButton.OK);
                }
                wordDoc.Close();
                wordApp.Quit();
                Process.Start(fileName.ToString());
                Process.Start(@"C:\Users\Public\ReportManager\Reportes\");
                MainWindow main = new MainWindow();
                main.Show();
                Close();
            }
        }
        private void btnPreview_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(txbName.Text) ||
                String.IsNullOrEmpty(txbPhoneNumber.Text) ||
                String.IsNullOrEmpty(txbTemplatePath.Text))
            {
                MessageBox.Show("Do not enough information to preview the report", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            List <Pallet> listPallet = new List <Pallet>();

            switch (Display.Mode)
            {
            case "Real Time": listPallet = Pallet.ListPallet; break;

            case "Simulation": listPallet = Pallet.SimListPallet; break;
            }

            object missing = System.Reflection.Missing.Value;

            MSWord.Application wordApp   = new MSWord.Application();
            MSWord.Document    myWordDoc = null;
            object             filename  = txbTemplatePath.Text;

            if (System.IO.File.Exists((string)filename))
            {
                DateTime today     = DateTime.Now;
                object   readOnly  = false; //default
                object   isVisible = false;
                wordApp.Visible = false;
                myWordDoc       = wordApp.Documents.Open(ref filename, ref missing, ref readOnly,
                                                         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);

                //Find and replace:
                this.FindAndReplace(wordApp, "<name>", txbName.Text);
                this.FindAndReplace(wordApp, "<phone number>", txbPhoneNumber.Text);
                this.FindAndReplace(wordApp, "<date>", DateTime.Now.ToString("dddd, MMMM dd, yyyy h:mm:ss tt"));
                this.FindAndReplace(wordApp, "<email>", txbEmail.Text);
                this.FindAndReplace(wordApp, "<count>", listPallet.Count);
                this.FindAndReplace(wordApp, "<p>", (listPallet.Count) / 72.0f * 100.0f);

                MSWord.Table table = myWordDoc.Tables[1];
                for (int i = 0; i < listPallet.Count; i++)
                {
                    table.Cell(i + 2, 1).Range.Text = (i + 1).ToString();
                    table.Cell(i + 2, 2).Range.Text = listPallet[i].Code;
                    table.Cell(i + 2, 3).Range.Text = listPallet[i].StoreTime;
                    table.Cell(i + 2, 4).Range.Text = listPallet[i].AtBlock + "-" + listPallet[i].AtColumn + "-" + listPallet[i].AtLevel;
                    if (i != listPallet.Count - 1)
                    {
                        table.Rows.Add(missing);
                    }
                }
            }
            else
            {
                MessageBox.Show("File dose not exist.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            myWordDoc.ActiveWindow.Selection.WholeStory();
            myWordDoc.ActiveWindow.Selection.Copy();
            IDataObject dataObject = Clipboard.GetDataObject();

            rtxbTemplate.Rtf = dataObject.GetData(DataFormats.Rtf).ToString();

            object isSave = false;

            myWordDoc.Close(isSave, ref missing, ref missing);
            wordApp.Quit(isSave, ref missing, ref missing);
        }
Exemplo n.º 40
0
        private void buttonShowPages_Click(object sender, EventArgs e)
        {
            string msg = "";

            try
            {
                DialogResult ret = this.openFileDialogWord.ShowDialog(this);

                if (ret != DialogResult.OK)
                {
                    return;
                }

                string docFile = this.openFileDialogWord.FileName;

                if (docFile == null || !(docFile.ToLower().EndsWith("doc") || docFile.ToLower().EndsWith("docx")))
                {
                    msg = "非word文件: " + docFile;
                    throw new Exception(msg);
                }

                this.textBox1.Text = msg;

                object wordFile = docFile;

                object oMissing = Missing.Value;

                //自定义object类型的布尔值
                object oTrue  = true;
                object oFalse = false;

                object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;

                //定义WORD Application相关
                Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();

                //WORD程序不可见
                appWord.Visible = false;
                //不弹出警告框
                appWord.DisplayAlerts = WdAlertLevel.wdAlertsNone;

                //打开要打印的文件
                Microsoft.Office.Interop.Word.Document doc = appWord.Documents.Open(
                    ref wordFile,
                    ref oMissing,
                    ref oTrue,
                    ref oFalse,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing);


                // 计算Word文档页数 
                WdStatistic stat = WdStatistic.wdStatisticPages;
                int         num  = doc.ComputeStatistics(stat, ref oMissing);//.ComputeStatistics(stat, ref Nothing); 
                //打印完关闭WORD文件
                doc.Close(ref doNotSaveChanges, ref oMissing, ref oMissing);

                //退出WORD程序
                appWord.Quit(ref oMissing, ref oMissing, ref oMissing);

                doc     = null;
                appWord = null;

                msg = docFile + " : All Pages:" + num;
            }
            catch (System.Exception ex)
            {
                msg = ex.Message;
            }

            this.textBox1.Text = msg;
        }
Exemplo n.º 41
0
        private void button5_Click(object sender, EventArgs e)
        {
            List <Shablons> GetTime = dal.GetAllShablons(Convert.ToInt64(dataGridView1.CurrentRow.Cells["Номер карты"].Value.ToString()));

            Word.Application app = new Word.Application();
            Word.Document    doc = app.Documents.Add(Visible: true);
            Word.Range       r   = doc.Range();
            Word.Table       t   = doc.Tables.Add(r, GetTime.Count, 1);
            t.Borders.Enable = 1;
            int ii = -1;

            // int flag = 0, iii = 0;
            foreach (Word.Row row in t.Rows)
            {
                foreach (Word.Cell cell in row.Cells)
                {
                    ii++;

                    /*if (cell.RowIndex == 1)
                     * {
                     *  if (cell.ColumnIndex == 1)
                     *  {
                     *      cell.Range.Text = "ФИО Врача";
                     *      ii = 1;
                     *  }
                     *  if (cell.ColumnIndex == 2)
                     *  {
                     *      cell.Range.Text = "ФИО Пациента";
                     *      ii = 2;
                     *  }
                     *
                     *  if (cell.ColumnIndex == 3)
                     *  {
                     *      cell.Range.Text = "Дата посещения";
                     *      ii = 4;
                     *  }
                     *  if (cell.ColumnIndex == 4)
                     *  {
                     *      cell.Range.Text = "Диагноз";
                     *      ii = 5;
                     *  }
                     *  if (cell.ColumnIndex == 5)
                     *  {
                     *      cell.Range.Text = "Код";
                     *      ii = 6;
                     *  }
                     *
                     *  // cell.Range.Text = "Колонка" + cell.ColumnIndex.ToString();
                     *  cell.Range.Bold = 1;
                     *  cell.Range.Font.Name = "verdana";
                     *  cell.Range.Font.Size = 10;
                     *
                     *  cell.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                     *  cell.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                     * }
                     * else
                     * {
                     *  if (flag == 0)
                     *  {
                     *      while (iii < AllPrint.Count)
                     *      {
                     *
                     *          if (Convert.ToInt64(AllPrint[iii].Year) >= Convert.ToInt64(dateTimePicker3.Value.Year) && Convert.ToInt64(AllPrint[iii].Year) <= Convert.ToInt64(dateTimePicker2.Value.Year))
                     *          {
                     *              if (Convert.ToInt64(AllPrint[iii].Month) >= dateTimePicker3.Value.Month && Convert.ToInt64(AllPrint[iii].Month) <= dateTimePicker2.Value.Month)
                     *              {
                     *                  if (Convert.ToInt64(AllPrint[iii].Day) >= dateTimePicker3.Value.Day && Convert.ToInt64(AllPrint[iii].Day) <= dateTimePicker2.Value.Day)
                     *                  {
                     *                      flag++;
                     *                      iii++;
                     *                      break;
                     *                  }
                     *              }
                     *          }
                     *      }
                     *  }*/

                    // if (cell.ColumnIndex == 1)
                    // {
                    cell.Range.Text = "ФИО врача: " + GetTime[ii].DocName + "\n" + "Дата: " + GetTime[ii].Day + "/" + GetTime[ii].Month + "/" + GetTime[ii].Year + "\n" + GetTime[ii].Bolezn + "\n" + GetTime[ii].Shablon;

                    /* }
                     * if (cell.ColumnIndex == 2)
                     * {
                     *   cell.Range.Text = AllPrint[iii].PacName;
                     * }
                     * if (cell.ColumnIndex == 3)
                     * {
                     *   cell.Range.Text = AllPrint[iii].Day.ToString() + "/" + AllPrint[iii].Month.ToString() + "/" + AllPrint[iii].Year.ToString();
                     * }
                     *
                     * if (cell.ColumnIndex == 4)
                     * {
                     *   cell.Range.Text = AllPrint[iii].Diagnoz.ToString();
                     * }
                     * if (cell.ColumnIndex == 5)
                     * {
                     *   cell.Range.Text = AllPrint[iii].Code;
                     *   flag = 0;
                     * }*/

                    //}
                }
            }
            doc.SaveAs(@"C:\Result\" + dataGridView1.CurrentRow.Cells["Фамилия"].Value.ToString() + ".doc");

            app.Documents.Open(@"C:\Template\1.docx");
            try
            {
                app.Documents.Close();
                app.Quit();
            }
            catch
            {
            }
        }
Exemplo n.º 42
0
        /// <summary>
        /// 向指定Word中写入指定文本
        /// </summary>
        /// <param name="filePath">Word 所在路径</param>
        /// <param name="list">所需写入的内容</param>
        public static void WriteDocument(ref string filePath, List <DataRow> list, object SpeName, object SpeCode)
        {
            Microsoft.Office.Interop.Word.Application app = null;
            Document doc = null;

            try
            {
                //构造数据
                List <EntityObject> datas = new List <EntityObject>();
                for (int i = 0; i < list.Count; i++)
                {
                    string code    = SQLiteHelper.GetValueByKey(list[i]["fi_categor"]);
                    string name    = GetValue(list[i]["fi_name"]);
                    string user    = GetValue(list[i]["fi_user"]);
                    string carrier = SQLiteHelper.GetValueByKey(list[i]["fi_carrier"]);
                    int    pages   = Convert.ToInt32(list[i]["fi_pages"]);
                    string date    = GetDateTime(list[i]["fi_create_date"], "yyyy-MM-dd");
                    datas.Add(new EntityObject {
                        Code = code, Name = name, User = user, Type = carrier, PageSize = pages, Date = date
                    });
                }

                int    rows     = datas.Count() + 1;                   //表格行数加1是为了标题栏
                int    cols     = 7;                                   //表格列数
                object oMissing = Missing.Value;
                app = new Microsoft.Office.Interop.Word.Application(); //创建word应用程序
                doc = app.Documents.Add();                             //添加一个word文档

                app.Selection.PageSetup.LeftMargin  = 50f;
                app.Selection.PageSetup.RightMargin = 50f;
                app.Selection.PageSetup.PageWidth   = 800f; //页面宽度

                //标题
                app.Selection.Font.Bold = 700;
                app.Selection.Font.Size = 18;
                app.Selection.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                app.Selection.Text = "重大专项项目(课题)档案交接清单";

                //子标题
                object subLine = WdUnits.wdLine;
                app.Selection.MoveDown(ref subLine, oMissing, oMissing);
                app.Selection.TypeParagraph();//换行
                app.Selection.Font.Bold = 0;
                app.Selection.Font.Size = 12;
                app.Selection.Text      = $"专项名称:{SpeName}\t\t专项编号:{SpeCode}";

                //换行添加表格
                object line = WdUnits.wdLine;
                app.Selection.MoveDown(ref line, oMissing, oMissing);
                app.Selection.TypeParagraph();//换行
                app.Selection.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                Range range = app.Selection.Range;
                Table table = app.Selection.Tables.Add(range, rows, cols, ref oMissing, ref oMissing);
                //设置表格的字体大小粗细
                table.Range.Font.Size          = 10;
                table.Range.Font.Bold          = 0;
                table.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle;
                table.Borders.InsideLineStyle  = WdLineStyle.wdLineStyleSingle;

                //设置表格标题
                int rowIndex = 1;
                table.Rows[rowIndex].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                table.Rows[rowIndex].Range.Font.Bold = 100;
                table.Rows[rowIndex].Height          = 30f;
                table.Cell(rowIndex, 1).Range.Text   = "项目(课题)档案材料名称";
                table.Cell(rowIndex, 2).Range.Text   = "责任者";
                table.Cell(rowIndex, 3).Range.Text   = "载体类型";
                table.Cell(rowIndex, 4).Range.Text   = "页数";
                table.Cell(rowIndex, 5).Range.Text   = "文件数";
                table.Cell(rowIndex, 6).Range.Text   = "日期";
                table.Cell(rowIndex, 7).Range.Text   = "备注";
                table.Columns[1].Width = 200f;
                table.Columns[2].Width = table.Columns[4].Width = table.Columns[5].Width = 50f;
                //循环数据创建数据行
                foreach (EntityObject eo in datas)
                {
                    rowIndex++;
                    table.Cell(rowIndex, 1).Range.Text = eo.Name;
                    table.Cell(rowIndex, 2).Range.Text = eo.User;
                    table.Cell(rowIndex, 3).Range.Text = eo.Type;
                    table.Cell(rowIndex, 4).Range.Text = eo.PageSize.ToString();
                    table.Cell(rowIndex, 6).Range.Text = eo.Date;
                    table.Cell(rowIndex, 7).Range.Text = eo.Remark;
                }
                app.Selection.EndKey(WdUnits.wdStory, oMissing); //将光标移动到文档末尾
                app.Selection.Font.Bold = 0;
                app.Selection.Font.Size = 11;

                //底部署名
                doc.Content.InsertAfter("\n移交单位(盖章):                                        接收单位(盖章):\n");
                doc.Content.InsertAfter("移交人:                                                 接收人:\n");
                doc.Content.InsertAfter("交接时间:    年  月  日");

                //导出到文件
                filePath += DateTime.Now.ToString("yyyyMMddHHmmss") + ".doc";
                doc.SaveAs(filePath,
                           oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
                           oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (doc != null)
                {
                    doc.Close();//关闭文档
                }
                if (app != null)
                {
                    app.Quit();//退出应用程序
                }
            }
        }
        private void CreateWordDocument(object filename, object savaAs)
        {
            List <Pallet> listPallet = new List <Pallet>();

            switch (Display.Mode)
            {
            case "Real Time": listPallet = Pallet.ListPallet; break;

            case "Simulation": listPallet = Pallet.SimListPallet; break;
            }

            object missing = System.Reflection.Missing.Value;

            MSWord.Application wordApp = new MSWord.Application();

            MSWord.Document myWordDoc = null;

            if (System.IO.File.Exists((string)filename))
            {
                DateTime today = DateTime.Now;

                object readOnly  = false; //default
                object isVisible = false;

                wordApp.Visible = false;

                myWordDoc = wordApp.Documents.Open(ref filename, ref missing, ref readOnly,
                                                   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);

                myWordDoc.Activate();

                //Find and replace:
                this.FindAndReplace(wordApp, "<name>", txbName.Text);
                this.FindAndReplace(wordApp, "<phone number>", txbPhoneNumber.Text);
                this.FindAndReplace(wordApp, "<date>", DateTime.Now.ToString("dddd, MMMM dd, yyyy h:mm:ss tt"));
                this.FindAndReplace(wordApp, "<email>", txbEmail.Text);
                this.FindAndReplace(wordApp, "<count>", listPallet.Count);
                this.FindAndReplace(wordApp, "<p>", (listPallet.Count) / 72.0f * 100.0f);

                MSWord.Table table = myWordDoc.Tables[1];
                for (int i = 0; i < listPallet.Count; i++)
                {
                    table.Cell(i + 2, 1).Range.Text = (i + 1).ToString();
                    table.Cell(i + 2, 2).Range.Text = listPallet[i].Code;
                    table.Cell(i + 2, 3).Range.Text = listPallet[i].StoreTime;
                    table.Cell(i + 2, 4).Range.Text = listPallet[i].AtBlock + "-" + listPallet[i].AtColumn + "-" + listPallet[i].AtLevel;
                    if (i != listPallet.Count - 1)
                    {
                        table.Rows.Add(missing);
                    }
                }
            }
            else
            {
                MessageBox.Show("File dose not exist.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            //Save as: filename
            myWordDoc.SaveAs2(ref savaAs, 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);

            myWordDoc.Close(ref missing, ref missing, ref missing);
            wordApp.Quit(ref missing, ref missing, ref missing);

            MessageBox.Show("File is created at:\n" + savaAs, "", MessageBoxButtons.OK, MessageBoxIcon.Information);

            txbTemplatePath.Clear();
            rtxbTemplate.Clear();
        }
Exemplo n.º 44
0
        /// <summary>
        /// Takes a command provided by the user in the word document, parses it into a TextReplacementOptions object, and executes that command based on the user-provided parameters.
        /// </summary>
        /// <param name="rawCommand">The exact text provided by the user in the document command</param>
        /// <param name="columnValueCounters">List of objects that contain information about each column</param>
        private void ProcessDocumentCommand(string rawCommand, Word.Application wordApp, List <ColumnValueCounter> columnValueCounters)
        {
            //Remove any extraneous braces
            string command = rawCommand.Trim('{', '}');
            TextReplacementOptions processedCommand = new TextReplacementOptions();

            //Parse the raw command to get a textReplacementOptions object that stores more usable command options.
            try {
                processedCommand = GetTextReplacementOptions(command);
            }
            catch (Exception e) {
                MessageBox.Show(new Form {
                    TopMost = true
                }, "Error: " + e.Message);
                wordApp.Quit();
                Environment.Exit(1);
            }
            //if the command was a declaration of the color pallette used in the document, just remove the text and do not execute anything.
            if (processedCommand.isColors)
            {
                ReplaceTextWithText(rawCommand, "", wordApp);
                return;
            }
            else if (processedCommand.isOrder)
            {
                _graphColumnOrder = processedCommand.order;
                ReplaceTextWithText(rawCommand, "", wordApp);
                return;
            }
            //A list of the columns that we actually use for this command.
            DocumentCommandExecuter commandExecuter = new DocumentCommandExecuter(ColorPalette, _graphColumnOrder);
            //Populate a list of columnValueCounters that pertain to the columns that we are actually using for this command.
            List <ColumnValueCounter> usedColumns = GetUsedColumns(processedCommand, columnValueCounters);

            //Ensure that all columns in the list of used columns have the same number of unique row values
            NormalizeColumns(usedColumns);
            if (processedCommand.hasFailed)
            {
                MessageBox.Show(new Form {
                    TopMost = true
                }, "Command Failed: Check template command syntax");
                wordApp.Quit();
                Environment.Exit(1);
            }
            if (usedColumns.Count == 0)
            {
                MessageBox.Show(new Form {
                    TopMost = true
                }, "No columns found in CSV file for command:\n" + processedCommand.rawInput);
                wordApp.Quit();
                Environment.Exit(1);
            }
            //Process the command as a graph
            if (processedCommand.isGraph)
            {
                string replaceWith = commandExecuter.GenerateGraph(usedColumns, Application.StartupPath + "\\tempGraph.PNG", processedCommand, wordApp);
                ReplaceTextWithImage(rawCommand, replaceWith, wordApp);
            }
            //Process the command as text replacement
            else if (processedCommand.isText)
            {
                string replaceWith = commandExecuter.GenerateText(usedColumns, processedCommand);
                ReplaceTextWithText(rawCommand, replaceWith, wordApp);
            }
            else
            {
                return;
            }
        }
Exemplo n.º 45
0
        private void button1_Click(object sender, EventArgs e)
        {
            Word.Application app = new Word.Application() ;   //定义应用程序对象
            Word.Document doc = null;   //定义 word 文档对象
            Object saveChanges = app.Options.BackgroundSave;//文档另存为
            Object missing = System.Reflection.Missing.Value; //定义空变量

            try
            {

                Object isReadOnly = false;
                object filePath = AppDomain.CurrentDomain.BaseDirectory + "test.dotx";//文档路径
                doc = app.Documents.Open(ref filePath, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

                doc.Activate();//激活文档
                object bookmarkName = "richTextContentControl1";
                foreach (Word.ContentControl item in app.ActiveDocument.ContentControls)
                {
                    if (item.Tag =="Information")
                    {
                        item.SetPlaceholderText(Text: "紫川软件...");
                    }
                }

                object savePath = AppDomain.CurrentDomain.BaseDirectory + "test.docx";   //文档另存为的路径

                doc.SaveAs(ref savePath, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
            }
            catch (Exception ex)
            {

            }
            finally
            {
                doc.Close(ref saveChanges, ref missing, ref missing);//关闭文档
                app.Quit(ref missing, ref missing, ref missing);//关闭应用程序
            }
        }
Exemplo n.º 46
0
        public string GetReport()
        {
            try
            {
                _wordApp = new Word.Application();
                _doc = _wordApp.Documents.Add(_templateWordPath);

                _doc.Bookmarks["Арендатор"].Range.Text = Renter;
                _doc.Bookmarks["АрендаторФИО"].Range.Text = RenterFIO;
                _doc.Bookmarks["Арендодатель"].Range.Text = LandLord;
                _doc.Bookmarks["АрендодательФИО"].Range.Text = Director;
                _doc.Bookmarks["Город"].Range.Text = City;
                _doc.Bookmarks["ГосНомер1"].Range.Text = TransportRegNumber;
                _doc.Bookmarks["ГосНомер2"].Range.Text = TransportRegNumber;
                _doc.Bookmarks["Дата"].Range.Text = Date.ToShortDateString();
                _doc.Bookmarks["ДатаДоговора"].Range.Text = ContractDate.ToShortDateString();
                _doc.Bookmarks["Директор"].Range.Text = LandLordFIO;
                _doc.Bookmarks["Номер"].Range.Text = Number.ToString();
                _doc.Bookmarks["Транспорт1"].Range.Text = TransportName;
                _doc.Bookmarks["Транспорт2"].Range.Text = TransportName;

                _doc.SaveAs2(FileName: _documnetSavePath, FileFormat: Word.WdSaveFormat.wdFormatPDF);

                return _documnetSavePath;
            }
            catch (Exception)
            {
            }
            finally
            {
                _doc.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
                _wordApp.Quit(Word.WdSaveOptions.wdDoNotSaveChanges);
            }
            return null;
        }
Exemplo n.º 47
0
        ///<summary>
        ///Процедура формирования документа
        ///</summary>
        ///<param name="type">Тип документа</param>
        ///<param name="name">Название документа</param>
        ///<param name="table">результирующая таблица</param>
        public void Document_Create(Document_Type type, string name, DataTable table)
        {
            //Получение данных о документе
            Configuration_class configuration_Class = new Configuration_class();

            configuration_Class.Document_Configuration_Get();
            switch (name != "" || name != null)
            {
            case (true):
                switch (type)
                {
                case (Document_Type.Check):
                    //Открытие приложения и документа в нём
                    word.Application application = new word.Application();
                    word.Document    document    = application.Documents.Add(Visible: true);
                    //Формирование документа
                    try
                    {
                        //Начало
                        word.Range range = document.Range(0, 0);
                        //Поля
                        document.Sections.PageSetup.LeftMargin   = application.CentimetersToPoints((float)Configuration_class.doc_Left_Merge);
                        document.Sections.PageSetup.RightMargin  = application.CentimetersToPoints((float)Configuration_class.doc_Right_Merge);
                        document.Sections.PageSetup.TopMargin    = application.CentimetersToPoints((float)Configuration_class.doc_Top_Merge);
                        document.Sections.PageSetup.BottomMargin = application.CentimetersToPoints((float)Configuration_class.doc_Bottom_Merge);
                        //Присвоение текстового значения в абзац
                        range.Text = Configuration_class.Organization_Name;
                        //Выравнивание
                        range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter;
                        //Интервалы в абзаце
                        range.ParagraphFormat.SpaceAfter      = 1;
                        range.ParagraphFormat.SpaceBefore     = 1;
                        range.ParagraphFormat.LineSpacingRule = word.WdLineSpacing.wdLineSpaceSingle;
                        //Шрифт
                        range.Font.Name = "Times New Roman";
                        range.Font.Size = 12;
                        //Параграф (один Enter)
                        document.Paragraphs.Add();
                        document.Paragraphs.Add();
                        document.Paragraphs.Add();
                        //Название документа
                        word.Paragraph Document_Name = document.Paragraphs.Add();
                        //Настройка параграфа
                        Document_Name.Format.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter;
                        Document_Name.Range.Font.Name  = "Times New Roman";
                        Document_Name.Range.Font.Size  = 16;
                        Document_Name.Range.Text       = "Выгрузка чека";
                        document.Paragraphs.Add();
                        document.Paragraphs.Add();
                        document.Paragraphs.Add();
                        //Создание таблицы
                        word.Paragraph statparg   = document.Paragraphs.Add();
                        word.Table     stat_table = document.Tables.Add(statparg.Range, table.Rows.Count, table.Columns.Count);
                        //Настройка таблицы
                        stat_table.Borders.InsideLineStyle       = word.WdLineStyle.wdLineStyleSingle;
                        stat_table.Borders.OutsideLineStyle      = word.WdLineStyle.wdLineStyleSingle;
                        stat_table.Rows.Alignment                = word.WdRowAlignment.wdAlignRowCenter;
                        stat_table.Range.Cells.VerticalAlignment = word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                        stat_table.Range.Font.Size               = 11;
                        stat_table.Range.Font.Name               = "Times New Roman";
                        //Заполнение таблицы
                        for (int row = 1; row <= table.Rows.Count; row++)
                        {
                            for (int col = 1; col <= table.Columns.Count; col++)
                            {
                                stat_table.Cell(row, col).Range.Text = table.Rows[row - 1][col - 1].ToString();
                            }
                        }
                        document.Paragraphs.Add();
                        document.Paragraphs.Add();
                        document.Paragraphs.Add();
                        //Строка даты создания
                        word.Paragraph Footparg = document.Paragraphs.Add();
                        Footparg.Range.Text = string.Format("Дата создания \t\t\t{0}", DateTime.Now.ToString());
                    }
                    catch
                    {
                    }
                    finally
                    {
                        try
                        {
                            //Сохранение документа
                            document.SaveAs2(name + "DOC", word.WdSaveFormat.wdFormatDocument);
                            //Закрытие документа
                            document.Close(SaveChanges: false);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                        application.Quit();
                    }
                    break;

                case (Document_Type.MarkSchemes):
                    //Открытие приложения, создание документа (книги) и листа в нём.
                    excel.Application application_ex = new excel.Application();
                    excel.Workbook    workbook       = application_ex.Workbooks.Add();
                    //excel.Worksheet worksheet = (excel.Worksheet)workbook.ActiveSheet;
                    excel.Worksheet worksheet = workbook.ActiveSheet;
                    try
                    {
                        worksheet.Name        = "MarketerDoc";
                        worksheet.Cells[1][1] = "Отчёт о работе отдела маркетинга";
                        worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[1, table.Columns.Count + 1]].Merge();
                        //Заполнение таблицы
                        for (int row = 0; row < table.Rows.Count; row++)
                        {
                            for (int col = 0; col < table.Columns.Count; col++)
                            {
                                worksheet.Cells[row + 3, col + 1] = table.Rows[row][col].ToString();
                            }
                        }
                        //Работа со стилем таблицы
                        excel.Range border1 = worksheet.Range[worksheet.Cells[3, 1], worksheet.Cells[table.Rows.Count + 3][table.Columns.Count]];
                        border1.Borders.LineStyle   = excel.XlLineStyle.xlContinuous;
                        border1.VerticalAlignment   = excel.XlVAlign.xlVAlignCenter;
                        border1.HorizontalAlignment = excel.XlHAlign.xlHAlignCenter;
                        //Дата документа
                        worksheet.Cells[2][table.Rows.Count + 3] = string.Format("Дата создания {0}", DateTime.Now.ToString());
                        //Объединение ячеек
                        worksheet.Range[worksheet.Cells[table.Rows.Count + 3, 2], worksheet.Cells[table.Rows.Count + 3, table.Columns.Count + 2]].Merge();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    finally
                    {
                        //Сохранение и выход
                        workbook.SaveAs(name, application_ex.DefaultSaveFormat);
                        workbook.Close();
                        application_ex.Quit();
                    }
                    break;

                case (Document_Type.Order):
                    //Открытие приложения и документа в нём
                    word.Application application_or = new word.Application();
                    word.Document    document_or    = application_or.Documents.Add(Visible: true);
                    //Формирование документа
                    try
                    {
                        //Начало
                        word.Range range = document_or.Range(0, 0);
                        //Поля
                        document_or.Sections.PageSetup.LeftMargin   = application_or.CentimetersToPoints((float)Configuration_class.doc_Left_Merge);
                        document_or.Sections.PageSetup.RightMargin  = application_or.CentimetersToPoints((float)Configuration_class.doc_Right_Merge);
                        document_or.Sections.PageSetup.TopMargin    = application_or.CentimetersToPoints((float)Configuration_class.doc_Top_Merge);
                        document_or.Sections.PageSetup.BottomMargin = application_or.CentimetersToPoints((float)Configuration_class.doc_Bottom_Merge);
                        //Присвоение текстового значения в абзац
                        range.Text = Configuration_class.Organization_Name;
                        //Выравнивание
                        range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter;
                        //Интервалы в абзаце
                        range.ParagraphFormat.SpaceAfter      = 1;
                        range.ParagraphFormat.SpaceBefore     = 1;
                        range.ParagraphFormat.LineSpacingRule = word.WdLineSpacing.wdLineSpaceSingle;
                        //Шрифт
                        range.Font.Name = "Times New Roman";
                        range.Font.Size = 12;
                        //Параграф (один Enter)
                        document_or.Paragraphs.Add();
                        document_or.Paragraphs.Add();
                        document_or.Paragraphs.Add();
                        //Название документа
                        word.Paragraph Document_Name = document_or.Paragraphs.Add();
                        //Настройка параграфа
                        Document_Name.Format.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter;
                        Document_Name.Range.Font.Name  = "Times New Roman";
                        Document_Name.Range.Font.Size  = 16;
                        Document_Name.Range.Text       = table.Rows[0][0].ToString();
                        document_or.Paragraphs.Add();
                        document_or.Paragraphs.Add();
                        document_or.Paragraphs.Add();
                        //Создание таблицы
                        word.Paragraph statparg      = document_or.Paragraphs.Add();
                        word.Paragraph Document_Text = document_or.Paragraphs.Add();
                        //Настройка параграфа
                        Document_Text.Format.Alignment  = word.WdParagraphAlignment.wdAlignParagraphLeft;
                        Document_Text.Format.LeftIndent = (float)1.25;
                        Document_Text.Range.Font.Name   = "Times New Roman";
                        Document_Text.Range.Font.Size   = 14;
                        Document_Text.Range.Text        = table.Rows[0][1].ToString();
                    }
                    catch
                    {
                    }
                    finally
                    {
                        try
                        {
                            //Сохранение документа
                            document_or.SaveAs2(name + "PDF", word.WdSaveFormat.wdFormatPDF);
                            //Закрытие документа
                            document_or.Close(SaveChanges: false);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                        application_or.Quit();
                    }
                    break;

                case (Document_Type.Storage):
                    //Открытие приложения и документа в нём
                    word.Application application_St = new word.Application();
                    word.Document    document_St    = application_St.Documents.Add(Visible: true);
                    //Формирование документа
                    try
                    {
                        //Начало
                        word.Range range = document_St.Range(0, 0);
                        //Поля
                        document_St.Sections.PageSetup.LeftMargin   = application_St.CentimetersToPoints((float)Configuration_class.doc_Left_Merge);
                        document_St.Sections.PageSetup.RightMargin  = application_St.CentimetersToPoints((float)Configuration_class.doc_Right_Merge);
                        document_St.Sections.PageSetup.TopMargin    = application_St.CentimetersToPoints((float)Configuration_class.doc_Top_Merge);
                        document_St.Sections.PageSetup.BottomMargin = application_St.CentimetersToPoints((float)Configuration_class.doc_Bottom_Merge);
                        //Присвоение текстового значения в абзац
                        range.Text = Configuration_class.Organization_Name;
                        //Выравнивание
                        range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter;
                        //Интервалы в абзаце
                        range.ParagraphFormat.SpaceAfter      = 1;
                        range.ParagraphFormat.SpaceBefore     = 1;
                        range.ParagraphFormat.LineSpacingRule = word.WdLineSpacing.wdLineSpaceSingle;
                        //Шрифт
                        range.Font.Name = "Times New Roman";
                        range.Font.Size = 12;
                        //Параграф (один Enter)
                        document_St.Paragraphs.Add();
                        document_St.Paragraphs.Add();
                        document_St.Paragraphs.Add();
                        //Название документа
                        word.Paragraph Document_Name = document_St.Paragraphs.Add();
                        //Настройка параграфа
                        Document_Name.Format.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter;
                        Document_Name.Range.Font.Name  = "Times New Roman";
                        Document_Name.Range.Font.Size  = 16;
                        Document_Name.Range.Text       = "Выгрузка чека";
                        document_St.Paragraphs.Add();
                        document_St.Paragraphs.Add();
                        document_St.Paragraphs.Add();
                        //Создание таблицы
                        word.Paragraph statparg   = document_St.Paragraphs.Add();
                        word.Table     stat_table = document_St.Tables.Add(statparg.Range, table.Rows.Count, table.Columns.Count);
                        //Настройка таблицы
                        stat_table.Borders.InsideLineStyle       = word.WdLineStyle.wdLineStyleSingle;
                        stat_table.Borders.OutsideLineStyle      = word.WdLineStyle.wdLineStyleSingle;
                        stat_table.Rows.Alignment                = word.WdRowAlignment.wdAlignRowCenter;
                        stat_table.Range.Cells.VerticalAlignment = word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                        stat_table.Range.Font.Size               = 11;
                        stat_table.Range.Font.Name               = "Times New Roman";
                        //Заполнение таблицы
                        for (int row = 1; row <= table.Rows.Count; row++)
                        {
                            for (int col = 1; col <= table.Columns.Count; col++)
                            {
                                stat_table.Cell(row, col).Range.Text = table.Rows[row - 1][col - 1].ToString();
                            }
                        }
                        document_St.Paragraphs.Add();
                        document_St.Paragraphs.Add();
                        document_St.Paragraphs.Add();
                        //Строка даты создания
                        word.Paragraph Footparg = document_St.Paragraphs.Add();
                        Footparg.Range.Text = string.Format("Дата создания \t\t\t{0}", DateTime.Now.ToString());
                    }
                    catch
                    {
                    }
                    finally
                    {
                        try
                        {
                            //Сохранение документа
                            document_St.SaveAs2(name + "DOC", word.WdSaveFormat.wdFormatDocument);
                            //Закрытие документа
                            document_St.Close(SaveChanges: false);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                        application_St.Quit();
                    }
                    break;
                }
                break;

            case (false):
                MessageBox.Show("Введите название документа");
                break;
            }
        }
Exemplo n.º 48
0
 public override void Dispose()
 {
     _wordDocument?.Quit(ref _missing, ref _missing, ref _missing);
     _wordDocument = null;
 }
Exemplo n.º 49
0
        /// <summary>
        /// Performs the playback of actions in this module.
        /// </summary>
        /// <remarks>You should not call this method directly, instead pass the module
        /// instance to the <see cref="TestModuleRunner.Run(ITestModule)"/> method
        /// that will in turn invoke this method.</remarks>
        void ITestModule.Run()
        {
            Mouse.DefaultMoveTime        = 300;
            Keyboard.DefaultKeyPressTime = 100;
            Delay.SpeedFactor            = 1.0;

            // This is dependent on the itext 7 community NuGet package reference

            string src = @"C:\Users\edgewords\Documents\czechexamples\Property_contract_sample.pdf";

            //Read PDF
            PdfReader   reader = new PdfReader(src);
            PdfDocument pdf    = new PdfDocument(reader);
            string      text   = string.Empty;

            //Iterate over all pages
            for (int page = 1; page <= pdf.GetNumberOfPages(); page++)
            {
                PdfPage myPage = pdf.GetPage(page);
                //Extract plain text
                text += PdfTextExtractor.GetTextFromPage(myPage);
            }
            reader.Close();

            //Find specific text
            int pos = text.IndexOf("Spoluúčast") + 10;

            //Get next 10 characters
            Ranorex.Report.Info(text.Substring(pos, 10));



            //*************************//
            // Now for the word document. Open the word document, then save as text only, you could then open it and read from it
            // using normal System.IO library

            Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
            Document document = null;

            application.Visible = false;
            object missing  = System.Reflection.Missing.Value;
            object readOnly = false;

            document = application.Documents.Open(@"C:\Users\edgewords\Documents\czechexamples\Property_policy_sample.doc", ref missing, ref readOnly);
            //document.ExportAsFixedFormat(@"C:\Users\edgewords\Documents\czechexamples\Property_policy_sample.pdf", WdExportFormat.wdExportFormatPDF);
            document.SaveAs(@"C:\Users\edgewords\Documents\czechexamples\Property_policy_sample.txt", 2);
            Ranorex.Report.Info(document.Range(1, document.Characters.Count).Text);
            application.ActiveDocument.Close();
            application.Quit();



            // Try to open the Xfa dynamic acrobat form as xml document

            // https://csharp.hotexamples.com/examples/iTextSharp.text.pdf/XfaForm/-/php-xfaform-class-examples.html


            PdfReader   newreader = new PdfReader(@"C:\Users\edgewords\Documents\czechexamples\eForm_example.pdf");
            PdfDocument pdfDoc    = new PdfDocument(newreader);

            XfaForm xfa = new XfaForm(pdfDoc);

            if (xfa.IsXfaPresent())
            {
                XDocument myXMLDoc             = xfa.GetDomDocument();
                IEnumerable <XElement> mylist  = myXMLDoc.Descendants("CONTRACT_ID");
                List <XElement>        mylistt = mylist.ToList <XElement>();
                Report.Info(mylistt[0].Value);

                // or if more than one, you can cycle through:

                /***
                 * foreach (XElement theEl in mylist){
                 *      Report.Info(theEl.Value);
                 * }
                 *
                 ***/
            }

            else
            {
                PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, false);
                IDictionary <String, PdfFormField> fields = form.GetFormFields();
                PdfFormField toSet;
                fields.TryGetValue("CONTRACT_ID", out toSet);

                Report.Info(toSet.GetValueAsString());
            }

            //reader.Close();
        }
Exemplo n.º 50
0
        /// <summary>
        /// COM from 4.0
        /// </summary>
        /// <param name="missing"></param>
        /// <param name="excel"></param>
        /// <param name="wb"></param>
        /// <param name="ws"></param>
        /// <param name="range"></param>
        /// <param name="sumValues"></param>
        /// <param name="word"></param>
        /// <param name="visible"></param>
        /// <param name="filename"></param>
        /// <param name="doc"></param>
        /// <param name="p1"></param>
        /// <param name="headingStyle"></param>
        /// <param name="p2"></param>
        /// <param name="saveChanges"></param>
        private static void DoCOMIntroduction_4()
        {
            Microsoft.Office.Interop.Excel.Application excel;
            Workbook  wb;
            Worksheet ws;

            Microsoft.Office.Interop.Excel.Range range;
            double sumValues;

            Microsoft.Office.Interop.Word.Application word;
            object   visible;
            object   filename;
            Document doc;

            Microsoft.Office.Interop.Word.Paragraph p1;
            object headingStyle;

            Microsoft.Office.Interop.Word.Paragraph p2;
            object saveChanges;


            excel         = new Microsoft.Office.Interop.Excel.Application();
            excel.Visible = true;

            wb = excel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
            ws = wb.Worksheets[1];

            range         = ws.get_Range("A1", "A10");
            range.Formula = "=RANDBETWEEN(1, 10)";

            excel.Cells[11, 1].Value = "=SUM(A1:A10)";

            // Com indexing
            sumValues = (double)ws.Cells[11, 1].Value;



            visible = true;

            filename = System.IO.Path.Combine(Environment.GetFolderPath(
                                                  Environment.SpecialFolder.Desktop), @"interop_.docx");

            if (!File.Exists(filename.ToString()))
            {
                File.Create(filename.ToString());
            }

            word         = new Microsoft.Office.Interop.Word.Application();
            word.Visible = true;
            // optional parameters and not reference required
            doc = word.Documents.Open(filename, Visible: true);


            p1           = doc.Paragraphs.Add();
            headingStyle = "Cím";
            //p1.Range.set_Style(re
            p1.Range.Text = "Az excel által számított érték:";
            p1.Range.InsertParagraphAfter();


            p2            = doc.Paragraphs.Add(Type.Missing);
            p2.Range.Text = sumValues.ToString();
            p2.Range.InsertParagraphAfter();

            doc.SaveAs(ref filename);

            saveChanges = true;
            word.Quit(ref saveChanges);
            excel.Quit();
        }
        public OpenMSWordAndCreatePdfs(
            List <CockleFile> filesSelectedForConversion,
            string original_progress_report,
            IProgress <string> progress,
            CancellationToken cancellationToken,
            bool exceptionThrownInAwait)
        {
            origProgressReport     = original_progress_report;
            Progress               = progress;
            CancellationToken      = cancellationToken;
            ExceptionThrownInAwait = exceptionThrownInAwait;

            //instantiate Word Application & Document
            Word.Application app = new Word.Application();
            //var app = (Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
            app.Visible = true;
            Word.Document doc = null;

            //System.Runtime.InteropServices.Marshal;

            //get original printer & prepare to create PDF
            var current_printer   = app.ActivePrinter;
            var adobe_pdf_printer = "Adobe PDF";

            app.ActivePrinter = adobe_pdf_printer;

            // collection of special class to track files
            FilesPrintedSuccessfully = new List <FilePrintedSuccessfully>();

            try
            {
                // counter to track files printed
                int i = 0;
                var tempFilesSavedToScratch = new List <string>();
                // loop through files
                foreach (CockleFile fileSelected in filesSelectedForConversion)
                {
                    // cancel if requested
                    try { CancellationToken.ThrowIfCancellationRequested(); }
                    catch (OperationCanceledException) { ExceptionThrownInAwait = true; throw new OperationCanceledException(); }

                    // catch pdf files saved to Current
                    if (System.IO.Path.GetExtension(fileSelected.FullName).Equals(".pdf"))
                    {
                        // don't try to open, just save to scratch and add to list
                        var pdfFileInCurrent = System.IO.Path.Combine(@"C:\scratch", System.IO.Path.GetFileName(fileSelected.FullName));
                        System.IO.File.Copy(fileSelected.FullName, pdfFileInCurrent);
                        // here, just a string & no cover length
                        FilesPrintedSuccessfully.Add(
                            new FilePrintedSuccessfully
                        {
                            CockleFile    = null,
                            TempWordFile  = null,
                            PdfFilename   = pdfFileInCurrent,
                            Filetype      = SourceFileTypeEnum.Camera_Ready, // may have to adjust type here
                            LengthOfCover = null
                        });
                        continue;
                    }

                    // Open docx files in Word, clean up, and convert
                    try
                    {
                        doc = app.Documents.Open(FileName: fileSelected.FullName, ReadOnly: true);
                    }
                    catch
                    {
                        System.Diagnostics.Debug.WriteLine($"{fileSelected.FullName} failed to open");
                    }

                    // save to c:\scratch (overwriting existing files)
                    var tempFileSavedToScratch = System.IO.Path.Combine(@"c:\scratch", System.IO.Path.GetFileName(fileSelected.FullName));
                    if (System.IO.File.Exists(tempFileSavedToScratch))
                    {
                        System.IO.File.Delete(tempFileSavedToScratch);
                    }
                    doc.SaveAs2(FileName: tempFileSavedToScratch);
                    tempFilesSavedToScratch.Add(tempFileSavedToScratch);

                    // ctrl shift f9 (had problem with links in index: removes links from main story)
                    Word.Range r = doc.StoryRanges[Word.WdStoryType.wdMainTextStory];
                    r.Fields.Unlink();

                    // delete footer
                    MicrosoftWordStaticClass.WordDoc_DeleteFooters(fileSelected, doc);

                    // line to capture length of cover
                    int?lengthOfCover = null;
                    if (fileSelected.FileType == SourceFileTypeEnum.Cover)
                    {
                        lengthOfCover = MicrosoftWordStaticClass.CaptureCoverLength(doc);
                    }

                    // cancel if requested
                    try { CancellationToken.ThrowIfCancellationRequested(); }
                    catch (OperationCanceledException) { ExceptionThrownInAwait = true; throw new OperationCanceledException(); }

                    // print to pdf
                    var newPdfConvertedFromWord = string.Empty;
                    newPdfConvertedFromWord = MicrosoftWordStaticClass.PrintToFile(app, doc.FullName);

                    doc.SaveAs2(FileName: tempFileSavedToScratch);

                    //AdobePDFMakerForOffice.PDFMaker pmkr = null;
                    //Microsoft.Office.Core.COMAddIn add_in = null;
                    //newPdfConvertedFromWord = MicrosoftWordStaticClass.PrintToFileWithPdfMaker(app, add_in, doc.FullName);
                    // report progress to gui
                    var report = original_progress_report +
                                 $"\nNow creating:\n{System.IO.Path.GetFileName(newPdfConvertedFromWord)}";
                    Progress.Report(report);

                    // add to files_printed list
                    FilesPrintedSuccessfully.Add(
                        new FilePrintedSuccessfully
                    {
                        CockleFile    = fileSelected,
                        TempWordFile  = tempFileSavedToScratch,
                        PdfFilename   = newPdfConvertedFromWord,
                        Filetype      = SourceFileTypeEnum.Unrecognized,
                        LengthOfCover = lengthOfCover
                    });

                    // close document & delete temp file
                    doc.Close(SaveChanges: Word.WdSaveOptions.wdDoNotSaveChanges);
                    // increment counter
                    i++;
                }// end for loop to convert each files

                // report progress to gui
                var report2 = original_progress_report + "\nPrinting  ...";
                Progress.Report(report2);

                var sw = new System.Diagnostics.Stopwatch();
                sw.Start();

                // after printing each doc: Leave Word open until printing complete
                while (app.BackgroundPrintingStatus > 0)
                {
                    try
                    {
                        // files not yet printed
                        var tempcount = FilesPrintedSuccessfully.Where(x => System.IO.File.Exists(x.PdfFilename)).Count();
                        // report progress to gui
                        var elapsedtime_toFiveSecs = (sw.ElapsedMilliseconds / 1000) / 5 * 5;
                        var report3 = original_progress_report
                                      + $"\nPrinted: {tempcount} / {FilesPrintedSuccessfully.Count} files"
                                      + $"\nSeconds elapsed: {elapsedtime_toFiveSecs}";
                        Progress.Report(report3);

                        // this seems to jolt COM into printing the files !!!
                        Thread.Sleep(100);

                        CancellationToken.ThrowIfCancellationRequested();
                    }
                    catch (OperationCanceledException) { ExceptionThrownInAwait = true; throw new OperationCanceledException(); }
                }
                while (app.BackgroundSavingStatus != 0) // this is probably unnecessary !!!
                {
                    try { CancellationToken.ThrowIfCancellationRequested(); }
                    catch (OperationCanceledException) { ExceptionThrownInAwait = true; throw new OperationCanceledException(); }
                }
                // cycle through to make sure all exist and Word is not actively printing:
                while (!FilesPrintedSuccessfully.TrueForAll(x => System.IO.File.Exists(x.PdfFilename)))
                {
                    try { CancellationToken.ThrowIfCancellationRequested(); }
                    catch (OperationCanceledException) { ExceptionThrownInAwait = true; throw new OperationCanceledException(); }
                }

                // delete temp files
                tempFilesSavedToScratch.ForEach(x => System.IO.File.Delete(x));
            }
            catch { } /* skip catch so that I can clean up files left in scratch*/
            finally
            {
                app.ActivePrinter = current_printer;
                app?.Quit();
                if (null != doc)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
                }
                if (null != app)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
                }
                doc = null;
                app = null;
                GC.Collect();
            }
            if (exceptionThrownInAwait)
            {
                // close app
                app.ActivePrinter = current_printer;
                app?.Quit();
                if (null != doc)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
                }
                if (null != app)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
                }
                doc = null;
                app = null;
                GC.Collect();
                //System.Runtime.InteropServices.
                // try to clean folder
                FilesPrintedSuccessfully.ForEach(f =>
                {
                    if (System.IO.File.Exists(f.PdfFilename))
                    {
                        System.IO.File.Delete(f.PdfFilename);
                    }
                    if (System.IO.File.Exists(f.TempWordFile))
                    {
                        System.IO.File.Delete(f.TempWordFile);
                    }
                });
                FilesPrintedSuccessfully = null;
            }
            // report progress to gui
            Progress.Report(original_progress_report);
        }
Exemplo n.º 52
0
        private void print_button_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
            Document doc = app.Documents.Add(Visible: true);


            DataRow[] productInStockRows = databaseForLabDataSet.ProductInStock.Select("NumOfStock =" + numTextBox.Text);
            DataRow[] stockRow           = databaseForLabDataSet.Stock.Select("Num =" + numTextBox.Text);
            DataRow[] productRow         = databaseForLabDataSet.Product.Select();



            var r0 = doc.Paragraphs.Add();

            r0.Range.Bold      = 1;
            r0.Range.Font.Size = 20;
            string text = "Инвентарь склада №" + stockRow[0].ItemArray[0];

            r0.Range.Text = text;
            r0.Range.InsertParagraphAfter();

            var r = doc.Paragraphs.Add();

            r.Range.Bold  = 0;
            r.Range.Text += "\nАдрес: " + stockRow[0].ItemArray[1] +
                            "\nВремя создания отчета: " + DateTime.Now;
            r.Range.InsertParagraphAfter();

            var   r2 = doc.Paragraphs.Add();
            Table t  = doc.Tables.Add(r2.Range, productInStockRows.Length + 1, 6);

            t.Borders.Enable = 1;
            t.Rows[1].Cells[1].Range.Text = "Название товара";
            t.Rows[1].Cells[2].Range.Text = "Вид товара";
            t.Rows[1].Cells[3].Range.Text = "Единица измерения";
            t.Rows[1].Cells[4].Range.Text = "Количество";
            t.Rows[1].Cells[5].Range.Text = "Цена за единицу";
            t.Rows[1].Cells[6].Range.Text = "Сумма";
            double sum = 0;

            foreach (Row row in t.Rows)
            {
                if (row.Index > 1)
                {
                    DataRow[] productRows = databaseForLabDataSet.Product.Select("Name = '" + productInStockRows[row.Index - 2].ItemArray[0].ToString() + "'");
                    row.Cells[1].Range.Text = productInStockRows[row.Index - 2].ItemArray[0].ToString();
                    row.Cells[2].Range.Text = productRows[0].ItemArray[3].ToString();
                    row.Cells[3].Range.Text = productRows[0].ItemArray[1].ToString();
                    row.Cells[4].Range.Text = productInStockRows[row.Index - 2].ItemArray[1].ToString();
                    row.Cells[5].Range.Text = productRows[0].ItemArray[2].ToString();
                    row.Cells[6].Range.Text = (Convert.ToDouble(productInStockRows[row.Index - 2].ItemArray[1]) * Convert.ToDouble(productRows[0].ItemArray[2])).ToString();
                    sum += (Convert.ToDouble(productInStockRows[row.Index - 2].ItemArray[1]) * Convert.ToDouble(productRows[0].ItemArray[2]));
                }
            }
            r2.Range.InsertParagraphAfter();
            var r3 = doc.Paragraphs.Add();

            r3.Range.Text = "Итого: " + sum;
            r3.Range.Bold = 1;
            doc.Save();

            app.Quit();
        }
Exemplo n.º 53
0
        /// <summary>
        ///  Convert existing Word document to a specified extension and returns path to file
        /// </summary>
        public static string ConvertWord(string DocFilePathRaw, string NewFileName, string DirectoryToSaveRaw,
                                         string NewFileExtension, Word.WdSaveFormat NewFileFormat)
        {
            //calculate file name with exxtension
            if (!NewFileName.EndsWith("." + NewFileExtension))
            {
                NewFileName = NewFileName + "." + NewFileExtension;
            }

            //get absolute filePaths for both the new directory and the old file path
            string directoryToSave = String.IsNullOrEmpty(DirectoryToSaveRaw) ? Directory.GetCurrentDirectory() : Path.GetFullPath(DirectoryToSaveRaw);
            string docFilePath     = Path.GetFullPath(DocFilePathRaw);

            //calculate new File Path
            string newFilePath = Path.Combine(directoryToSave, NewFileName);



            // Open and init the Word Application.
            Word._Application word_app = new Word.Application();
            word_app.Visible       = false;
            word_app.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
            bool save_changes = false;


            //performing conversion operation
            try
            {
                //initialize settings
                bool   confirm_conversions = false;
                bool   read_only           = true;
                bool   add_to_recent_files = false;
                object format = 0;

                //open the document
                Word._Document word_doc = word_app.Documents.Open(docFilePath, confirm_conversions, read_only, add_to_recent_files, Type.Missing,
                                                                  Type.Missing, Type.Missing, Type.Missing,
                                                                  Type.Missing, Type.Missing, Type.Missing,
                                                                  Type.Missing, Type.Missing, Type.Missing,
                                                                  Type.Missing, Type.Missing);

                word_doc.SaveAs(newFilePath, NewFileFormat,
                                Type.Missing, Type.Missing, Type.Missing,
                                Type.Missing, Type.Missing, Type.Missing,
                                Type.Missing, Type.Missing, Type.Missing,
                                Type.Missing, Type.Missing, Type.Missing,
                                Type.Missing, Type.Missing);

                //Close the document
                word_doc.Close(save_changes, Type.Missing, Type.Missing);
            }
            catch
            {
                throw;
            }
            finally
            {
                //Close the App
                word_app.Quit();
                GC.Collect();
            }
            return(newFilePath);
        }
Exemplo n.º 54
0
 public void Close()
 {
     application?.Quit(SaveChanges: false);
 }
        private void goFontsCharsToPics()
        {
            try
            {
                string chDir = DirFiles.searchRootDirChange(textBox1.Text);
                if (chDir == "")
                {
                    MessageBox.Show("並無此目錄,請確認後再執行!", "",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else if (textBox1.Text != chDir)
                {
                    textBox1.Text = chDir;
                }

                BackColor    = Color.Gray;
                this.Enabled = false; button1.Enabled = false;
                string           fontname = textBox2.Text;
                WinWord.Document wd       = new fontsPics().getFontCharacterset
                                                (fontname);
                if (wd != null)
                {
                    BackColor = Color.Red;
                    string picFolder = textBox1.Text;
                    if (picFolder.IndexOf(fontname) == -1)
                    {
                        picFolder += ("\\" + fontname + "\\");
                    }
                    powerPnt.Presentation ppt =
                        new fontsPics().prepareFontPPT(fontname,
                                                       float.Parse(textBox3.Text));
                    new fontsPics().addCharsSlidesExportPng(wd, ppt, picFolder,
                                                            Int32.Parse(textBox4.Text));
                    FileInfo            wdf   = new FileInfo(wd.FullName);
                    WinWord.Application wdApp = wd.Application;
                    wd.Close();//執行完成,關閉因程式而開啟的Word
                    if (!wdApp.UserControl)
                    {
                        wdApp.Quit();
                    }
                    //移動已完成的檔案到已完成資料夾下
                    string destFilename = wdf.Directory.FullName
                                          + "\\done已完成\\" + wdf.Name;
                    if (!File.Exists(destFilename))
                    {
                        wdf.MoveTo(destFilename);
                    }
                    if (BackColor != Color.BurlyWood)//若字圖與字型字數無不同,才顯示綠底色
                    {
                        BackColor = Color.Green;
                    }
                    warnings.playSound();
                }
                this.Enabled = true; button1.Enabled = true;
            }
            catch (Exception e)
            {
                printExceptiontoDoc(e);
                this.Enabled = true; button1.Enabled = true;
            }
        }
Exemplo n.º 56
0
        private void CreateDocumentInternal(IEnumerable <Request> report, string engnam)
        {
            var reportItemsList = report.ToList();
            var winword         = new Microsoft.Office.Interop.Word.Application();

            winword.ShowAnimation = false;

            object missing = System.Reflection.Missing.Value;

            winword.Visible = false;

            var document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);

            foreach (Section section in document.Sections)
            {
                Range headerRange = section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                headerRange.Fields.Add(headerRange, WdFieldType.wdFieldPage);
                headerRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                headerRange.Font.ColorIndex           = WdColorIndex.wdBlue;
                headerRange.Font.Size = 25;
                headerRange.Text      = $"Звіт за замовленнями інженера {engnam}";
            }

            var para1 = document.Content.Paragraphs.Add(ref missing);

            para1.Range.InsertParagraphAfter();
            para1.Range.Text = "!!!!!!!!!!!!!!!!";

            Table firstTable = document.Tables.Add(para1.Range, reportItemsList.Count + 1, 4, ref missing, ref missing);

            firstTable.Borders.Enable = 1;
            foreach (Row row in firstTable.Rows)
            {
                foreach (Cell cell in row.Cells)
                {
                    //Header row
                    if (cell.RowIndex == 1)
                    {
                        cell.Range.Text      = Headers[cell.ColumnIndex - 1];
                        cell.Range.Font.Bold = 1;
                        //other format properties goes here
                        cell.Range.Font.Name = "verdana";
                        cell.Range.Font.Size = 10;
                        //cell.Range.Font.ColorIndex = WdColorIndex.wdGray25;
                        cell.Shading.BackgroundPatternColor = WdColor.wdColorGray25;
                        //Center alignment for the Header cells
                        cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                        cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                    }
                    //Data row
                    else
                    {
                        var    currItem = reportItemsList[cell.RowIndex - 2];
                        string text     = null;
                        switch (cell.ColumnIndex)
                        {
                        case 1:
                            text = currItem.Request_Name.ToString();
                            break;

                        case 2:
                            text = currItem.StateReq.GetDescription();
                            break;

                        case 3:
                            text = currItem.Code_edrpou.ToString();
                            break;

                        case 4:
                            text = currItem.Approximate_Duration.ToString();
                            break;
                        }
                        cell.Range.Text = text;
                    }
                }
            }

            //Save the document
            document.Activate();
            try
            {
                winword.Visible = true;
                document.Close(ref missing, ref missing, ref missing);
            }
            catch (Exception)
            {
            }
            winword.Quit(ref missing, ref missing, ref missing);
        }
Exemplo n.º 57
0
        public async void CreateProtocol()
        {
            try
            {
                await Task.Run(() =>
                {
                    procPers = 0F;

                    string path           = @"C:\Protocols";
                    DirectoryInfo dirInfo = new DirectoryInfo(path);
                    if (!dirInfo.Exists)
                    {
                        dirInfo.Create();
                    }
                    if (File.Exists(@"C:\Protocols\TemplayProtocol.docx"))
                    {
                        File.Delete(@"C:\Protocols\TemplayProtocol.docx");
                    }
                    File.Copy("TemplayProtocol.docx", @"C:\Protocols\TemplayProtocol.docx");
                    wordApp = new Microsoft.Office.Interop.Word.Application();

                    wordApp.Visible  = false;
                    var wordDocument = wordApp.Documents.Open(@"C:\Protocols\TemplayProtocol.docx");
                    procPers        += 5;
                    ReplaceWordStub("{productName}", prodName, ref wordDocument);
                    ReplaceWordStub("{productMade}", modName, ref wordDocument);
                    ReplaceWordStub("{exspDate}", expDate, ref wordDocument);
                    ReplaceWordStub("{expDate}", expDate, ref wordDocument);
                    ReplaceWordStub("{exspPlace}", expPlace, ref wordDocument);
                    ReplaceWordStub("{exspType}", expType, ref wordDocument);
                    ReplaceWordStub("{exspClass}", expClass, ref wordDocument);
                    ReplaceWordStub("{client}", client, ref wordDocument);
                    ReplaceWordStub("{prot}", prot, ref wordDocument);
                    ReplaceWordStub("{ModeNumb}", pumpNumb, ref wordDocument);
                    ReplaceWordStub("{protNumb}", protNumb, ref wordDocument);
                    ReplaceWordStub("{OrderNum}", orderNum, ref wordDocument);
                    ReplaceWordStub("{OrderNumb}", orderNumb, ref wordDocument);
                    ReplaceWordStub("{D1}", string.Format("{0:0.000}", d1In), ref wordDocument);
                    ReplaceWordStub("{D2}", string.Format("{0:0.000}", d2Out), ref wordDocument);
                    ReplaceWordStub("{DWork}", string.Format("{0:0.000}", dWork), ref wordDocument);
                    ReplaceWordStub("{QNom}", string.Format("{0:0.00}", qNom), ref wordDocument);
                    ReplaceWordStub("{HNom}", string.Format("{0:0.00}", hNom), ref wordDocument);
                    ReplaceWordStub("{SpeedNom}", string.Format("{0}", speedNom), ref wordDocument);
                    ReplaceWordStub("{PowNom}", string.Format("{0:0.00}", powNom), ref wordDocument);
                    ReplaceWordStub("{KPDNom}", string.Format("{0:0.00}", KPDNom), ref wordDocument);
                    ReplaceWordStub("{temH2o}", string.Format("{0:0.00}", TempH2o02), ref wordDocument);
                    ReplaceWordStub("{pltH2o}", string.Format("{0:0.00}", mathConvert.PlotnH20(TempH2o02)), ref wordDocument);
                    ReplaceWordStub("{Psmog}", string.Format("{0:0.00}", Ksmog), ref wordDocument);
                    ReplaceWordStub("{Kvz}", string.Format("{0:0.00}", kVz), ref wordDocument);
                    ReplaceWordStub("{PH}", string.Format("{0:0.00}", pH), ref wordDocument);
                    ReplaceWordStub("{MadeName}", driveMode, ref wordDocument);
                    ReplaceWordStub("{TypeDrive}", driveType, ref wordDocument);
                    ReplaceWordStub("{PowDrive}", string.Format("{0:0.00}", drivePow), ref wordDocument);
                    ReplaceWordStub("{SpeedDrive}", string.Format("{0}", driveSpeed), ref wordDocument);
                    ReplaceWordStub("{PhaseDrive}", string.Format("{0}", drivePhase), ref wordDocument);
                    ReplaceWordStub("{VoltDrive}", string.Format("{0}", driveVolt), ref wordDocument);
                    ReplaceWordStub("{CurrDrive}", string.Format("{0}", driveCurr), ref wordDocument);
                    ReplaceWordStub("{tempAir}", string.Format("{0:0.00}", ZtempAir), ref wordDocument);
                    ReplaceWordStub("{temp}", string.Format("{0:0.00}", TempH2o02), ref wordDocument);
                    ReplaceWordStub("{bp}", string.Format("{0:0.00}", bPress), ref wordDocument);
                    ReplaceWordStub("{Zmd}", string.Format("{0:0.00}", dZm), ref wordDocument);
                    ReplaceWordStub("{Zm1}", string.Format("{0:0.00}", Zm1), ref wordDocument);
                    ReplaceWordStub("{Zm2}", string.Format("{0:0.00}", Zm2), ref wordDocument);
                    procPers += 5;
                    if (set01)
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            if (i > 2)
                            {
                                ReplaceWordStub("{p1-" + i + "}", Point01[i] != 0f ? string.Format("{0:0.00}", Point01[i]) : "", ref wordDocument);
                            }
                            else
                            {
                                ReplaceWordStub("{p1-" + i + "}", Point01[i] != 0f ? string.Format("{0:0}", Point01[i]) : "", ref wordDocument);
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            ReplaceWordStub("{p1-" + i + "}", "", ref wordDocument);
                        }
                    }
                    procPers += 5;
                    if (set02)
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            if (i > 2)
                            {
                                ReplaceWordStub("{p2-" + i + "}", Point02[i] != 0f ? string.Format("{0:0.00}", Point02[i]) : "", ref wordDocument);
                            }
                            else
                            {
                                ReplaceWordStub("{p2-" + i + "}", Point02[i] != 0f ? string.Format("{0:0}", Point02[i]) : "", ref wordDocument);
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            ReplaceWordStub("{p2-" + i + "}", "", ref wordDocument);
                        }
                    }
                    procPers += 5;
                    if (set03)
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            if (i > 2)
                            {
                                ReplaceWordStub("{p3-" + i + "}", Point03[i] != 0f ? string.Format("{0:0.00}", Point03[i]) : "", ref wordDocument);
                            }
                            else
                            {
                                ReplaceWordStub("{p3-" + i + "}", Point03[i] != 0f ? string.Format("{0:0}", Point03[i]) : "", ref wordDocument);
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            ReplaceWordStub("{p3-" + i + "}", "", ref wordDocument);
                        }
                    }
                    procPers += 5;
                    if (set04)
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            if (i > 2)
                            {
                                ReplaceWordStub("{p4-" + i + "}", Point04[i] != 0f ? string.Format("{0:0.00}", Point04[i]) : "", ref wordDocument);
                            }
                            else
                            {
                                ReplaceWordStub("{p4-" + i + "}", Point04[i] != 0f ? string.Format("{0:0}", Point04[i]) : "", ref wordDocument);
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            ReplaceWordStub("{p4-" + i + "}", "", ref wordDocument);
                        }
                    }
                    procPers += 5;
                    if (set05)
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            if (i > 2)
                            {
                                ReplaceWordStub("{p5-" + i + "}", Point05[i] != 0f ? string.Format("{0:0.00}", Point05[i]) : "", ref wordDocument);
                            }
                            else
                            {
                                ReplaceWordStub("{p5-" + i + "}", Point05[i] != 0f ? string.Format("{0:0}", Point05[i]) : "", ref wordDocument);
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            ReplaceWordStub("{p5-" + i + "}", "", ref wordDocument);
                        }
                    }
                    procPers += 5;
                    if (set06)
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            if (i > 2)
                            {
                                ReplaceWordStub("{p6-" + i + "}", Point06[i] != 0f ? string.Format("{0:0.00}", Point06[i]) : "", ref wordDocument);
                            }
                            else
                            {
                                ReplaceWordStub("{p6-" + i + "}", Point06[i] != 0f ? string.Format("{0:0}", Point06[i]) : "", ref wordDocument);
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            ReplaceWordStub("{p6-" + i + "}", "", ref wordDocument);
                        }
                    }
                    procPers += 5;
                    if (set07)
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            if (i > 2)
                            {
                                ReplaceWordStub("{p7-" + i + "}", Point07[i] != 0f ? string.Format("{0:0.00}", Point07[i]) : "", ref wordDocument);
                            }
                            else
                            {
                                ReplaceWordStub("{p7-" + i + "}", Point07[i] != 0f ? string.Format("{0:0}", Point07[i]) : "", ref wordDocument);
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            ReplaceWordStub("{p7-" + i + "}", "", ref wordDocument);
                        }
                    }
                    procPers += 5;
                    if (set08)
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            if (i > 2)
                            {
                                ReplaceWordStub("{p8-" + i + "}", Point08[i] != 0f ? string.Format("{0:0.00}", Point08[i]) : "", ref wordDocument);
                            }
                            else
                            {
                                ReplaceWordStub("{p8-" + i + "}", Point08[i] != 0f ? string.Format("{0:0}", Point08[i]) : "", ref wordDocument);
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            ReplaceWordStub("{p8-" + i + "}", "", ref wordDocument);
                        }
                    }
                    procPers += 5;
                    if (set09)
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            if (i > 2)
                            {
                                ReplaceWordStub("{p9-" + i + "}", Point09[i] != 0f ? string.Format("{0:0.00}", Point09[i]) : "", ref wordDocument);
                            }
                            else
                            {
                                ReplaceWordStub("{p9-" + i + "}", Point09[i] != 0f ? string.Format("{0:0}", Point09[i]) : "", ref wordDocument);
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            ReplaceWordStub("{p9-" + i + "}", "", ref wordDocument);
                        }
                    }
                    procPers += 5;
                    if (set10)
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            if (i > 2)
                            {
                                ReplaceWordStub("{p10-" + i + "}", Point10[i] != 0f ? string.Format("{0:0.00}", Point10[i]) : "", ref wordDocument);
                            }
                            else
                            {
                                ReplaceWordStub("{p10-" + i + "}", Point10[i] != 0f ? string.Format("{0:0}", Point10[i]) : "", ref wordDocument);
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            ReplaceWordStub("{p10-" + i + "}", "", ref wordDocument);
                        }
                    }
                    procPers += 5;
                    if (set11)
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            if (i > 2)
                            {
                                ReplaceWordStub("{p11-" + i + "}", Point11[i] != 0f ? string.Format("{0:0.00}", Point11[i]) : "", ref wordDocument);
                            }
                            else
                            {
                                ReplaceWordStub("{p11-" + i + "}", Point11[i] != 0f ? string.Format("{0:0}", Point11[i]) : "", ref wordDocument);
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            ReplaceWordStub("{p11-" + i + "}", "", ref wordDocument);
                        }
                    }
                    procPers += 5;
                    if (set12)
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            if (i > 2)
                            {
                                ReplaceWordStub("{p12-" + i + "}", Point12[i] != 0f ? string.Format("{0:0.00}", Point12[i]) : "", ref wordDocument);
                            }
                            else
                            {
                                ReplaceWordStub("{p12-" + i + "}", Point12[i] != 0f ? string.Format("{0:0}", Point12[i]) : "", ref wordDocument);
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            ReplaceWordStub("{p12-" + i + "}", "", ref wordDocument);
                        }
                    }
                    procPers += 5;
                    if (set13)
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            if (i > 2)
                            {
                                ReplaceWordStub("{p13-" + i + "}", Point13[i] != 0f ? string.Format("{0:0.00}", Point13[i]) : "", ref wordDocument);
                            }
                            else
                            {
                                ReplaceWordStub("{p13-" + i + "}", Point13[i] != 0f ? string.Format("{0:0}", Point13[i]) : "", ref wordDocument);
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            ReplaceWordStub("{p13-" + i + "}", "", ref wordDocument);
                        }
                    }
                    procPers += 5;
                    if (set14)
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            if (i > 2)
                            {
                                ReplaceWordStub("{p14-" + i + "}", Point14[i] != 0f ? string.Format("{0:0.00}", Point14[i]) : "", ref wordDocument);
                            }
                            else
                            {
                                ReplaceWordStub("{p14-" + i + "}", Point14[i] != 0f ? string.Format("{0:0}", Point14[i]) : "", ref wordDocument);
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i < 33; i++)
                        {
                            ReplaceWordStub("{p14-" + i + "}", "", ref wordDocument);
                        }
                    }
                    procPers += 5;
                    wordDocument.SaveAs2((@"C:\Protocols\ProtNumb" + protNumb + ".pdf"), WdSaveFormat.wdFormatPDF);
                    wordDocument.Close();
                    wordApp.Visible = false;
                    wordApp.Quit();
                    procPers += 5;
                    File.Delete(@"C:\Protocols\TemplayProtocol.docx");
                    Process.Start(@"C:\Protocols\");

                    procPers = 0f;
                });
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemplo n.º 58
0
        public override void ExportDeliveryList()
        {
            // date
            // data_table
            if (!System.IO.File.Exists(DeliveryListTemplate))
            {
                throw new ApplicationException("Файл шаблона для данного документа не найден!");
            }
            var orderRepository = DbManger.GetInstance().GetOrderRepository();
            var customersRepo = DbManger.GetInstance().GetCustomersRepository();

            var albumOrders = orderRepository.GetOrdersForAlbum(WorkingAlbum);
            var groupedAlbumOrders = albumOrders.GroupBy(order => order.CustomerId);

            var albumCustomers = new List<Customer>();
            foreach (IGrouping<int, Order> group in groupedAlbumOrders)
            {
                var customer = customersRepo.GetById(group.Key);
                if (customer == null) continue;

                albumCustomers.Add(customer);
            }
            albumCustomers.Sort((c1, c2) => String.Compare(c1.LastName, c2.LastName, StringComparison.CurrentCultureIgnoreCase));

            var report = new StringBuilder();
            report.AppendLine(String.Format("Лист доставки от {0}", DateTime.Now.ToLongDateString()).ToUpper());
            report.AppendLine();

            Word.Application word;
            try
            {
                word = new Word.Application();
            }
            catch (Exception e)
            {
                m_log.ErrorException(e);
                throw new ApplicationException("Не удалось запустить MS Word. Пожалуйста удостоверьтесь, что установлена версия MS MSWord не ниже 2007.");
            }

            var doc = word.Documents.Open(DeliveryListTemplate);
            if (doc == null) return;

            if (!doc.Bookmarks.Exists("data_table"))
            {
                m_log.ErrorFormat("Content bookmark 'data_table' not found in template!");
                doc.Close();
                word.Quit();
                throw new ApplicationException(String.Format("Шаблон '{0}' некорректен!", CustomerOrderTemplate));
            }
            var range = doc.Bookmarks["data_table"].Range;
            if (range.Tables.Count == 0)
            {
                m_log.ErrorFormat("Content bookmark 'data_table' is not containing table to fill!");
                doc.Close();
                word.Quit();
                throw new ApplicationException(String.Format("Шаблон '{0}' некорректен!", CustomerOrderTemplate));
            }
            var table = range.Tables[1];

            int counter = 2;
            foreach (Customer customer in albumCustomers)
            {
                IGrouping<int, Order> orders = null;

                var totalItems = 0;
            //                var totalPosition = 0;

                foreach (IGrouping<int, Order> group in groupedAlbumOrders)
                {
                    if (group.Key != customer.Id) continue;
                    orders = group;
                }
                if (orders != null)
                {
                    totalItems += orders.Sum(order => order.Amount);
                }
                if (totalItems == 0)
                {
                    // у покупателя в заказе одни нули - пропускаем
                    continue;
                }

                table.Rows.Add();
                table.Cell(counter, 1).Range.Text = (counter - 1).ToString();
                table.Cell(counter, 2).Range.Text = customer.GetFullName();
                table.Cell(counter, 4).Range.Text = totalItems.ToString();
                table.Cell(counter, 5).Range.Text = string.Format("{0} ({1})", customer.Address, customer.Phone);
                counter++;
            }
            try
            {
                table.Rows[counter].Delete();
            }
            catch (Exception)
            {

            }
            if (doc.Bookmarks.Exists("date"))
            {
                doc.Bookmarks["date"].Range.Text = DateTime.Now.ToLongDateString();
            }

            doc.SaveAs(m_filename);
            doc.Close();
            word.Quit();
        }
Exemplo n.º 59
0
        public override void ExportCustomerOrders(Customer customer)
        {
            if (!System.IO.File.Exists(CustomerOrderTemplate))
            {
                throw new ApplicationException("Файл шаблона для данного документа не найден!");
            }

            const string itemsTableBookmark = @"customer_orders_table";
            const string customerNameBookmark = @"customer_name";
            const string dateBookmark = @"current_date";
            const string clearSumBookmark = @"clear_sum";
            const string comissionSumBookmark = @"comission";
            const string totalSumBookmark = @"total";
            const string addressBookmark = @"customer_address";
            const string deliveryBookmark = @"delivery_value";

            var orderRepo = DbManger.GetInstance().GetOrderRepository();
            var prodRepo = DbManger.GetInstance().GetProductRepository();
            //            var ratesRepo = DbManger.GetInstance().GetRatesRepository();

            //            ManagedRate comission;
            //            try
            //            {
            //                comission = ratesRepo.GetById(customer.AccountTypeId);
            //            }
            //            catch (Exception e)
            //            {
            //                m_log.ErrorException(e);
            //                throw new ApplicationException("Ошибка. Не удалось получить ставку покупателя.");
            //            }
            if(customer.GetCommissionInfo() == null)
                throw new ApplicationException("Ошибка. Не удалось получить ставку покупателя.");

            List<Order> orders;
            try
            {
                orders = orderRepo.GetOrdersForCustomerFromAlbum(customer, WorkingAlbum);
            }
            catch (Exception e)
            {
                m_log.ErrorException(e);
                throw new ApplicationException("Не удалось получить список заказов для покупателя.");
            }

            Word.Application word;
            try
            {
                word = new Word.Application();
            }
            catch (Exception e)
            {
                m_log.ErrorException(e);
                throw new ApplicationException("Не удалось запустить MS Word. Пожалуйста удостоверьтесь, что установлена версия MS MSWord не ниже 2007.");
            }

            // word.Visible = true;
            var doc = word.Documents.Open(CustomerOrderTemplate);
            if (!doc.Bookmarks.Exists(itemsTableBookmark))
            {
                m_log.ErrorFormat("Content bookmark '{0}' not found in template!", itemsTableBookmark);
                doc.Close();
                word.Quit();
                throw new ApplicationException(String.Format("Шаблон '{0}' некорректен!", CustomerOrderTemplate));
            }

            var range = doc.Bookmarks[itemsTableBookmark].Range;
            if (range.Tables.Count == 0)
            {
                m_log.ErrorFormat("Content bookmark '{0}' is not containing table to fill!", itemsTableBookmark);
                doc.Close();
                word.Quit();
                throw new ApplicationException(String.Format("Шаблон '{0}' некорректен!", CustomerOrderTemplate));
            }

            var table = range.Tables[1];
            int row = 2;
            decimal clearSum = 0;
            for (int i = 0; i < orders.Count; i++)
            {
                var order = orders[i];

                if (order.Amount == 0 && !IsIncludingEmpty) continue;

                //string partialIndicator = "";
                Product p;
                try
                {
                    p = prodRepo.GetById(order.ProductId);
                    if (p == null)
                    {
                        continue;
                    }
                    var total = orderRepo.GetProductTotalOrderedAmount(p);
                    if (total < p.MinAmount)
                    {
                        if (!IsIncludingPartial)
                        {
                            continue;
                        }
                       // else partialIndicator = "(!)";
                    }
                }
                catch (Exception e)
                {
                    m_log.ErrorException(e);
                    throw new ApplicationException("Ошибка БД.");
                }

                var title = p.GenericUrl.Length > 0 ? String.Format("{0} ({1})", p.Title, p.GenericUrl) : p.Title;

                table.Rows.Add();
                table.Cell(row, 1).Range.Text = (row - 1).ToString();
                table.Cell(row, 2).Range.Text = title;
                table.Cell(row, 3).Range.Text = p.Price.ToString("C2");
                table.Cell(row, 4).Range.Text = order.Amount.ToString();
                table.Cell(row, 5).Range.Text = (p.Price*order.Amount).ToString("C2");

                clearSum += (p.Price*order.Amount);
                row++;
            }

            try
            {
                table.Rows[row].Delete();
            }
            catch (Exception)
            {

            }

            var comission = customer.GetCommissionInfo();
            var comissionValue = (clearSum*(comission.Rate/100));
            var summary = clearSum*(1 + comission.Rate/100);
            decimal deliveryPrice = 0;

            var delivery = customer.GetDeliveryInfo();
            if (delivery != null && delivery.IsActive)
            {
                if ((delivery.IsConditional &&
                         delivery.MinimumOrderSummaryCondition > summary) ||
                        delivery.IsConditional == false)
                {
                    summary += delivery.Price;
                    deliveryPrice = delivery.Price;
                }
            }

            if (doc.Bookmarks.Exists(customerNameBookmark))
            {
                doc.Bookmarks[customerNameBookmark].Range.Text = customer.GetFullName();
            }
            if (doc.Bookmarks.Exists(dateBookmark))
            {
                doc.Bookmarks[dateBookmark].Range.Text = DateTime.Now.ToLongDateString();
            }
            if (doc.Bookmarks.Exists(clearSumBookmark))
            {
                doc.Bookmarks[clearSumBookmark].Range.Text = String.Format("Сумма: {0:C2}", clearSum);
            }
            if (doc.Bookmarks.Exists(comissionSumBookmark))
            {
                doc.Bookmarks[comissionSumBookmark].Range.Text = String.Format("{0}: {1:C2}", comission.Comment, comissionValue);
            }
            if (doc.Bookmarks.Exists(deliveryBookmark))
            {
                doc.Bookmarks[deliveryBookmark].Range.Text = String.Format("Доставка: {0:C0}", deliveryPrice);
            }
            if (doc.Bookmarks.Exists(totalSumBookmark))
            {
                doc.Bookmarks[totalSumBookmark].Range.Text = String.Format("Итого: {0:C0}", summary);
            }
            if (doc.Bookmarks.Exists(addressBookmark))
            {
                doc.Bookmarks[addressBookmark].Range.Text = customer.Address;
            }

            doc.SaveAs(m_filename);
            doc.Close();
            word.Quit();
        }
Exemplo n.º 60
-1
        private bool ConvertWordDocToXPSDoc(string wordDocName)
        {
            // Create a WordApplication and add Document to it
            Microsoft.Office.Interop.Word.Application wordApplication = new Microsoft.Office.Interop.Word.Application();
            wordApplication.Documents.Add(wordDocName);
            Document doc = wordApplication.ActiveDocument;
            // You must make sure you have Microsoft.Office.Interop.Word.Dll version 12.
            // Version 11 or previous versions do not have WdSaveFormat.wdFormatXPS option
            try
            {
                string xpsDocName = @"http://www.jjgjt.com/download/1.xps";
                doc.SaveAs(xpsDocName, WdSaveFormat.wdFormatXPS);
                wordApplication.Quit();
                //XpsDocument xpsDoc = new XpsDocument(xpsDocName, System.IO.FileAccess.Read);
                XpsDocument xpsDoc = new XpsDocument(xpsDocName, System.IO.FileAccess.Read);

                documentViewer1.Document = xpsDoc.GetFixedDocumentSequence();
                return true;
            }
            catch (Exception exp)
            {
                string str = exp.Message;
                return false;
            }
        }