/// <summary>
        /// Печать акта приёмки заказа
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrint_Click(object sender, EventArgs e)
        {
            var templateFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "акт выдачи оборудования.dotx");

            if (!File.Exists(templateFile))
            {
                throw new Exception("Не найден файл " + templateFile);
            }
            var       oWord           = new Word.Application();
            _Document oDoc            = null;
            var       newTemplateFile = Path.Combine(
                AppDomain.CurrentDomain.BaseDirectory,
                $"Акты выдачи\\акт_выдачи_оборудования_{DateTime.Now:dd.MM.yyyy_HH.mm.ss}_{this.textBoxFIO.Text}.docx");

            try
            {
                oDoc = oWord.Documents.Add(templateFile);
                this.SetTemplate(oDoc);

                oDoc.SaveAs2(FileName: newTemplateFile);
            }
            finally
            {
                oDoc?.Close();
                oWord.Quit();
            }
            MessageBox.Show("Сохранение прошло успешно", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
            Process.Start(newTemplateFile);
        }
Exemplo n.º 2
0
        private void CreateWordDocument()
        {
            _Document oDoc = null;

            try
            {
                Word._Application oWord  = new Word.Application();
                string            source = @"C:\Users\temch\Desktop\Шаблон.dotx";
                oDoc = oWord.Documents.Add(source);
                Word.Bookmarks wBookmarks = oDoc.Bookmarks;
                Word.Range     wRange;
                string[]       arr = { "27", "Tema", "Shevchenko" };
                int            i   = 0;
                foreach (Word.Bookmark mark in wBookmarks)
                {
                    wRange      = mark.Range;
                    wRange.Text = arr[i];
                    i++;
                }
                string pathToSaveObj = @"C:\Users\temch\Desktop\Контракт.docx";
                oDoc.SaveAs2(pathToSaveObj);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                oDoc.Close();
                oDoc = null;
            }
        }
Exemplo n.º 3
0
        void button1_Click(object sender, EventArgs e)
        {
            //var application = new Microsoft.Office.Interop.Word.Application();
            //var document = new Microsoft.Office.Interop.Word.Document();
            _Document oDoc = GetDoc(@"D:\Проект работы с шаблонами\NEW_C_PRJ\test.docx");

            oDoc.SaveAs2(FileName: @"D:\Проект работы с шаблонами\NEW_C_PRJ\test_2.docx");
            oDoc.Close();
        }
        public static void ReplaceMailMergeFields(string dir, string msWordFileName, IMergeFieldsProvider domainObject, string fileSuffix)
        {
            object docName = msWordFileName;

            object missing = Missing.Value;

            // Hide MS Word's window.
            var app = new Application {
                Visible = false
            } as _Application;

            var path = dir + docName as object;

            _Document doc = app.Documents.Open(ref path);

            MailMerge mailMerge = doc.MailMerge;

            // Try to find the field name.

            foreach (MailMergeField f in mailMerge.Fields)
            {
                // Assuming the field code is: MERGEFIELD  "mailMergeFieldName"
                string mailMergeFieldName = f.Code.Text;

                string newValue = domainObject.GetContentsFor(mailMergeFieldName);

                if (!string.IsNullOrWhiteSpace(newValue))
                {
                    f.Select();

                    // Replace selected field with supplied value.

                    app.Selection.TypeText(newValue);
                }
            }

            // Save changes and close MS Word.

            object newName = dir + msWordFileName.Replace(".docx", "") + "-" + fileSuffix + ".docx";

            doc.SaveAs2(ref newName);

            object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;

            doc.Close(ref saveChanges, ref missing, ref missing);

            app.Quit(ref missing, ref missing, ref missing);
        }
