public void Print(int id, DateTime date, List <Document> docs, string orgName,
                          string clientName, string identityClienName, string cost, string memo, string paymentStatus, string employee, Sign sign, string entryType = "")
        {
            _templateService.LoadActualIssueTemplate();

            var wordApp = new Word.Application();

            wordApp.Visible = false;

            try
            {
                var wordDocument = wordApp.Documents.Open(_templateService.IssueTemplatePath);
                FillingAllWordStub(wordDocument, id, date, docs, orgName, clientName, identityClienName, cost, memo, paymentStatus, employee, sign, entryType);
                wordApp.ActivePrinter = GlobalSettings.GetPrinters()[GlobalSettings.SelectPrinter];
                wordApp.PrintOut(Background: true);

                wordDocument.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
            }
            catch
            {
                wordApp.Quit();
                throw new Exception("Ошибка печати. Проверьте настройки принтера и путь к шаблону печати.");
            }
            finally
            {
                wordApp.Quit();
            }
        }
Example #2
0
        private void button1_Click(object sender, EventArgs e)
        {
            Word.Application app = new Word.Application();
            Word.Document    doc = app.Documents.Add();
            doc.Select();
            app.Selection.TypeParagraph();
            app.Selection.TypeText(" ТАЛОН ");
            app.Selection.TypeParagraph();
            app.Selection.TypeText("на прием к врачу : ");
            app.Selection.TypeParagraph();
            app.Selection.TypeText("Имя пациента : " + ticket.patCard.name);
            app.Selection.TypeParagraph();
            app.Selection.TypeText("Специализация : " + ticket.specialization.name);
            app.Selection.TypeParagraph();
            app.Selection.TypeText("ФИО врача : " + ticket.doctor.name);
            app.Selection.TypeParagraph();
            app.Selection.TypeText("Дата : " + ticket.date.ToString("dd.MM.yyyy"));
            app.Selection.TypeParagraph();
            app.Selection.TypeText("Кабинет : " + ticket.cabinet.number);
            app.Selection.TypeParagraph();
            app.Selection.TypeText("Время : " + ticket.time);
            app.PrintOut();

            //app.Visible = true;
            this.Close();
        }
Example #3
0
        public static void InWord(IEnumerable <Tuple <string, string> > res, string relativeSource)
        {
            try
            {
                Word.Application app    = new Word.Application();
                string           source = AppDomain.CurrentDomain.BaseDirectory + relativeSource;
                Word.Document    doc    = app.Documents.Add(source);
                doc.Activate();
                Word.Bookmarks bookmarks = doc.Bookmarks;

                StringBuilder result = new StringBuilder();

                foreach (var b in res)
                {
                    result.AppendLine(b.Item1);
                    result.AppendLine(b.Item2);
                }

                bookmarks["Results"].Range.Text    = result.ToString();
                bookmarks["Name"].Range.Text       = StaticParameters.User.Name;
                bookmarks["SecondName"].Range.Text = StaticParameters.User.SecondName;

                app.PrintOut(Range: Word.WdPrintOutRange.wdPrintAllDocument);
            }
            catch
            {
                MessageBox.Show("Произошла ошибка с печатью документа");
            }
        }
Example #4
0
 private void SendToPrinter(Application wordApp)
 {
     wordApp.ActivePrinter = _printerCapture();
     wordApp.PrintOut(true, false, WdPrintOutRange.wdPrintAllDocument,
         Item: WdPrintOutItem.wdPrintDocumentContent, Copies: "1", Pages: "",
         PageType: WdPrintOutPages.wdPrintAllPages, PrintToFile: false, Collate: true,
         ManualDuplexPrint: false);
 }
        internal static string PrintToFileForProof(Word.Application app, string input_filename)
        {
            // Create pdf filename
            var prnFileName = input_filename;

            // change root directory: try to land the file in scratch directory
            prnFileName = System.IO.Path.Combine(
                @"c:\scratch", System.IO.Path.GetFileNameWithoutExtension(prnFileName) + ".prn");

            // make sure c:\scratch exists
            if (!System.IO.Directory.Exists(@"C:\scratch"))
            {
                // create new if does not
                System.IO.Directory.CreateDirectory(@"C:\scratch");
            }

            // Remove existing files in C:\scratch
            if (System.IO.File.Exists(prnFileName))
            {
                System.IO.File.Delete(prnFileName);
            }

            // Print to PDF, using method from VBA cockle
            try
            {
                // let Acrobat Distiller determine the filename
                app.PrintOut(
                    FileName: "",
                    Range: Word.WdPrintOutRange.wdPrintAllDocument,
                    Item: Word.WdPrintOutItem.wdPrintDocumentContent,
                    Copies: 1,
                    Pages: "",
                    PageType: Word.WdPrintOutPages.wdPrintAllPages,
                    ManualDuplexPrint: false,
                    Collate: true,
                    Background: true,
                    PrintToFile: true,
                    PrintZoomColumn: 0,
                    PrintZoomRow: 0,
                    PrintZoomPaperWidth: 0,
                    PrintZoomPaperHeight: 0,
                    OutputFileName: prnFileName
                    );

                //Application.PrintOut fileName:= "", Range:= wdPrintAllDocument, Item:= _
                //wdPrintDocumentContent, Copies:= 1, Pages:= "", PageType:= wdPrintAllPages, _
                //ManualDuplexPrint:= False, Collate:= True, Background:= True, PrintToFile:= _
                //False, PrintZoomColumn:= 0, PrintZoomRow:= 0, PrintZoomPaperWidth:= 0, _
                //PrintZoomPaperHeight:= 0 ', OutputFileName:=pdffileName, Append:=False
            }
            catch
            {
                System.Diagnostics.Debug.WriteLine($"{input_filename} failed to print");
            }
            return(prnFileName);
        }
        internal static string PrintToFile(Word.Application app, string filename)
        {
            // Remove existing files in C:\scratch
            string pattern = @"\.docx*";

            // Create pdf filename
            var   pdfFileName = filename;
            Regex rx          = new Regex(pattern);

            if (rx.IsMatch(pdfFileName))
            {
                pdfFileName = rx.Replace(pdfFileName, @".pdf");
            }
            if (System.IO.File.Exists(pdfFileName))
            {
                System.IO.File.Delete(pdfFileName);
            }

            // Print to PDF, using method from VBA cockle
            try
            {
                app.PrintOut(
                    FileName: "",
                    Range: Word.WdPrintOutRange.wdPrintAllDocument,
                    Item: Word.WdPrintOutItem.wdPrintDocumentContent,
                    Copies: 1,
                    Pages: "",
                    PageType: Word.WdPrintOutPages.wdPrintAllPages,
                    ManualDuplexPrint: false,
                    Collate: true,
                    Background: true,
                    PrintToFile: false,
                    PrintZoomColumn: 0,
                    PrintZoomRow: 0,
                    PrintZoomPaperWidth: 0,
                    PrintZoomPaperHeight: 0);

                //Application.PrintOut fileName:= "", Range:= wdPrintAllDocument, Item:= _
                //wdPrintDocumentContent, Copies:= 1, Pages:= "", PageType:= wdPrintAllPages, _
                //ManualDuplexPrint:= False, Collate:= True, Background:= True, PrintToFile:= _
                //False, PrintZoomColumn:= 0, PrintZoomRow:= 0, PrintZoomPaperWidth:= 0, _
                //PrintZoomPaperHeight:= 0 ', OutputFileName:=pdffileName, Append:=False
            }
            catch
            {
                System.Diagnostics.Debug.WriteLine($"{filename} failed to print");
            }
            return(pdfFileName);
        }
