Ejemplo n.º 1
0
        /// <summary>
        ///     Prints the file.
        /// </summary>
        /// <param name="processTimeout">The timespan to wait for the process to finish</param>
        /// <returns>true, if printing was successful</returns>
        public bool Print(TimeSpan processTimeout)
        {
            if (CommandType == PrintType.Unprintable)
            {
                throw new InvalidOperationException("File is not printable");
            }

            var printerHelper = new PrinterHelper();

            if (CommandType == PrintType.Print && Printer != printerHelper.GetDefaultPrinter())
            {
                throw new InvalidOperationException("The default printer needs to be set in order to print this file");
            }

            var p = ProcessWrapperFactory.BuildProcessWrapper(new ProcessStartInfo());

            var verb = SupportsPrintTo()
                ? "printto"
                : "print";

            var command   = GetCommand(verb);
            var arguments = SupportsPrintTo()
                ? command.GetReplacedCommandArgs(Filename, Printer)
                : command.GetReplacedCommandArgs(Filename);

            p.StartInfo.FileName  = command.Command;
            p.StartInfo.Arguments = arguments;

            Logger.Debug($"Launching {verb} for \"{Filename}\": {command.Command} {arguments}");

            try
            {
                p.Start();
                p.WaitForExit(processTimeout);

                if (!p.HasExited)
                {
                    Logger.Warn("Process was not finishing after {0} seconds, killing it now...", processTimeout.TotalSeconds);
                    p.Kill();
                }
                else
                {
                    Successful = true;
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Exception during printing"
                             + "\r\nType: " + ex.GetType()
                             + "\r\nMessage: " + ex.Message
                             );
                return(false);
            }

            return(Successful);
        }
        /// <summary>
        ///     Prints the file.
        /// </summary>
        /// <param name="processTimeout">The timespan to wait for the process to finish</param>
        /// <returns>true, if printing was successful</returns>
        public bool Print(TimeSpan processTimeout)
        {
            if (CommandType == PrintType.Unprintable)
            {
                throw new InvalidOperationException("File is not printable");
            }

            var printerHelper = new PrinterHelper();

            if (CommandType == PrintType.Print && Printer != printerHelper.GetDefaultPrinter())
            {
                throw new InvalidOperationException("The default printer needs to be set in order to print this file");
            }

            var p = ProcessWrapperFactory.BuildProcessWrapper(new ProcessStartInfo(Filename));

            if (SupportsPrintTo())
            {
                Logger.Debug("Launch PrintTo for \"" + Filename + "\"");
                p.StartInfo.Verb      = "Printto";
                p.StartInfo.Arguments = "\"" + Printer + "\"";
            }
            else
            {
                Logger.Debug("Launch Print for \"" + Filename + "\"");
                p.StartInfo.Verb = "Print";
            }

            try
            {
                p.Start();
                p.WaitForExit(processTimeout);

                if (!p.HasExited)
                {
                    Logger.Warn("Process was not finishing after {0} seconds, killing it now...", processTimeout.TotalSeconds);
                    p.Kill();
                }
                else
                {
                    Successful = true;
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Exception during printing"
                             + "\r\nType: " + ex.GetType()
                             + "\r\nMessage: " + ex.Message
                             );
                return(false);
            }

            return(Successful);
        }
Ejemplo n.º 3
0
        public void PrintCommand_GivenValidPrintOnlyFile_PrintsSuccessfully()
        {
            var tempFile      = TempFileHelper.CreateTempFile("PrintCommand", "test.ini");
            var printerHelper = new PrinterHelper();
            var printCommand  = new PrintCommand(tempFile, printerHelper.GetDefaultPrinter(), new FileAssoc());

            var factory = new MockProcessWrapperFactory(true);

            printCommand.ProcessWrapperFactory = factory;

            printCommand.Print();

            Assert.IsTrue(printCommand.Successful);
            Assert.IsFalse(factory.LastMock.WasKilled);
        }
Ejemplo n.º 4
0
        public void PrintCommand_GivenValidPrintOnlyFile_HasCorrectStartInfo()
        {
            var tempFile      = TempFileHelper.CreateTempFile("PrintCommand", "test.ini");
            var printerHelper = new PrinterHelper();
            var printCommand  = new PrintCommand(tempFile, printerHelper.GetDefaultPrinter(), new FileAssoc());

            var factory = new MockProcessWrapperFactory(true);

            printCommand.ProcessWrapperFactory = factory;

            printCommand.Print();

            Assert.IsTrue(printCommand.Successful);
            StringAssert.Contains(tempFile, factory.LastMock.StartInfo.Arguments);
        }