Exemplo n.º 5
0
    /// <summary>
    ///     Método responsável por criar um novo documento do Word (DOCX ou DOC).
    /// </summary>
    /// <param name="CaminhoArq">String contendo o caminho + nome + extensão do documento</param>
    /// <param name="FecharWordAoCriar">Valor booleando, onde, 'true' encerra os objetos instanciados</param>
    /// <param name="MostrarWord"><Valor booleano, onde, 'true' mostra o documento/param>
    public void CriaWord(String CaminhoArq, Boolean FecharWordAoCriar, Boolean MostrarWord)
    {
        if (mWord == null)
        {
            throw new NotImplementedException("Word não está propriamente instalado");
        }

        if (String.IsNullOrEmpty(CaminhoArq))
        {
            throw new NotImplementedException("Caminho do arquivo não existe");
        }

        if (System.IO.File.Exists(CaminhoArq))
        {
            throw new System.IO.FileLoadException(String.Format("O arquivo informado '{0}' já existe e não pode ser substituído", CaminhoArq));
        }

        if (!CaminhoArq.ToUpper().StartsWith("\\") && !CaminhoArq.ToUpper().StartsWith("C") && !CaminhoArq.ToUpper().EndsWith(".DOCX") && !CaminhoArq.ToUpper().EndsWith(".DOC"))
        {
            throw new ArgumentOutOfRangeException("Caminho informado não está no formato correto (não é unidade de rede nem unidade local ou não possuí a extensão 'DOCX' ou 'DOC'");
        }

        object misValue = System.Reflection.Missing.Value;

        //Precisei adicionar essa condição pois estava sempre mostrando o Word (I don't know why!!)
        mWord.Visible = MostrarWord;

        mDoc = mWord.Documents.Add(ref misValue, ref misValue, ref misValue, ref misValue);

        mDoc.SaveAs2(CaminhoArq);

        if (FecharWordAoCriar)
        {
            mDoc.Close(true, misValue, misValue);
            //mWord.Quit(ref misValue, ref misValue, ref misValue);

            Marshal.ReleaseComObject(mWord);
            Marshal.ReleaseComObject(mDoc);
        }

        _CaminhoArqWord = CaminhoArq.ToUpper();
        _MostrarWord    = MostrarWord;

        if (_MostrarWord)
        {
            AbrirWord();
        }
    }
Exemplo n.º 6
0
        public void MergeFieldsInWordDoc(string sourcePath, IDocumentMergeFieldsProvider sourceObject, string destinationPath)
        {
            object missing = Missing.Value;

            // Hide MS Word's window.
            Application app = new Application {
                Visible = false
            };

            var       path = sourcePath as object;
            _Document doc  = app.Documents.Open(ref path);


            MailMerge mailMerge = doc.MailMerge;

            foreach (MailMergeField f in mailMerge.Fields)
            {
                // Assuming the field code is: MERGEFIELD  "mailMergeFieldName"

                string fieldName = f.Code.Text;

                string newValue = GetValueForMergeField(sourceObject, fieldName);

                if (!string.IsNullOrWhiteSpace(newValue))
                {
                    f.Select();

                    // Replace selected field with supplied value.

                    app.Selection.TypeText(newValue);
                }
            }

            // Save changes and close MS Word.

            object newName = destinationPath as object;

            doc.SaveAs2(ref newName);

            object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;

            doc.Close(ref saveChanges, ref missing, ref missing);

            //TODO: Fix  -  check with Stef
            //app.Quit(ref missing, ref missing, ref missing);
        }