Example #7
0
        private void btnOn_Click(object sender, EventArgs e)
        {
            object Pages = "";

            if (rbArea.Checked == true)
            {
                if (tbPage.Text.Trim() == "")
                {
                    PrintError pr = new PrintError();
                    pr.ShowDialog();
                    return;
                }

                string[] Str = tbPage.Text.Trim().Split('-');
                if (Str.Length > 2)
                {
                    PrintError pr = new PrintError();
                    pr.ShowDialog();
                    return;
                }

                foreach (string s in Str)
                {
                    if (!udt.IsValidByte(s))
                    {
                        PrintError pr = new PrintError();
                        pr.ShowDialog();
                        return;
                    }
                }
                Pages = tbPage.Text.Trim();
            }
            object oMissing = System.Reflection.Missing.Value;
            object Copies = nudCopy.Value.ToString();
            object Background = true, PrintZoomColumn = 0, PrintZoomRow = 0, PrintZoomPaperWidth = 0,
                   PrintZoomPaperHeight = 0, Append = oMissing, FileName = oMissing, From = oMissing, To = oMissing, ManualDuplexPrint = false;

            WordApp.PrintOut(ref Background, ref Append, ref PrintOutRange, ref FileName, ref oMissing, ref oMissing, ref PrintOutItem, ref Copies,
                             ref Pages, ref PrintType, ref PrintToFile, ref Collate, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                             ref oMissing, ref oMissing, ref PrintZoomPaperHeight);
            //WordApp.PrintOut(ref Background, ref Append, ref PrintOutRange, ref FileName, ref From, ref To, ref PrintOutItem, ref Copies,
            //    ref Pages, ref PrintType, ref PrintToFile, ref Collate, ref oMissing, ref oMissing, ref ManualDuplexPrint, ref PrintZoomColumn,
            //    ref PrintZoomRow, ref PrintZoomPaperWidth, ref PrintZoomPaperHeight);
            this.Close();
        }
Example #8
0
        public static void printLibroSoci(Object oTemplatePath, List <Iscrizione> iscrizioni, DateTime data_iscrizione, bool shallclose)
        {
            Microsoft.Office.Interop.Word.Application wordApp = null;

            //    try
            //   {
            Object oMissing = System.Reflection.Missing.Value;

            wordApp = new Microsoft.Office.Interop.Word.Application();
            Document wordDoc = new Document();

            wordDoc = wordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);

            foreach (Field myMergeField in wordDoc.Fields)
            {
                Range  rngFieldCode = myMergeField.Code;
                String fieldText    = rngFieldCode.Text;
                if (fieldText.StartsWith(" MERGEFIELD"))
                {
                    Int32  endMerge        = fieldText.IndexOf("\\");
                    Int32  fieldNameLength = fieldText.Length - endMerge;
                    String fieldName       = fieldText.Substring(11, endMerge - 11);

                    fieldName = fieldName.Trim();

                    if (fieldName == "Stagione" && DB.instance.stagione_corrente != null)
                    {
                        myMergeField.Select();
                        wordApp.Selection.TypeText(stringToWord(DB.instance.stagione_corrente.Descrizione));
                    }
                    else if (fieldName == "Oggi")
                    {
                        myMergeField.Select();
                        wordApp.Selection.TypeText(DateTime.Today.ToString("d"));
                    }
                    else if (fieldName == "DataIscrizione")
                    {
                        myMergeField.Select();
                        wordApp.Selection.TypeText(data_iscrizione.ToString("d"));
                    }
                }
            }


            int nrighe   = iscrizioni.Count + 1;
            int ncolonne = 7;

            object start         = wordDoc.Content.End - 1;
            object end           = wordDoc.Content.End - 1;
            Range  tableLocation = wordDoc.Range(ref start, ref end);
            Table  t             = wordDoc.Tables.Add(tableLocation, nrighe, ncolonne);

            int rownum = 1;

            for (int c = 1; c < ncolonne + 1; c++)
            {
                Cell cell = t.Cell(rownum, c);
                cell.Range.Bold = 1;
                cell.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                cell.Range.Text = c == 1 ? "Nome" :
                                  c == 2 ? "Cognome" :
                                  c == 3 ? "Data Nascita" :
                                  c == 4 ? "Luogo Nascita" :
                                  c == 5 ? "Codice Fiscale" :
                                  c == 6 ? "Tessera#" :
                                  "Data Socio";
            }
            rownum++;

            foreach (Iscrizione i in iscrizioni)
            {
                for (int c = 1; c < ncolonne + 1; c++)
                {
                    Cell cell = t.Cell(rownum, c);

                    cell.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    cell.Range.Text = c == 1 ? i.persona.Nome :
                                      c == 2 ? i.persona.Cognome :
                                      c == 3 ? (i.persona.DataNascita == null ? string.Empty : ((DateTime)i.persona.DataNascita).ToString("d")) :
                                      c == 4 ? i.persona.LuogoNascita :
                                      c == 5 ? i.persona.CodiceFiscale :
                                      c == 6 ? "" + i.tesseran :
                                      (i.data_socio == null ? string.Empty : ((DateTime)i.data_socio).ToString("d"));
                }
                rownum++;
            }


            wordApp.PrintOut();
            if (shallclose)
            {
                Microsoft.Office.Interop.Word._Document document = wordApp.ActiveDocument;
                document.Close(Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges);
                ((Microsoft.Office.Interop.Word._Application)wordApp).Quit();
            }
            else
            {
                wordApp.Visible = true;
            }

            /*  }
             * catch (Exception e)
             * {
             *    String errorString = "Errore Stampando il Libro Soci:\n" + e.Message;
             *
             *    if (Config.Instance.ShowErrors)
             *        MessageBox.Show(errorString, "Errore ", MessageBoxButtons.OK, MessageBoxIcon.Error);
             *
             *    Log.Instance.WriteLine(Log.LogLevel.Exception, errorString);
             *
             *    try { ((Microsoft.Office.Interop.Word._Application)wordApp).Quit(); }
             *    catch (Exception e1)
             *    {
             *        Log.Instance.WriteLine(Log.LogLevel.Exception, "Errore chiudendo Office: "+e1.ToString());
             *    }
             * }*/
        }