Ejemplo n.º 5
0
        public void PrintCommand_GivenValidPrintOnlyFile_HasCorrectStartInfo()
        {
            string tempFile      = TempFileHelper.CreateTempFile("PrintCommand", "test.ini");
            var    printerHelper = new PrinterHelper();
            var    printCommand  = new PrintCommand(tempFile, printerHelper.GetDefaultPrinter());

            var factory = new MockProcessWrapperFactory(true);

            printCommand.ProcessWrapperFactory = factory;

            printCommand.Print();

            Assert.IsTrue(printCommand.Successful);
            Assert.AreEqual(tempFile, factory.LastMock.StartInfo.FileName);
            Assert.IsNullOrEmpty(factory.LastMock.StartInfo.Arguments);
        }
Ejemplo n.º 6
0
        /// <summary>
        ///     Prints all files in the list.
        /// </summary>
        /// <returns>true, if all files could be printed</returns>
        public bool PrintAll()
        {
            if (string.IsNullOrEmpty(_clawPdfPrinter))
            {
                _logger.Error("No clawPDF is installed.");
                return(false);
            }

            var printerHelper = new PrinterHelper();

            var requiresDefaultPrinter = _printCommands.RequiresDefaultPrinter;
            var defaultPrinter         = printerHelper.GetDefaultPrinter();

            try
            {
                if (requiresDefaultPrinter)
                {
                    if (SettingsHelper.Settings.ApplicationSettings.AskSwitchDefaultPrinter)
                    {
                        if (!QuerySwitchDefaultPrinter())
                        {
                            return(false);
                        }
                    }

                    PrinterHelper.SetDefaultPrinter(_clawPdfPrinter);
                }

                return(_printCommands.PrintAll());
            }
            finally
            {
                if (requiresDefaultPrinter)
                {
                    PrinterHelper.SetDefaultPrinter(defaultPrinter);
                }
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Crea un documento dependiendo del fileformat que se requiera
        /// </summary>
        /// <param name="enumFileFormat">enumerdo con el formato para crear el documento</param>
        /// <history>
        /// [emoguel] 02/09/2016 created
        /// </history>
        private void CreateFile(EnumFileFormat enumFileFormat)
        {
            Workbook wb = null;

            Microsoft.Office.Interop.Excel.Application excel = null;
            string defaultPrinter  = "";
            bool   blnChagePrinter = false;

            try
            {
                if (_excelFile.Exists)
                {
                    #region Printer
                    defaultPrinter = PrinterHelper.GetDefaultPrinter();
                    if (!string.IsNullOrWhiteSpace(defaultPrinter) && defaultPrinter.Contains("pdf", StringComparison.OrdinalIgnoreCase))                         //Ver si hay impresora predeterminada y que no sea pdf
                    {
                        var lstPrinters = PrinterHelper.getAllPrinters().Where(printer => !printer.Contains("pdf", StringComparison.OrdinalIgnoreCase)).ToList(); //Obtener la lista de impresoras que no sean pdf

                        //Verificar si hay una impresora xps
                        string xpsPrinter = lstPrinters.FirstOrDefault(printer => printer.Contains("xps", StringComparison.OrdinalIgnoreCase)); //Buscar impresora XPS
                        if (!string.IsNullOrWhiteSpace(xpsPrinter))                                                                             //Verficar si existe una impresora XPS
                        {
                            PrinterHelper.SetDefaultPrinter(xpsPrinter);                                                                        //Predefinir la impresora XPS
                            blnChagePrinter = true;
                        }
                        else
                        {
                            PrinterHelper.SetDefaultPrinter(lstPrinters[0]);//Predefinir la primera impresora
                            blnChagePrinter = true;
                        }
                    }

                    #endregion


                    //Obtenemos la orientacion seleccionada
                    XlPageOrientation pageOrientation = (XlPageOrientation)cmbOrientation.SelectedValue;
                    //Obtenemos el tamaño de papel seleccionado
                    XlPaperSize paperSize = (XlPaperSize)cmbPageSize.SelectedValue;
                    //Obtenemos el margen seleccionado
                    Margin margin = cmbMargin.SelectedValue as Margin;
                    //Obtenemos la escala seleccionada
                    EnumScale enumScale = (EnumScale)cmbScale.SelectedValue;
                    excel                = new Microsoft.Office.Interop.Excel.Application();
                    excel.Visible        = false;
                    excel.ScreenUpdating = false;
                    excel.DisplayAlerts  = false;

                    wb = excel.Workbooks.Open(_excelFile.FullName, 0, false, Missing.Value, Missing.Value, Missing.Value, true, XlPlatform.xlWindows, Missing.Value, false, false, Missing.Value, false, true, false);//Cargamos el excel
                    _Worksheet ws = ((_Worksheet)wb.ActiveSheet);

                    #region Page Configuration
                    ws.PageSetup.PaperSize    = paperSize;                                //asignamos el tamaño de hoja
                    ws.PageSetup.Orientation  = pageOrientation;                          //asignamos orientación de la pagina
                    ws.PageSetup.LeftMargin   = excel.CentimetersToPoints(margin.left);   //asignamos Margen Izquierdo
                    ws.PageSetup.RightMargin  = excel.CentimetersToPoints(margin.right);  //asignamos Margen Derecho
                    ws.PageSetup.TopMargin    = excel.CentimetersToPoints(margin.top);    //asignamos Margen de arriba
                    ws.PageSetup.BottomMargin = excel.CentimetersToPoints(margin.bottom); //asignamos Margen de abajo
                    ws.PageSetup.Zoom         = false;
                    #endregion
                    #region Scale
                    //Asignamos la escala seleccionada
                    switch (enumScale)
                    {
                    case EnumScale.Noscaling:
                    {
                        ws.PageSetup.FitToPagesTall = false;
                        ws.PageSetup.FitToPagesWide = false;
                        break;
                    }

                    case EnumScale.FitSheetOnOnePage:
                    {
                        ws.PageSetup.FitToPagesTall = 1;
                        ws.PageSetup.FitToPagesWide = 1;
                        break;
                    }

                    case EnumScale.FitAllColumnsOnOnePage:
                    {
                        ws.PageSetup.FitToPagesWide = 1;
                        ws.PageSetup.FitToPagesTall = false;
                        break;
                    }

                    case EnumScale.FitAllRowsOnOnePage:
                    {
                        ws.PageSetup.FitToPagesTall = 1;
                        ws.PageSetup.FitToPagesWide = false;
                        break;
                    }
                    }
                    #endregion

                    ws.PageSetup.Order = XlOrder.xlOverThenDown;//Poner el orden de la paginas
                    #region Export
                    switch (enumFileFormat)
                    {
                    case EnumFileFormat.Pdf:
                    {
                        SaveFileDialog dialog = new SaveFileDialog();//Cargamos el saveFileDialog
                        dialog.FileName = Uid;
                        dialog.Filter   = "PDF files(*.pdf) | *.pdf;";
                        if (dialog.ShowDialog() == true)
                        {
                            wb.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, dialog.FileName, XlFixedFormatQuality.xlQualityStandard, false, true, Missing.Value, Missing.Value, false, Missing.Value);//Guardamos como PDF

                            if (File.Exists(dialog.FileName))
                            {
                                UIHelper.ShowMessage("Document sufesfully saved.");
                                Process.Start(dialog.FileName);
                            }
                            else
                            {
                                UIHelper.ShowMessage("Document not saved.");
                            }
                        }
                        break;
                    }

                    case EnumFileFormat.Xps:
                    {
                        wb.ExportAsFixedFormat(XlFixedFormatType.xlTypeXPS, $"{_fullPathAndName}.xps", XlFixedFormatQuality.xlQualityStandard, false, true, Missing.Value, Missing.Value, false, Missing.Value);//Guardamos como XPS
                        break;
                    }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                UIHelper.ShowMessage(ex);
            }
            finally
            {
                if (wb != null)
                {
                    wb.Close();
                }
                if (excel != null)
                {
                    excel.Quit();
                }
                if (blnChagePrinter)
                {
                    PrinterHelper.SetDefaultPrinter(defaultPrinter);
                }
            }
        }