Exemplo n.º 7
0
 async private void CreateWordDocument()
 {
     await Task.Run(() =>
     {
         _Document oDoc          = null;
         Word._Application oWord = new Word.Application();
         try
         {
             string source = @"C:\Users\temch\Desktop\Договор.dotx";
             oDoc          = oWord.Documents.Add(source);
             Word.Range markRange;
             oDoc.Bookmarks["NumberDocument"].Range.Text = DocParameters[0];
             markRange      = oDoc.Bookmarks["Day"].Range;
             markRange.Text = DocParameters[1];
             markRange      = oDoc.Bookmarks["Month"].Range;
             markRange.Text = DocParameters[2];
             markRange      = oDoc.Bookmarks["Year"].Range;
             markRange.Text = DocParameters[3];
             markRange      = oDoc.Bookmarks["Fio"].Range;
             markRange.Text = DocParameters[4];
             markRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
             markRange.Underline = WdUnderline.wdUnderlineSingle;
             markRange           = oDoc.Bookmarks["SumIncome"].Range;
             markRange.Text      = DocParameters[5];
             markRange.Underline = WdUnderline.wdUnderlineSingle;
             markRange           = oDoc.Bookmarks["PeriodIncome"].Range;
             markRange.Text      = DocParameters[6];
             markRange.Underline = WdUnderline.wdUnderlineSingle;
             markRange           = oDoc.Bookmarks["DateEndIncome"].Range;
             markRange.Text      = DocParameters[7];
             markRange.Underline = WdUnderline.wdUnderlineSingle;
             markRange           = oDoc.Bookmarks["Percent"].Range;
             markRange.Text      = DocParameters[8];
             markRange.Underline = WdUnderline.wdUnderlineSingle;
             markRange           = oDoc.Bookmarks["NumberAccount"].Range;
             markRange.Text      = DocParameters[9];
             markRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
             markRange.Underline  = WdUnderline.wdUnderlineSingle;
             markRange            = oDoc.Bookmarks["FioUser"].Range;
             markRange.Text       = DocParameters[10];
             markRange.Underline  = WdUnderline.wdUnderlineSingle;
             markRange            = oDoc.Bookmarks["Address"].Range;
             markRange.Text       = DocParameters[11];
             markRange.Underline  = WdUnderline.wdUnderlineSingle;
             markRange            = oDoc.Bookmarks["Email"].Range;
             markRange.Text       = DocParameters[12];
             markRange.Underline  = WdUnderline.wdUnderlineSingle;
             markRange            = oDoc.Bookmarks["Series"].Range;
             markRange.Text       = DocParameters[13];
             markRange.Underline  = WdUnderline.wdUnderlineSingle;
             markRange            = oDoc.Bookmarks["NumberPassport"].Range;
             markRange.Text       = DocParameters[14];
             markRange.Underline  = WdUnderline.wdUnderlineSingle;
             markRange            = oDoc.Bookmarks["Issued"].Range;
             markRange.Text       = DocParameters[15];
             markRange.Underline  = WdUnderline.wdUnderlineSingle;
             markRange            = oDoc.Bookmarks["DateIssued"].Range;
             markRange.Text       = DocParameters[16];
             markRange.Underline  = WdUnderline.wdUnderlineSingle;
             markRange            = oDoc.Bookmarks["DateOfBirth"].Range;
             markRange.Text       = DocParameters[17];
             markRange.Underline  = WdUnderline.wdUnderlineSingle;
             markRange            = oDoc.Bookmarks["PlaceOfBirth"].Range;
             markRange.Text       = DocParameters[18];
             markRange.Underline  = WdUnderline.wdUnderlineSingle;
             string pathToSaveObj = @"C:\Users\temch\Desktop\Контракт.docx";
             oDoc.SaveAs2(pathToSaveObj);
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.ToString());
         }
         finally
         {
             oDoc.Close();
             oDoc = null;
             oWord.Quit();
         }
     });
 }
Exemplo n.º 8
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (cmbLettori.SelectedIndex != -1)
            {
                string dati = creaStringa();

                clsLettore l = new clsLettore("Biblioteca.mdf");

                l.codice = Convert.ToInt32(cmbLettori.SelectedValue);
                l.getDati();

                Percorso = System.Windows.Forms.Application.StartupPath;
                //MessageBox.Show(Percorso);
                FileDOC = Percorso + "/" + "PDF\\" + lblTitolo.Text + "_" + l.cognome + l.nome + ".docx";
                FilePDF = Percorso + "/" + "PDF\\" + lblTitolo.Text + "_" + l.cognome + l.nome + ".pdf";

                l.dispose();
                // Creo una NUOVA istanza di WORD Application
                myWord = new Microsoft.Office.Interop.Word.Application();

                // Rendo visibile la nuova Word Application
                //myWord.Visible = false;
                myWord.Visible = false;

                //Aggiungo un NUOVO Documento
                myDoc = new Document();
                myDoc = myWord.Documents.Add();

                start   = myDoc.Sentences[myDoc.Sentences.Count].End - 1;
                end     = myDoc.Sentences[myDoc.Sentences.Count].End;
                myRange = myDoc.Range(ref start, ref end);

                // Aggiungo il Testo
                myRange.Text = dati + "\n";

                myDoc.SaveAs2(FileDOC);

                // Chiudo il Documento
                myDoc.Close();

                // Chiudo il Word Application
                myWord.Quit();

                this.Cursor = Cursors.WaitCursor;

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

                myWord.Visible = false;

                myDoc = new Document();

                myDoc = myWord.Documents.Open(@FileDOC);

                myDoc.ExportAsFixedFormat(@FilePDF, WdExportFormat.wdExportFormatPDF);

                myDoc.Close();

                myWord.Quit();

                this.Cursor = Cursors.Default;

                MessageBox.Show("PDF creato con successo");

                File.Delete(@FileDOC);

                cmbLettori.SelectedIndex = -1;
                cmbLettori.SelectedIndex = -1;
            }
            else
            {
                MessageBox.Show("Seleziona il lettore");
            }
        }