Example #9
0
 public void PrintWord(string file, string printer)
 {
     try
     {
         // Kill opened word instances.
         if (KillProcess("WINWORD"))
         {
             // Thread safe.
             lock (locker)
             {
                 string fileName    = file;
                 string printerName = printer;
                 if (File.Exists(fileName))
                 {
                     Microsoft.Office.Interop.Word.Application _application = new Microsoft.Office.Interop.Word.Application();
                     _application.Application.ActivePrinter = printerName;
                     object   oSourceFilePath = (object)fileName;
                     object   docType         = WdDocumentType.wdTypeDocument;
                     object   oFalse          = (object)false;
                     object   oMissing        = System.Reflection.Missing.Value;
                     Document _document       = _application.Documents.Open(ref oSourceFilePath,
                                                                            ref docType,
                                                                            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);
                     // Print
                     _application.PrintOut(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, ref oMissing,
                                           ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                     object saveOptions = WdSaveOptions.wdDoNotSaveChanges;
                     _document.Close(ref oFalse, ref oMissing, ref oMissing);
                     if (_application != null)
                     {
                         object oSave = false;
                         Object oMiss = System.Reflection.Missing.Value;
                         _application.Quit(ref oSave, ref oMiss, ref oMissing);
                         _application = null;
                     }
                     // Delete the file once it is printed
                     File.Delete(fileName);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         KillProcess("WINWORD");
         MessageBox.Show(ex.Message.ToString(), "Error while Printing - Student Management System", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
     finally
     {
     }
 }
Example #10
0
        public void Print()
        {
            _wordApp.PrintOut();

            Dispose();
        }
Example #11
0
 public static void Print(Auto curTc)
 {
     Fill(curTc);
     _wordApp.PrintOut();
 }
Example #12
0
        public static void printIncassiGiorno(Object oTemplatePath, List <UNFHibernate.Windows.ViewIncassi.EntryIscrizione> pagamenti, DateTime DataIscrizione, bool shallclose)
        {
            Microsoft.Office.Interop.Word.Application wordApp = null;

            try
            {
                Object oMissing = System.Reflection.Missing.Value;

                wordApp = new Microsoft.Office.Interop.Word.Application();
                Document wordDoc = new Document();
                wordDoc = wordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);

                foreach (Field myMergeField in wordDoc.Fields)
                {
                    Range  rngFieldCode = myMergeField.Code;
                    String fieldText    = rngFieldCode.Text;
                    if (fieldText.StartsWith(" MERGEFIELD"))
                    {
                        Int32  endMerge        = fieldText.IndexOf("\\");
                        Int32  fieldNameLength = fieldText.Length - endMerge;
                        String fieldName       = fieldText.Substring(11, endMerge - 11);

                        fieldName = fieldName.Trim();

                        if (fieldName == "Stagione" && DB.instance.stagione_corrente != null)
                        {
                            myMergeField.Select();
                            wordApp.Selection.TypeText(stringToWord(DB.instance.stagione_corrente.Descrizione));
                        }
                        else if (fieldName == "Oggi")
                        {
                            myMergeField.Select();
                            wordApp.Selection.TypeText(DateTime.Today.ToString("d"));
                        }
                        else if (fieldName == "Data")
                        {
                            myMergeField.Select();
                            wordApp.Selection.TypeText(DataIscrizione.ToString("d"));
                        }
                    }
                }

                int nrighe   = pagamenti.Count + 1;
                int ncolonne = 5;

                object start         = wordDoc.Content.End - 1;
                object end           = wordDoc.Content.End - 1;
                Range  tableLocation = wordDoc.Range(ref start, ref end);
                Table  t             = wordDoc.Tables.Add(tableLocation, nrighe, ncolonne);

                int rownum = 1;
                for (int c = 1; c < ncolonne + 1; c++)
                {
                    Cell cell = t.Cell(rownum, c);
                    cell.Range.Bold = 1;
                    cell.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    cell.Range.Text = c == 1 ? "Nome" :
                                      c == 2 ? "Cognome" :
                                      c == 3 ? "Corso" :
                                      c == 4 ? "Modalita" :
                                      "Importo";
                }
                rownum++;

                foreach (UNFHibernate.Windows.ViewIncassi.EntryIscrizione i in pagamenti)
                {
                    for (int c = 1; c < ncolonne + 1; c++)
                    {
                        Cell cell = t.Cell(rownum, c);

                        cell.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                        cell.Range.Text = c == 1 ? i.Nome :
                                          c == 2 ? i.Cognome :
                                          c == 3 ? i.Corso :
                                          c == 4 ? i.Modalita :
                                          i.Importo;
                    }
                    rownum++;
                }


                wordApp.PrintOut();
                if (shallclose)
                {
                    Microsoft.Office.Interop.Word._Document document = wordApp.ActiveDocument;
                    document.Close(Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges);
                    ((Microsoft.Office.Interop.Word._Application)wordApp).Quit();
                }
                else
                {
                    wordApp.Visible = true;
                }
            }
            catch (Exception e)
            {
                String errorString = "Errore Stampando gli incassi del giorno:\n" + e.Message;

                if (Config.Instance.ShowErrors)
                {
                    MessageBox.Show(errorString, "Errore ", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                Log.Instance.WriteLine(Log.LogLevel.Exception, errorString);

                try { ((Microsoft.Office.Interop.Word._Application)wordApp).Quit(); }
                catch (Exception e1)
                {
                    Log.Instance.WriteLine(Log.LogLevel.Exception, "Errore chiudendo Office: " + e1.ToString());
                }
            }
        }
        public void Print_Kartochka(SaveFileDialog saveFileDialog, string ID, DialogResult dialog)
        {
            WordApplication WordApp   = null;
            Documents       Documents = null;
            Document        Document  = null;
            string          output    = null;
            string          fileName  = null;
            DataTable       dt        = new DataTable();
            DataTable       dt2       = new DataTable();

            saveFileDialog.DefaultExt = "Документ Word|*.docx";
            saveFileDialog.Filter     = "Документ Word|*.docx|Документ Word 93-2003|*.doc|PDF|*.pdf";
            saveFileDialog.Title      = "Сохранить личную карточку пациента как";
            output = Select_Text(MySqlQueries.Print_Kartochka_Pacienta, ID);
            saveFileDialog.FileName         = output.Split(';')[0];
            saveFileDialog.InitialDirectory = Application.StartupPath + "\\Личные карточки\\";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    fileName  = saveFileDialog.FileName;
                    WordApp   = new WordApplication();
                    Documents = WordApp.Documents;
                    Document  = Documents.Open(Application.StartupPath + "\\blanks\\kartochka.docx");
                    string pol = Select_Text(MySqlQueries.Select_Pol_Pacienta_Kartochka, ID);
                    if (pol == "М")
                    {
                        Replace("{graj}", "Гражданин", Document);
                        Replace("{proj}", "проживает", Document);
                        Replace("{nahod}", "НАХОДИЛСЯ", Document);
                    }
                    else if (pol == "Ж")
                    {
                        Replace("{graj}", "Гражданка", Document);
                        Replace("{proj}", "проживающая", Document);
                        Replace("{nahod}", "НАХОДИЛАСЬ", Document);
                    }
                    Replace("{id}", output.Split(';')[1], Document);
                    Replace("{pacient}", output.Split(';')[2], Document);
                    Replace("{pacient}", output.Split(';')[2], Document);
                    Replace("{adress_pacienta}", output.Split(';')[3], Document);
                    Replace("{filial}", output.Split(';')[4].Split(' ')[2], Document);

                    dt     = Select_DataTable(MySqlQueries.Print_Otdeleniya_Pacienta, ID);
                    output = "";
                    foreach (DataRow row in dt.Rows)
                    {
                        output += row[0].ToString() + '\r' + '\t';
                    }
                    Replace("{otdelenie}", output, Document);

                    dt     = Select_DataTable(MySqlQueries.Print_Perenes_Zabol_Pacienta, ID);
                    output = "";
                    foreach (DataRow row in dt.Rows)
                    {
                        output += row[0].ToString() + '\r' + '\t';
                    }
                    Replace("{zaklucheniya}", output, Document);

                    dt     = Select_DataTable(MySqlQueries.Print_Perenesennye_Operacii_Pacienta, ID);
                    output = "";
                    foreach (DataRow row in dt.Rows)
                    {
                        output += row[0].ToString() + '\r' + '\t';
                    }
                    Replace("{perenesennye_operacii}", output, Document);

                    dt     = Select_DataTable(MySqlQueries.Print_Recomendacii_Pacienta, ID);
                    output = "";
                    foreach (DataRow row in dt.Rows)
                    {
                        output += row[0].ToString() + '\r' + '\t';
                    }
                    Replace("{recomendacii}", output, Document);

                    dt     = Select_DataTable(MySqlQueries.Print_Preparaty_Pacienta, ID);
                    output = "";
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (i != dt.Rows.Count - 1)
                        {
                            output += dt.Rows[i][0].ToString() + ", ";
                        }
                        else
                        {
                            output += dt.Rows[i][0].ToString() + ".";
                        }
                    }
                    Replace("{preparaty}", output, Document);

                    output = "";
                    dt     = Select_DataTable(MySqlQueries.Print_Proved_LabIssl_Pacienta, ID);
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        output += dt.Rows[i][1].ToString();
                        dt2     = Select_DataTable(MySqlQueries.Print_Dannye_LabIssl_Pacienta, ID, dt.Rows[i][0].ToString());
                        for (int j = 0; j < dt2.Rows.Count; j++)
                        {
                            if (j != dt2.Rows.Count - 1)
                            {
                                output += dt2.Rows[j][0].ToString() + ", ";
                            }
                            else if (i != dt.Rows.Count - 1)
                            {
                                output += dt2.Rows[j][0].ToString() + "." + '\r' + '\t';
                            }
                            else
                            {
                                output += dt2.Rows[j][0].ToString() + ".";
                            }
                        }
                    }
                    Replace("{lab_issl}", output, Document);

                    output = "";
                    dt     = Select_DataTable(MySqlQueries.Print_Proved_InstrIssl_Pacienta, ID);
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        output += dt.Rows[i][1].ToString();
                        dt2     = Select_DataTable(MySqlQueries.Print_Dannye_InstrIssl_Pacienta, ID, dt.Rows[i][0].ToString());
                        for (int j = 0; j < dt2.Rows.Count; j++)
                        {
                            if (j != dt2.Rows.Count - 1)
                            {
                                output += dt2.Rows[j][0].ToString() + ", ";
                            }
                            else if (i != dt.Rows.Count - 1)
                            {
                                output += dt2.Rows[j][0].ToString() + "." + '\r' + '\t';
                            }
                            else
                            {
                                output += dt2.Rows[j][0].ToString() + ".";
                            }
                        }
                    }
                    Replace("{instr_issl}", output, Document);

                    Document.SaveAs(fileName);
                    if (dialog == DialogResult.Yes)
                    {
                        WordApp.Quit();
                    }
                    if (dialog == DialogResult.No)
                    {
                        WordApp.PrintPreview = true;
                        WordApp.Visible      = true;
                    }
                    if (dialog == DialogResult.Cancel)
                    {
                        WordApp.PrintOut();
                        WordApp.Quit();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Marshal.ReleaseComObject(Documents);
                    Marshal.ReleaseComObject(Document);
                    Marshal.ReleaseComObject(WordApp);
                }
                finally
                {
                    Marshal.ReleaseComObject(Documents);
                    Marshal.ReleaseComObject(Document);
                    Marshal.ReleaseComObject(WordApp);
                }
            }
        }
        public void Print_Epikriz(SaveFileDialog saveFileDialog, string ID, DialogResult dialog)
        {
            WordApplication WordApp   = null;
            Documents       Documents = null;
            Document        Document  = null;
            string          output    = null;
            string          fileName  = null;
            DataTable       dt        = new DataTable();
            DataTable       dt2       = new DataTable();

            saveFileDialog.DefaultExt = "Документ Word|*.docx";
            saveFileDialog.Filter     = "Документ Word|*.docx|Документ Word 93-2003|*.doc|PDF|*.pdf";
            saveFileDialog.Title      = "Сохранить выписной эпикриз как";
            output = Select_Text(MySqlQueries.Print_Epikrizy, ID);
            saveFileDialog.FileName         = output.Split(';')[0];
            saveFileDialog.InitialDirectory = Application.StartupPath + "\\Выписные эпикризы\\";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    fileName  = saveFileDialog.FileName;
                    WordApp   = new WordApplication();
                    Documents = WordApp.Documents;
                    Document  = Documents.Open(Application.StartupPath + "\\blanks\\epikriz.docx");
                    string pol = Select_Text(MySqlQueries.Select_Pol_Pacienta, ID);
                    if (pol == "М")
                    {
                        Replace("{graj}", "Гражданин", Document);
                        Replace("{proj}", "проживающий", Document);
                        Replace("{nahod}", "находился", Document);
                    }
                    else if (pol == "Ж")
                    {
                        Replace("{graj}", "Гражданка", Document);
                        Replace("{proj}", "проживающая", Document);
                        Replace("{nahod}", "находилась", Document);
                    }
                    Replace("{id}", output.Split(';')[1], Document);
                    Replace("{pacient}", output.Split(';')[2], Document);
                    Replace("{adress_pacienta}", output.Split(';')[3], Document);
                    Replace("{filial}", output.Split(';')[4].Split(' ')[2], Document);
                    Replace("{otdelenie}", output.Split(';')[5], Document);
                    Replace("{date_n}", output.Split(';')[6], Document);
                    Replace("{date_k}", output.Split(';')[7], Document);
                    Replace("{sost_vypiski}", output.Split(';')[8].ToLower(), Document);
                    Replace("{lvn_n}", output.Split(';')[9], Document);
                    Replace("{lvn_k}", output.Split(';')[10], Document);
                    Replace("{recomendacii}", output.Split(';')[11], Document);
                    Replace("{lech_vrach}", output.Split(';')[12], Document);

                    dt     = Select_DataTable(MySqlQueries.Print_Diagnozy_Pacienta, ID);
                    output = "";
                    foreach (DataRow row in dt.Rows)
                    {
                        output += row[0].ToString();
                    }
                    Replace("{diagnozy_pacienta}", output, Document);

                    dt     = Select_DataTable(MySqlQueries.Print_Perenesennye_Operacii, ID);
                    output = "";
                    foreach (DataRow row in dt.Rows)
                    {
                        output += row[0].ToString();
                    }
                    Replace("{perenesennye_operacii}", output, Document);

                    dt     = Select_DataTable(MySqlQueries.Print_Zaklucheniya_Pacienta, ID);
                    output = "";
                    foreach (DataRow row in dt.Rows)
                    {
                        output += row[0].ToString();
                    }
                    Replace("{zaklucheniya}", output, Document);

                    dt     = Select_DataTable(MySqlQueries.Print_Preparaty, ID);
                    output = "";

                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (i != dt.Rows.Count - 1)
                        {
                            output += dt.Rows[i][0].ToString() + ", ";
                        }
                        else
                        {
                            output += dt.Rows[i][0].ToString() + ".";
                        }
                    }
                    Replace("{preparaty}", output, Document);

                    output = "";
                    dt     = Select_DataTable(MySqlQueries.Print_Proved_LabIssl, ID);
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        output += dt.Rows[i][1].ToString();
                        dt2     = Select_DataTable(MySqlQueries.Print_Dannye_LabIssl, ID, dt.Rows[i][0].ToString());
                        for (int j = 0; j < dt2.Rows.Count; j++)
                        {
                            if (j != dt2.Rows.Count - 1)
                            {
                                output += dt2.Rows[j][0].ToString() + ", ";
                            }
                            else if (i != dt.Rows.Count - 1)
                            {
                                output += dt2.Rows[j][0].ToString() + "." + '\r' + '\t';
                            }
                            else
                            {
                                output += dt2.Rows[j][0].ToString() + ".";
                            }
                        }
                    }
                    Replace("{lab_issl}", output, Document);

                    output = "";
                    dt     = Select_DataTable(MySqlQueries.Print_Proved_InstrIssl, ID);
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        output += dt.Rows[i][1].ToString();
                        dt2     = Select_DataTable(MySqlQueries.Print_Dannye_InstrIssl, ID, dt.Rows[i][0].ToString());
                        for (int j = 0; j < dt2.Rows.Count; j++)
                        {
                            if (j != dt2.Rows.Count - 1)
                            {
                                output += dt2.Rows[j][0].ToString() + ", ";
                            }
                            else if (i != dt.Rows.Count - 1)
                            {
                                output += dt2.Rows[j][0].ToString() + "." + '\r' + '\t';
                            }
                            else
                            {
                                output += dt2.Rows[j][0].ToString() + ".";
                            }
                        }
                    }
                    Replace("{instr_issl}", output, Document);

                    output = Select_Text(MySqlQueries.Print_Dop_Sved, ID);
                    if (output != "" && output != null)
                    {
                        for (int i = 0; i < 16; i++)
                        {
                            Replace("{ds" + i.ToString() + "}", output.Split(';')[i], Document);
                        }
                    }
                    else
                    {
                        for (int i = 0; i < 16; i++)
                        {
                            Replace("{ds" + i.ToString() + "}", "", Document);
                        }
                    }

                    output = Select_Text(MySqlQueries.Print_Zav_Otdeleniya, ID);
                    Replace("{zav_otdeleniya}", output, Document);

                    Document.SaveAs(fileName);
                    if (dialog == DialogResult.Yes)
                    {
                        WordApp.Quit();
                    }
                    if (dialog == DialogResult.No)
                    {
                        WordApp.PrintPreview = true;
                        WordApp.Visible      = true;
                    }
                    if (dialog == DialogResult.Cancel)
                    {
                        WordApp.PrintOut();
                        WordApp.Quit();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Marshal.ReleaseComObject(Documents);
                    Marshal.ReleaseComObject(Document);
                    Marshal.ReleaseComObject(WordApp);
                }
                finally
                {
                    Marshal.ReleaseComObject(Documents);
                    Marshal.ReleaseComObject(Document);
                    Marshal.ReleaseComObject(WordApp);
                }
            }
        }
        private void ImprimirReportes(FinancieraCredito credito)
        {
            FinancieraDS financieraDS = new FinancieraDS();
            DateTime     fechapago    = dtpFechaInicio.DateTime.Date;
            decimal      pagoPuntual  = decimal.Round(Convert.ToDecimal(txtMontoPago.EditValue), 1);
            decimal      pagoAtrasado = decimal.Round(
                (pagoPuntual + (pagoPuntual * Convert.ToDecimal(txtRecargoG.EditValue))), 1);

            for (int i = 0; i < Convert.ToInt32(txtNumPlazos.EditValue); i++)
            {
                switch (cboPlazo.Text)
                {
                case "SEMANAL":
                    financieraDS.Tables[0].Rows.Add(new object[] { null, fechapago.AddDays(7).Date, pagoPuntual, pagoAtrasado });
                    fechapago = fechapago.AddDays(7).Date;
                    break;

                case "QUINCENAL":
                    financieraDS.Tables[0].Rows.Add(new object[] { null, fechapago.AddDays(15).Date, pagoPuntual, pagoAtrasado });
                    fechapago = fechapago.AddDays(15).Date;
                    break;

                case "MENSUAL":
                    financieraDS.Tables[0].Rows.Add(new object[] { null, fechapago.AddMonths(1).Date, pagoPuntual, pagoAtrasado });
                    fechapago = fechapago.AddMonths(1).Date;
                    break;
                }
            }
            XrptControlPagosGrupal control = new XrptControlPagosGrupal();

            control.DataSource            = financieraDS.Tables[0];
            control.DatosGrupo.DataSource = credito;
            control.MontoCredito.Value    = Convert.ToDecimal(txtCantidadCredito.EditValue);
            control.DiasPago.Value        = string.Format("LOS {0} DE CADA SEMANA (CON PRORROGA HASTA EL {1})", dtpFechaInicio.DateTime.ToString("dddd").ToUpper(), dtpFechaInicio.DateTime.AddDays(Convert.ToInt32(txtProrrogaG.EditValue)).ToString("dddd").ToUpper());
            //control.ShowPreviewDialog();
            control.Print(new clsModificarConfiguracion().configGetValue("ImpresoraBoletas"));
            control.Print(new clsModificarConfiguracion().configGetValue("ImpresoraBoletas"));

            foreach (DataRow fila in dtIntegrantesGrupo.Rows)
            {
                fechapago = dtpFechaInicio.DateTime.Date;
                financieraDS.Tables[1].Rows.Clear();
                financieraDS.Tables[1].AcceptChanges();
                financieraDS.Tables[1].Columns["Pago"].AutoIncrementSeed = -1;
                financieraDS.Tables[1].Columns["Pago"].AutoIncrementStep = -1;
                financieraDS.Tables[1].Columns["Pago"].AutoIncrementSeed = 1;
                financieraDS.Tables[1].Columns["Pago"].AutoIncrementStep = 1;
                for (int i = 0; i < Convert.ToInt32(txtNumPlazos.EditValue); i++)
                {
                    switch (cboPlazo.Text)
                    {
                    case "SEMANAL":
                        financieraDS.Tables[1].Rows.Add(new[] { fila[1], fila[8], fila[9], fila[3], fechapago.AddDays(7).Date, null });
                        fechapago = fechapago.AddDays(7).Date;
                        break;

                    case "QUINCENAL":
                        financieraDS.Tables[1].Rows.Add(new[] { fila[1], fila[8], fila[9], fila[3], fechapago.AddDays(15).Date, null });
                        fechapago = fechapago.AddDays(15).Date;
                        break;

                    case "MENSUAL":
                        financieraDS.Tables[1].Rows.Add(new[] { fila[1], fila[8], fila[9], fila[3], fechapago.AddMonths(1).Date, null });
                        fechapago = fechapago.AddMonths(1).Date;
                        break;
                    }
                }
                XrptControlPagosPersonal control1 = new XrptControlPagosPersonal();
                control1.DataSource            = financieraDS.Tables[1];
                control1.DatosGrupo.DataSource = credito;
                control1.MontoCredito.Value    = Convert.ToDecimal(txtCantidadCredito.EditValue);
                control1.DiasPago.Value        = string.Format("LOS {0} DE CADA SEMANA (CON PRORROGA HASTA EL {1})", dtpFechaInicio.DateTime.ToString("dddd").ToUpper(), dtpFechaInicio.DateTime.AddDays(Convert.ToInt32(txtProrrogaG.EditValue)).ToString("dddd").ToUpper());
                control1.Print(new clsModificarConfiguracion().configGetValue("ImpresoraBoletas"));
                //financieraDS.Tables[2].Rows.Add(new[] { fila[1],CbToBytesA((Bitmap)fila[5]), CbToBytesA((Bitmap)fila[6]), CbToBytesA((Bitmap)fila[7])});
            }
            financieraDS.Tables[1].Rows.Clear();
            foreach (DataRow fila in dtIntegrantesGrupo.Rows)
            {
                financieraDS.Tables[1].Rows.Add(new[] { fila[1], fila[8], fila[9], fila[3], fechapago.AddDays(7).Date, null });
            }
            XrptHistrorialPagoPersonal historial = new XrptHistrorialPagoPersonal();

            historial.DataSource            = financieraDS;
            historial.DatosGrupo.DataSource = credito;
            historial.MontoCredito.Value    = Convert.ToDecimal(txtCantidadCredito.EditValue);
            historial.DiasPago.Value        = dtpFechaInicio.DateTime.ToString("dddd").ToUpper();
            XRSubreport detailReport = historial.Bands[BandKind.ReportHeader].FindControl("xrSubreport1", true) as XRSubreport;

            detailReport.ReportSource.DataSource = financieraDS.Tables[1];

            //for (int i = 0; i < dtIntegrantesGrupo.Rows.Count; i++)
            //{
            historial.Print(new clsModificarConfiguracion().configGetValue("ImpresoraBoletas"));
            historial.Print(new clsModificarConfiguracion().configGetValue("ImpresoraBoletas"));
            //}
            XrptPoderCobranza poder = new XrptPoderCobranza();

            poder.DataSource = credito;
            //poder.ShowPreviewDialog();
            poder.Print(new clsModificarConfiguracion().configGetValue("ImpresoraBoletas"));
            XrptReglamento reglamento = new XrptReglamento();

            reglamento.DataSource       = credito;
            reglamento.BaseLetras.Value = String.Format("{0} ({1}) ", txtBase.Text, Conversiones.NumeroALetras(txtBase.EditValue.ToString()));
            reglamento.Presidenta.Value =
                credito.FinancieraGrupo.FinancieraGruposDetalles.First(p => p.Tipo == "PRESIDENTA").FinancieraCliente.Nombre;
            reglamento.Tesorera.Value =
                credito.FinancieraGrupo.FinancieraGruposDetalles.First(p => p.Tipo == "TESORERA").FinancieraCliente.Nombre;
            reglamento.Print(new clsModificarConfiguracion().configGetValue("ImpresoraBoletas"));
            reglamento.Print(new clsModificarConfiguracion().configGetValue("ImpresoraBoletas"));
            //reglamento.ShowPreviewDialog();
            //control.Pages.AddRange(historial.Pages);
            this.oWord         = new Word.Application();
            this.oWord.Visible = false;


            // Ubicación de la plantilla en el disco duro
            oDoc = oWord.Documents.Add(Application.StartupPath + @"\Reglamento.dotx");
            oDoc.Bookmarks["Sucursal"].Range.Text  = new clsModificarConfiguracion().configGetValue("Empresa");
            oDoc.Bookmarks["Direccion"].Range.Text = new clsModificarConfiguracion().configGetValue("Direccion");
            object m      = System.Reflection.Missing.Value;
            object copies = 2;

            oWord.ActivePrinter = new clsModificarConfiguracion().configGetValue("ImpresoraBoletas");
            oWord.PrintOut(m, m, m, m, m, m, m, copies, m, m, m, m, m, m, m, m, m, m, m);
            object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;

            oDoc.Close(ref doNotSaveChanges, m, m);

            //////XrptFotosGrupos fotos=new XrptFotosGrupos {DataSource = financieraDS.Tables[2]};
            ////////fotos.ShowPreviewDialog(new clsModificarConfiguracion().configGetValue("ImpresoraBoletas"));
            //////fotos.Print(new clsModificarConfiguracion().configGetValue("ImpresoraBoletas"));
        }
Example #16
0
        public static void printIscrizione(Object oTemplatePath, Iscrizione iscrizione, int npagamento, bool shallclose)
        {
            Microsoft.Office.Interop.Word.Application wordApp = null;

            try
            {
                Object oMissing = System.Reflection.Missing.Value;

                wordApp = new Microsoft.Office.Interop.Word.Application();
                Document wordDoc = new Document();
                wordDoc = wordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);

                foreach (Field myMergeField in wordDoc.Fields)
                {
                    Range  rngFieldCode = myMergeField.Code;
                    String fieldText    = rngFieldCode.Text;
                    if (fieldText.StartsWith(" MERGEFIELD"))
                    {
                        Int32  endMerge        = fieldText.IndexOf("\\");
                        Int32  fieldNameLength = fieldText.Length - endMerge;
                        String fieldName       = fieldText.Substring(11, endMerge - 11);

                        fieldName = fieldName.Trim();

                        if (fieldName == "Nome")
                        {
                            myMergeField.Select();
                            wordApp.Selection.TypeText(stringToWord(iscrizione.persona.Nome));
                        }
                        else if (fieldName == "Cognome")
                        {
                            myMergeField.Select();
                            wordApp.Selection.TypeText(stringToWord(iscrizione.persona.Cognome));
                        }
                        else if (fieldName == "Nascita")
                        {
                            myMergeField.Select();

                            if (iscrizione.persona.DataNascita != null)
                            {
                                DateTime dt = (DateTime)iscrizione.persona.DataNascita;
                                wordApp.Selection.TypeText(dt.ToString("d"));
                            }
                            else
                            {
                                wordApp.Selection.TypeText("  /  /");
                            }
                        }
                        else if (fieldName == "CF")
                        {
                            myMergeField.Select();
                            wordApp.Selection.TypeText(stringToWord(iscrizione.persona.CodiceFiscale));
                        }
                        else if (fieldName == "ComuneNascita")
                        {
                            myMergeField.Select();
                            wordApp.Selection.TypeText(stringToWord(iscrizione.persona.LuogoNascita));
                        }
                        else if (fieldName == "Corso")
                        {
                            myMergeField.Select();
                            wordApp.Selection.TypeText(stringToWord(iscrizione.corso.Descrizione));
                        }
                        else if (fieldName == "Oggi")
                        {
                            myMergeField.Select();
                            wordApp.Selection.TypeText(DateTime.Today.ToString("d"));
                        }
                        else if (fieldName == "Giornate")
                        {
                            myMergeField.Select();
                            wordApp.Selection.TypeText(stringToWord(Utils.giornateToString(iscrizione.corso.getGiorniSettimana())));
                        }
                        else if (fieldName == "Orario")
                        {
                            myMergeField.Select();
                            wordApp.Selection.TypeText(stringToWord(iscrizione.corso.getOrarioString()));
                        }
                        else if (fieldName == "Dal")
                        {
                            myMergeField.Select();
                            if (iscrizione.data_inizio != null)
                            {
                                wordApp.Selection.TypeText(iscrizione.data_inizio.Value.Date.ToString("d"));
                            }
                        }
                        else if (fieldName == "Al")
                        {
                            myMergeField.Select();
                            //    wordApp.Selection.TypeText(iscrizione.corso.DataFine.ToString("d"));
                            wordApp.Selection.TypeText(Utils.dateToPrintableString(iscrizione.getLastDate()));
                        }
                        else if (fieldName == "Pagato")
                        {
                            myMergeField.Select();
                            wordApp.Selection.TypeText(iscrizione.Saldato ? "SI" : "NO");
                        }
                        else if (fieldName == "Indirizzo")
                        {
                            myMergeField.Select();
                            wordApp.Selection.TypeText(stringToWord(iscrizione.persona.Indirizzo));
                        }
                        else if (fieldName == "NumeroTelefono")
                        {
                            myMergeField.Select();
                            wordApp.Selection.TypeText(stringToWord(iscrizione.persona.NumeroTelefono));
                        }
                        else if (fieldName == "NumeroCellulare")
                        {
                            myMergeField.Select();
                            wordApp.Selection.TypeText(stringToWord(iscrizione.persona.NumeroCellulare));
                        }
                        else if (fieldName == "Email")
                        {
                            myMergeField.Select();
                            wordApp.Selection.TypeText(stringToWord(iscrizione.persona.Email));
                        }
                        else if (fieldName == "Stagione")
                        {
                            myMergeField.Select();
                            wordApp.Selection.TypeText(stringToWord(DB.instance.stagione_corrente.Descrizione));
                        }

                        else if (fieldName == "Importo")
                        {
                            if (npagamento < 0)
                            {
                                continue;
                            }

                            myMergeField.Select();

                            String importo = Utils.moneylongToString(npagamento == 0 ? iscrizione.primopagamento_importo :
                                                                     npagamento == 1 ? iscrizione.secondopagamento_importo :
                                                                     iscrizione.terzopagamento_importo);

                            wordApp.Selection.TypeText(stringToWord(importo));
                        }
                        else if (fieldName == "ModalitaPagamento")
                        {
                            if (npagamento < 0)
                            {
                                continue;
                            }

                            myMergeField.Select();
                            String modalita = npagamento == 0 ? iscrizione.primopagamento_modalita :
                                              npagamento == 1 ? iscrizione.secondopagamento_modalita :
                                              iscrizione.terzopagamento_modalita;

                            wordApp.Selection.TypeText(stringToWord(modalita));
                        }
                        else if (fieldName == "DataPagamento")
                        {
                            if (npagamento < 0)
                            {
                                continue;
                            }

                            try
                            {
                                myMergeField.Select();
                                DateTime?datapagamento = npagamento == 0 ? iscrizione.primopagamento_data :
                                                         npagamento == 1 ? iscrizione.secondopagamento_data :
                                                         iscrizione.terzopagamento_data;

                                if (datapagamento != null)
                                {
                                    wordApp.Selection.TypeText(datapagamento.Value.ToString("d"));
                                }
                            }
                            catch { }
                        }

                        else if (fieldName.StartsWith("Importo"))
                        {
                            try {
                                int n = Int32.Parse(fieldName.Replace("Importo", String.Empty));

                                myMergeField.Select();
                                String importo = Utils.moneylongToString(n == 0 ? iscrizione.primopagamento_importo :
                                                                         n == 1 ? iscrizione.secondopagamento_importo :
                                                                         iscrizione.terzopagamento_importo);

                                wordApp.Selection.TypeText(stringToWord(importo));
                            }
                            catch { continue; }
                        }
                        else if (fieldName.StartsWith("ModalitaPagamento"))
                        {
                            try
                            {
                                int n = Int32.Parse(fieldName.Replace("ModalitaPagamento", String.Empty));

                                myMergeField.Select();
                                String modalita = n == 0 ? iscrizione.primopagamento_modalita :
                                                  n == 1 ? iscrizione.secondopagamento_modalita :
                                                  iscrizione.terzopagamento_modalita;

                                wordApp.Selection.TypeText(stringToWord(modalita));
                            }
                            catch { continue; }
                        }
                        else if (fieldName.StartsWith("DataPagamento"))
                        {
                            try
                            {
                                int n = Int32.Parse(fieldName.Replace("DataPagamento", String.Empty));

                                myMergeField.Select();
                                DateTime?datapagamento = n == 0 ? iscrizione.primopagamento_data :
                                                         n == 1 ? iscrizione.secondopagamento_data :
                                                         iscrizione.terzopagamento_data;

                                if (datapagamento != null)
                                {
                                    wordApp.Selection.TypeText(datapagamento.Value.ToString("d"));
                                }
                            }
                            catch { continue; }
                        }
                    }
                }

                wordApp.PrintOut();
                if (shallclose)
                {
                    Microsoft.Office.Interop.Word._Document document = wordApp.ActiveDocument;
                    document.Close(Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges);
                    ((Microsoft.Office.Interop.Word._Application)wordApp).Quit();
                }
                else
                {
                    wordApp.Visible = true;
                }
            }
            catch (Exception e)
            {
                String errorString = "Errore Stampando un Pagamento:\n" + e.Message;

                if (Config.Instance.ShowErrors)
                {
                    MessageBox.Show(errorString, "Errore ", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                Log.Instance.WriteLine(Log.LogLevel.Exception, errorString);

                try { ((Microsoft.Office.Interop.Word._Application)wordApp).Quit(); }
                catch (Exception e1)
                {
                    Log.Instance.WriteLine(Log.LogLevel.Exception, "Errore chiudendo Office: " + e1.ToString());
                }
            }
        }
        private void ImprimirReportes(FinancieraCredito credito)
        {
            FinancieraDS financieraDS = new FinancieraDS();
            DateTime fechapago = dtpFechaInicio.DateTime.Date;
            decimal pagoPuntual = decimal.Round(Convert.ToDecimal(txtMontoPago.EditValue), 1);
            decimal pagoAtrasado = decimal.Round(
                (pagoPuntual + (pagoPuntual * Convert.ToDecimal(txtRecargoG.EditValue))), 1);
            for (int i = 0; i < Convert.ToInt32(txtNumPlazos.EditValue); i++)
            {
                switch (cboPlazo.Text)
                {
                    case "SEMANAL":
                        financieraDS.Tables[0].Rows.Add(new object[] { null, fechapago.AddDays(7).Date, pagoPuntual, pagoAtrasado });
                        fechapago = fechapago.AddDays(7).Date;
                        break;
                    case "QUINCENAL":
                        financieraDS.Tables[0].Rows.Add(new object[] { null, fechapago.AddDays(15).Date, pagoPuntual, pagoAtrasado });
                        fechapago = fechapago.AddDays(15).Date;
                        break;
                    case "MENSUAL":
                        financieraDS.Tables[0].Rows.Add(new object[] { null, fechapago.AddMonths(1).Date, pagoPuntual, pagoAtrasado });
                        fechapago = fechapago.AddMonths(1).Date;
                        break;
                }

            }
            XrptControlPagosGrupal control = new XrptControlPagosGrupal();
            control.DataSource = financieraDS.Tables[0];
            control.DatosGrupo.DataSource = credito;
            control.MontoCredito.Value = Convert.ToDecimal(txtCantidadCredito.EditValue);
            control.DiasPago.Value = string.Format("LOS {0} DE CADA SEMANA (CON PRORROGA HASTA EL {1})", dtpFechaInicio.DateTime.ToString("dddd").ToUpper(), dtpFechaInicio.DateTime.AddDays(Convert.ToInt32(txtProrrogaG.EditValue)).ToString("dddd").ToUpper());
            //control.ShowPreviewDialog();
            control.Print(new clsModificarConfiguracion().configGetValue("ImpresoraBoletas"));
            control.Print(new clsModificarConfiguracion().configGetValue("ImpresoraBoletas"));

            foreach (DataRow fila in dtIntegrantesGrupo.Rows)
            {
                fechapago = dtpFechaInicio.DateTime.Date;
                financieraDS.Tables[1].Rows.Clear();
                financieraDS.Tables[1].AcceptChanges();
                financieraDS.Tables[1].Columns["Pago"].AutoIncrementSeed = -1;
                financieraDS.Tables[1].Columns["Pago"].AutoIncrementStep = -1;
                financieraDS.Tables[1].Columns["Pago"].AutoIncrementSeed = 1;
                financieraDS.Tables[1].Columns["Pago"].AutoIncrementStep = 1;
                for (int i = 0; i < Convert.ToInt32(txtNumPlazos.EditValue); i++)
                {
                    switch (cboPlazo.Text)
                    {
                        case "SEMANAL":
                            financieraDS.Tables[1].Rows.Add(new[] { fila[1], fila[8], fila[9], fila[3], fechapago.AddDays(7).Date, null });
                            fechapago = fechapago.AddDays(7).Date;
                            break;
                        case "QUINCENAL":
                            financieraDS.Tables[1].Rows.Add(new[] { fila[1], fila[8], fila[9], fila[3], fechapago.AddDays(15).Date, null });
                            fechapago = fechapago.AddDays(15).Date;
                            break;
                        case "MENSUAL":
                            financieraDS.Tables[1].Rows.Add(new[] { fila[1], fila[8], fila[9], fila[3], fechapago.AddMonths(1).Date, null });
                            fechapago = fechapago.AddMonths(1).Date;
                            break;
                    }
                }
                XrptControlPagosPersonal control1 = new XrptControlPagosPersonal();
                control1.DataSource = financieraDS.Tables[1];
                control1.DatosGrupo.DataSource = credito;
                control1.MontoCredito.Value = Convert.ToDecimal(txtCantidadCredito.EditValue);
                control1.DiasPago.Value = string.Format("LOS {0} DE CADA SEMANA (CON PRORROGA HASTA EL {1})", dtpFechaInicio.DateTime.ToString("dddd").ToUpper(), dtpFechaInicio.DateTime.AddDays(Convert.ToInt32(txtProrrogaG.EditValue)).ToString("dddd").ToUpper());
                control1.Print(new clsModificarConfiguracion().configGetValue("ImpresoraBoletas"));
                //financieraDS.Tables[2].Rows.Add(new[] { fila[1],CbToBytesA((Bitmap)fila[5]), CbToBytesA((Bitmap)fila[6]), CbToBytesA((Bitmap)fila[7])});
            }
            financieraDS.Tables[1].Rows.Clear();
            foreach (DataRow fila in dtIntegrantesGrupo.Rows)
            {
                financieraDS.Tables[1].Rows.Add(new[] { fila[1], fila[8], fila[9], fila[3], fechapago.AddDays(7).Date, null });
            }
            XrptHistrorialPagoPersonal historial = new XrptHistrorialPagoPersonal();
            historial.DataSource = financieraDS;
            historial.DatosGrupo.DataSource = credito;
            historial.MontoCredito.Value = Convert.ToDecimal(txtCantidadCredito.EditValue);
            historial.DiasPago.Value = dtpFechaInicio.DateTime.ToString("dddd").ToUpper();
            XRSubreport detailReport = historial.Bands[BandKind.ReportHeader].FindControl("xrSubreport1", true) as XRSubreport;
            detailReport.ReportSource.DataSource = financieraDS.Tables[1];

            //for (int i = 0; i < dtIntegrantesGrupo.Rows.Count; i++)
            //{
            historial.Print(new clsModificarConfiguracion().configGetValue("ImpresoraBoletas"));
            historial.Print(new clsModificarConfiguracion().configGetValue("ImpresoraBoletas"));
            //}
            XrptPoderCobranza poder = new XrptPoderCobranza();
            poder.DataSource = credito;
            //poder.ShowPreviewDialog();
            poder.Print(new clsModificarConfiguracion().configGetValue("ImpresoraBoletas"));
            XrptReglamento reglamento = new XrptReglamento();
            reglamento.DataSource = credito;
            reglamento.BaseLetras.Value = String.Format("{0} ({1}) ", txtBase.Text, Conversiones.NumeroALetras(txtBase.EditValue.ToString()));
            reglamento.Presidenta.Value =
                credito.FinancieraGrupo.FinancieraGruposDetalles.First(p => p.Tipo == "PRESIDENTA").FinancieraCliente.Nombre;
            reglamento.Tesorera.Value =
                credito.FinancieraGrupo.FinancieraGruposDetalles.First(p => p.Tipo == "TESORERA").FinancieraCliente.Nombre;
            reglamento.Print(new clsModificarConfiguracion().configGetValue("ImpresoraBoletas"));
            reglamento.Print(new clsModificarConfiguracion().configGetValue("ImpresoraBoletas"));
            //reglamento.ShowPreviewDialog();
            //control.Pages.AddRange(historial.Pages);
            this.oWord = new Word.Application();
            this.oWord.Visible = false;

            // Ubicación de la plantilla en el disco duro
            oDoc = oWord.Documents.Add(Application.StartupPath + @"\Reglamento.dotx");
            oDoc.Bookmarks["Sucursal"].Range.Text = new clsModificarConfiguracion().configGetValue("Empresa");
            oDoc.Bookmarks["Direccion"].Range.Text = new clsModificarConfiguracion().configGetValue("Direccion");
            object m = System.Reflection.Missing.Value;
            object copies = 2;
            oWord.ActivePrinter = new clsModificarConfiguracion().configGetValue("ImpresoraBoletas");
            oWord.PrintOut(m, m, m, m, m, m, m, copies, m, m, m, m, m, m, m, m, m, m, m);
            object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
            oDoc.Close(ref doNotSaveChanges, m, m);

            //////XrptFotosGrupos fotos=new XrptFotosGrupos {DataSource = financieraDS.Tables[2]};
            ////////fotos.ShowPreviewDialog(new clsModificarConfiguracion().configGetValue("ImpresoraBoletas"));
            //////fotos.Print(new clsModificarConfiguracion().configGetValue("ImpresoraBoletas"));
        }