// Pode parecer estranho..., mas um site WEB pode imprimir conteudo direto na impressora
    // Isso pois o aplicativo é simplesmente um programa convencional.
    // Mas para que isso funciona deve existir uma impressora pdrão conectada ao servidor WEB
    // É logico que isso não irá funcionar em provedores de hostings, apenas em WEB SERVERs em redes locais
    protected void btnPrint_Click(object sender, EventArgs e)
    {
        // Para imprimir dados vindo de uma tabela de um banco de dados
        // é preciso definir conexões ao banco, com senhas, executar SELECTs.
        // Neste exemplo abaixo estou criando 5 registros em memoria e 
        // recalculando o boleto para cada página impressa
        // Customize de acordo com suas necessidades, pois este é apenas um exemplo 
        // basico por isso serão utilizados apenas poucos campos.

        blt = new BoletoForm();
        tbDados = new DataTable(); // Cria  atabela em memoria

        // Cria as colunas nos respectivos tipos
        tbDados.Columns.Add("Nome", typeof(string));
        tbDados.Columns.Add("Vencimento", typeof(DateTime));
        tbDados.Columns.Add("Valor", typeof(double));
        tbDados.Columns.Add("NossoNumero", typeof(int));

        // insere os dados
        tbDados.Rows.Add("Fábio", new DateTime(2008, 12, 30), 123.45, 345678);
        tbDados.Rows.Add("Érika", new DateTime(2008, 7, 25), 60, 12332);
        tbDados.Rows.Add("Milena", new DateTime(2008, 10, 20), 10.30, 234);
        tbDados.Rows.Add("Cecília", DateTime.MinValue, 200.55, 456445);
        tbDados.Rows.Add("qualquer um", new DateTime(2008, 2, 12), 7890.5, 56756);

        // posiciona o registro atual
        nReg = 0;
        PrintDocument pDoc = new PrintDocument();

        // ATENÇÃO: IMPORTANTE!!!
        // ======================
        pDoc.PrinterSettings.PrinterName = "EPSON Stylus CX5600 Series";
        // É necessário definir o nome da impressora instlada, exatamente com o nome que é exibido no windows.
        // A impressora do usuários ASPNET é diferente do seu usuários atualmente logado!

        pDoc.PrintPage += new PrintPageEventHandler(pDoc_PrintPageTabela);
        pDoc.Print();
    }
 // Print the file.
 public void Printing()
 {
     try {
         streamToPrint = new StreamReader(filePath);
         try {
             printFont = new Font("Consolas", 10);
             PrintDocument pd = new PrintDocument();
             pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
             // Print the document.
             pd.Print();
         }
         finally {
             streamToPrint.Close();
         }
     }
     catch (Exception ex) {
         MessageBox.Show(ex.Message);
     }
 }
示例#3
0
        public static void Main (string[] args)
        {                
		PrintDocument p = new PrintDocument ();
		p.PrintPage += new PrintPageEventHandler (PrintPageEvent);
		p.QueryPageSettings += new  QueryPageSettingsEventHandler (QueryPageSettings);
                p.Print ();
		
        }
示例#4
0
        public DialogResult ShowDialog(Window parent)
        {
            Control.SetEtoSettings(settings);
            var result = Control.ShowDialog();

            if (result == true)
            {
                settings.SetFromDialog(Control);
                Document?.Print();
                return(DialogResult.Ok);
            }
            return(DialogResult.Cancel);
        }
示例#5
0
    private void Print()
    {
        const string printerName = "Microsoft Office Document Image Writer";

        if (m_streams == null || m_streams.Count == 0)
            return;

        PrintDocument printDoc = new PrintDocument();
        printDoc.PrinterSettings.PrinterName = printerName;
        if (!printDoc.PrinterSettings.IsValid)
        {
            string msg = String.Format("Can't find printer \"{0}\".", printerName);
            Console.WriteLine(msg);
            return;
        }
        printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
        printDoc.Print();
    }
示例#6
0
        public DialogResult ShowDialog(Window parent)
        {
            if (parent?.HasFocus == false)
            {
                parent.Focus();
            }

            Control.SetEtoSettings(settings);
            var result = Control.ShowDialog();

            WpfFrameworkElementHelper.ShouldCaptureMouse = false;
            if (result == true)
            {
                settings.SetFromDialog(Control);
                Document?.Print();
                return(DialogResult.Ok);
            }
            return(DialogResult.Cancel);
        }
示例#7
0
文件: print.cs 项目: Diullei/Storm
 private void PrintOut(string data, bool file, bool prview)
 {
     try
     {
         using (streamToPrint = file ? (TextReader)new StreamReader (data) : (TextReader)new StringReader(data))
         {
             printFont = new Font("Arial", 10);
             PrintDocument pd = new PrintDocument();
             pd.PrintPage += new PrintPageEventHandler(PrintPageRoutine);
             if (prview)
             {
                 PrintPreviewDialog dlg = new PrintPreviewDialog();
                 dlg.Document = pd;
                 dlg.ShowDialog();
             }
             else
                 pd.Print();
         }
     }
     catch(Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
示例#8
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            locationstr = null;
            StringBuilder sb = new StringBuilder();

            if (SingleCompany == null && SingleCompanyName == string.Empty)
            {
                sb.AppendLine("請輸入公司名稱!");
            }
            if (m_AllTypes.GetSum() <= 0)
            {
                sb.AppendLine("沒有列印數量!");
            }
            if (sb.Length > 0)
            {
                MessageBox.Show(sb.ToString(), "注意", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            if (SingleCompany != null)
            {
                companyStr = SingleCompany.Name;
                switch (location)
                {
                case 0:
                    locationstr = "石牌";
                    break;

                case 1:
                    locationstr = "蘆洲";
                    break;

                case 2:
                    locationstr = "內湖";
                    break;
                }
            }
            else
            {
                companyStr = SingleCompanyName.Trim();
            }

            //開始列印


            //PrintingPage printpage = new PrintingPage(companystr, m_AllTypes, m_PrinterSetting);
            //printpage.Show();

            m_Pd1 = m_Pd2 = m_Pd3 = m_Pd4 = m_Pd5 = m_Pd6 = m_Pd7 = m_PdOneMore = null;

            StartPrint();

            if (m_Pd1 != null)
            {
                m_Pd1.Print();
            }
            if (m_Pd2 != null)
            {
                m_Pd2.Print();
            }
            if (m_Pd3 != null)
            {
                m_Pd3.Print();
            }
            if (m_Pd4 != null)
            {
                m_Pd4.Print();
            }
            if (m_Pd5 != null)
            {
                m_Pd5.Print();
            }
            if (m_Pd6 != null)
            {
                m_Pd6.Print();
            }
            if (m_Pd7 != null)
            {
                m_Pd7.Print();
            }
            if (m_PdOneMore != null)
            {
                m_PdOneMore.Print();
            }
        }
示例#9
0
 IEnumerator PrintProcess()
 {
     //實例列印物件
     PrintDocument pd = new PrintDocument();
     //加上事件
     pd.PrintPage += new PrintPageEventHandler(PrintImage);
     //執行列印
     pd.Print();
     yield return null;
 }
示例#10
0
        private void BtnPedidoTerminado_Click(object sender, EventArgs e)
        {
            tmrActualizaPedidos.Stop();

            int TotalDeFilas = dgvListaPedidos.Rows.Count;

            string InformacionDelError = string.Empty;

            ClsDetalles Detalles = new ClsDetalles();

            ClsPedidos Pedidos          = new ClsPedidos();
            Pedido     ActualizarPedido = new ClsPedidos();

            ClsDeliveries Delivery           = new ClsDeliveries();
            Delivery      ActualizarDelivery = new Delivery();

            for (int Indice = 0; Indice < TotalDeFilas; Indice++)
            {
                //Pregunto si la celda es diferente a null
                if (dgvListaPedidos.Rows[Indice].Cells[(int)ENumColDGVListaPedidos.Seleccionar].Value != null)
                {
                    //Casteo el check del objeto a booleano y pregunto si es true
                    if ((bool)dgvListaPedidos.Rows[Indice].Cells[(int)ENumColDGVListaPedidos.Seleccionar].Value)
                    {
                        InformacionDelError = string.Empty;

                        List <Detalle> ActualizarDetalle = Detalles.LeerListado((int)dgvListaPedidos.Rows[Indice].Cells[(int)ENumColDGVListaPedidos.ID_Pedido].Value, ClsDetalles.ETipoDeListado.ParaCocina, ref InformacionDelError);
                        ActualizarPedido = Pedidos.LeerPorNumero((int)dgvListaPedidos.Rows[Indice].Cells[(int)ENumColDGVListaPedidos.ID_Pedido].Value, ref InformacionDelError);

                        if (ActualizarDetalle != null && ActualizarPedido != null)
                        {
                            if (ActualizarPedido.ID_EstadoPedido == (int)ClsEstadosPedidos.EEstadosPedidos.EnProceso)
                            {
                                foreach (Detalle Elemento in ActualizarDetalle)
                                {
                                    if (Elemento.ID_EstadoDetalle == (int)ClsEstadoDetalle.EEstadoDetalle.CantidadAumentada)
                                    {
                                        Elemento.Cantidad        += Elemento.CantidadAgregada;
                                        Elemento.CantidadAgregada = 0;
                                    }

                                    Elemento.ID_EstadoDetalle = (int)ClsEstadoDetalle.EEstadoDetalle.YaCocinado;

                                    if (Detalles.Actualizar(Elemento, ref InformacionDelError) != 0)
                                    {
                                        dgvPlatosPorMesa.Rows.Clear();
                                        lblDetallesDelPedido.Text = string.Empty;
                                    }
                                    else if (InformacionDelError != string.Empty)
                                    {
                                        MessageBox.Show($"{InformacionDelError}", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                    }
                                }

                                if (ActualizarPedido.ID_Delivery == null)
                                {
                                    ActualizarPedido.TiempoEspera = null;
                                }

                                if (ActualizarPedido.ID_Delivery == null)
                                {
                                    ActualizarPedido.ID_EstadoPedido = (int)ClsEstadosPedidos.EEstadosPedidos.ParaEntrega;
                                }
                                else
                                {
                                    ActualizarPedido.ID_EstadoPedido = (int)ClsEstadosPedidos.EEstadosPedidos.Entregado;

                                    ActualizarDelivery = Delivery.LeerPorNumero(ActualizarPedido.ID_Delivery, ref InformacionDelError);

                                    if (ActualizarDelivery != null)
                                    {
                                        ActualizarDelivery.ID_EstadoDelivery = (int)ClsEstadosDeliveries.EEstadosDeliveries.ParaEntrega;

                                        if (Delivery.Actualizar(ActualizarDelivery, ref InformacionDelError) != 0)
                                        {
                                            FrmPrincipal.ObtenerInstancia().S_tslResultadoOperacion = "Delivery actualizado con exito";
                                        }
                                        else if (InformacionDelError == string.Empty)
                                        {
                                            FrmPrincipal.ObtenerInstancia().MensajeAdvertencia("Fallo al actualizar el delivery");
                                        }
                                        else
                                        {
                                            FrmPrincipal.ObtenerInstancia().MensajeAdvertencia("Fallo al actualizar el delivery");
                                            MessageBox.Show($"{InformacionDelError}", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                        }
                                    }
                                    else if (InformacionDelError == string.Empty)
                                    {
                                        FrmPrincipal.ObtenerInstancia().MensajeAdvertencia("Fallo al actualizar el delivery");
                                    }
                                    else
                                    {
                                        FrmPrincipal.ObtenerInstancia().MensajeAdvertencia("Fallo al actualizar el delivery");
                                        MessageBox.Show($"{InformacionDelError}", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                    }
                                }

                                if (Pedidos.Actualizar(ActualizarPedido, ref InformacionDelError) != 0)
                                {
                                    if (ActualizarPedido.ID_Delivery != null && ckbImprimirTicketDelivery.Checked)
                                    {
                                        ID_PedidoImprimir = ActualizarPedido.ID_Pedido;
                                        PtdImprimirTicket = new PrintDocument();

                                        if (ClsComprobarEstadoImpresora.ComprobarEstadoImpresora(PtdImprimirTicket.PrinterSettings.PrinterName))
                                        {
                                            PtdImprimirTicket.PrintPage += PrintPageEventHandler;
                                            PtdImprimirTicket.Print();
                                        }

                                        ID_PedidoImprimir = -1;
                                    }

                                    PedidosSeleccionados.RemoveAll(I => I == (int)dgvListaPedidos.Rows[Indice].Cells[(int)ENumColDGVListaPedidos.ID_Pedido].Value);

                                    lblMostrarNumeroPedido.Text = string.Empty;
                                    dgvPlatosPorMesa.Rows.Clear();
                                    dgvListaPedidos.Rows.Remove(dgvListaPedidos.Rows[Indice]);
                                    Indice       -= 1;
                                    TotalDeFilas -= 1;

                                    FrmPrincipal.ObtenerInstancia().S_tslResultadoOperacion = "Pedido actualizado";
                                }
                                else if (InformacionDelError != string.Empty)
                                {
                                    FrmPrincipal.ObtenerInstancia().MensajeAdvertencia("Fallo al actualizar el pedido");
                                    MessageBox.Show($"{InformacionDelError}", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                }
                            }
                            else
                            {
                                using (FrmInformacion FormInformacion = new FrmInformacion($"El pedido numero {ActualizarPedido.ID_Pedido}, no se indico como cocinado debido a " +
                                                                                           $"que fue retirado de la lista desde otra computadora y no llego a quitarse de esta al momento de indicarlo como terminado. " +
                                                                                           $"El pedido sera retirado de la lista al cerrar este mensaje (no se indicara como cocinado).", ClsColores.Blanco, 200, 400))
                                {
                                    FormInformacion.ShowDialog();
                                }

                                lblMostrarNumeroPedido.Text = string.Empty;
                                dgvPlatosPorMesa.Rows.Clear();
                                dgvListaPedidos.Rows.Remove(dgvListaPedidos.Rows[Indice]);
                                Indice       -= 1;
                                TotalDeFilas -= 1;
                            }
                        }
                        else if (InformacionDelError == string.Empty)
                        {
                            FrmPrincipal.ObtenerInstancia().MensajeAdvertencia("Fallo al actualizar el pedido");
                        }
                        else
                        {
                            FrmPrincipal.ObtenerInstancia().MensajeAdvertencia("Fallo al actualizar el pedido");
                            MessageBox.Show($"{InformacionDelError}", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                }
            }
            dgvListaPedidos.ClearSelection();
            tmrActualizaPedidos.Start();
        }
示例#11
0
 public void PrintToPDF()
 {
     document.Print();
 }
示例#12
0
        private void printButton_Click(object sender, EventArgs e)
        {
            var document = new PrintDocument();

            document.PrintPage += (s, page) =>
            {
                var lineHeight        = (int)Math.Ceiling(SystemFonts.DefaultFont.GetHeight(page.Graphics));
                var descriptionBounds = new Rectangle(
                    page.MarginBounds.X,
                    page.MarginBounds.Y,
                    page.MarginBounds.Width,
                    lineHeight
                    );

                page.Graphics.DrawString(
                    JoinIfNotEmpty(title, field),
                    SystemFonts.DefaultFont,
                    Brushes.Black,
                    descriptionBounds,
                    new StringFormat
                {
                    Alignment     = StringAlignment.Center,
                    LineAlignment = StringAlignment.Center
                }
                    );

                var imageBounds = new Rectangle(
                    page.MarginBounds.X,
                    page.MarginBounds.Y + lineHeight,
                    page.MarginBounds.Width,
                    page.MarginBounds.Height - lineHeight
                    );
                if (qrcode.Width < imageBounds.Width && qrcode.Height < imageBounds.Height)
                {
                    imageBounds = new Rectangle(
                        imageBounds.X + (int)(imageBounds.Width * 0.5f - qrcode.Width * 0.5f),
                        imageBounds.Y,
                        qrcode.Width,
                        qrcode.Height
                        );
                }
                else
                {
                    var scale = Math.Min(
                        imageBounds.Width / (float)qrcode.Width,
                        imageBounds.Height / (float)qrcode.Height
                        );

                    imageBounds = new Rectangle(
                        imageBounds.X + (int)(imageBounds.Width * 0.5f - (qrcode.Width * scale) * 0.5f),
                        imageBounds.Y,
                        (int)(qrcode.Width * scale),
                        (int)(qrcode.Height * scale)
                        );
                }

                page.Graphics.DrawImage(qrcode, imageBounds);
            };

            var print = new PrintDialog();

            print.Document = document;

            if (print.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    document.Print();
                }
                catch (Exception ex)
                {
                    MessageService.ShowWarning(ex);
                }
            }
        }
示例#13
0
        static void Main(string[] args)
        {
            var handle = GetConsoleWindow();
            //hides cosole window
            // ShowWindow(handle, SW_HIDE);
            String strConnString = "Data Source=192.168.5.1;Initial Catalog=WMS;User ID=bodek;";
            //multiple connections because each reader needs it's own connection
            SqlConnection conn  = new SqlConnection(strConnString);
            SqlConnection conn2 = new SqlConnection(strConnString);
            SqlConnection conn3 = new SqlConnection(strConnString);

            SqlDataReader rdr = null;


            try
            {
                //gets a new QC Alert
                string sql = "select top 1 AI._rid_, AI.inv_trace, AI.inv_trace_old, AI.user_id, AI.owner_id, AI.product_id, AI.location_id, AI.Transaction_time, OS.Carrier_id " +
                             " from audit_inventory AI, Outbound_shipments os " +
                             " where trantype = 'QC' and subtype = 'AUDIT' and AI.inv_trace=OS.Shipment_id " +
                             " and location_id is not null and exporttime_sys3 is null ";
                // Open the connection
                conn.Open();
                conn2.Open();
                conn3.Open();
                SqlCommand cmd = new SqlCommand(sql, conn);

                rdr = cmd.ExecuteReader();
                string Pickticket = "";
                string msg        = "";
                string header_msg = "";
                string RID        = "";
                string QCType     = "";



                while (rdr.Read())
                {
                    SqlDataReader Reader   = null;
                    SqlDataReader SDReader = null;
                    string        Auditsql;
                    string        ShortDescsql;
                    string        ShortDesc = "";



                    if (Pickticket != (rdr["inv_trace"].ToString() + rdr["inv_trace_old"].ToString()))
                    {
                        header_msg  = "\n **************************\n";
                        header_msg += " *** QC Pick Required ***\n";
                        header_msg += " Origional Pick Ticket:  " + rdr["inv_trace"] + rdr["inv_trace_old"];
                        header_msg += "\n CarrierID:  " + rdr["carrier_id"];
                        header_msg += "\n QC User ID:  " + rdr["user_id"];
                        header_msg += "\n Picker ID: " + rdr["owner_id"] + '\n';
                    }

                    Pickticket = (rdr["inv_trace"].ToString() + rdr["inv_trace_old"].ToString());

                    Auditsql = "select product_id, ISNULL(defect_id,'UNKNOWN') as QC_CODE,";

                    Auditsql += " ISNULL(defect_id_old,'0') as QUANTITY ";
                    Auditsql += " from audit_inventory_detail WITH (NOLOCK)";
                    Auditsql += " Where audit_inventory_rid = " + rdr["_rid_"];



                    SqlCommand Command = new SqlCommand(Auditsql, conn2);
                    Reader = Command.ExecuteReader();

                    while (Reader.Read())
                    {
                        ShortDescsql  = "select short_description from product_master WITH (NOLOCK)";
                        ShortDescsql += " where product_id = '" + rdr["product_id"] + "'";
                        SqlCommand SDCommand = new SqlCommand(ShortDescsql, conn3);
                        SDReader = SDCommand.ExecuteReader();
                        while (SDReader.Read())
                        {
                            ShortDesc = SDReader["short_description"].ToString();
                        }
                        SDReader.Close();
                        if (header_msg.Length > 0)
                        {
                            msg       += header_msg;
                            header_msg = "";
                        }

                        msg += "\n * * * * * * * * * * * * \n";
                        msg += "\n Error Time :    " + rdr["transaction_time"];
                        msg += "\n Product ID:     " + rdr["product_id"];
                        msg += "\n Description:  " + ShortDesc;
                        msg += "\n Location ID:  " + rdr["location_id"];
                        msg += "\n QC Code:  " + Reader["QC_CODE"];
                        msg += "\n Quantity:  " + Reader["Quantity"] + '\n';

                        QCType = Reader["QC_CODE"].ToString();
                    }

                    if (RID.Length == 0)
                    {
                        RID = rdr["_rid_"].ToString();
                    }
                    else
                    {
                        RID += ',' + rdr["_rid_"].ToString();
                    }



                    Console.WriteLine(msg);
                    Reader.Close();

                    PrintDocument   p         = new PrintDocument();
                    PrintController Controler = new StandardPrintController();
                    //designates a printer
                    p.PrinterSettings.PrinterName = "Norton QC";
                    //will hide the printing dialoge box
                    p.PrintController = Controler;
                    p.PrintPage      += delegate(object sender1, PrintPageEventArgs e1)
                    {
                        e1.Graphics.DrawString(msg, new Font("Times New Roman", 25), new SolidBrush(Color.Black), new RectangleF(0, 0, p.DefaultPageSettings.PrintableArea.Width, p.DefaultPageSettings.PrintableArea.Height));
                    };
                    try
                    {
                        //if(QCType!="PLS")
                        p.Print();
                    }

                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                        // Console.ReadLine();
                    }
                }
                updateAuditInventory(RID);
                rdr.Close();
                // Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                //  Console.ReadLine();
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }

                if (conn2 != null)
                {
                    conn2.Close();
                }

                if (conn3 != null)
                {
                    conn3.Close();
                }
            }
        }
        private void btnBookSeats_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                Dispatcher.Invoke(DispatcherPriority.Background, new Action(() => ManageLoadingDataVisibility(true)));
                if (Seats.Where(x => x.IsEnabled && x.IsChecked).ToList().Count() == 0)
                {
                    ModernDialog.ShowMessage("Please Select seats", "Alert", MessageBoxButton.OK);
                }
                else if (Seats.Where(x => x.IsEnabled && x.IsChecked).ToList().Count() > Convert.ToInt32(ConfigurationSettings.AppSettings["MaxBookingSeats"]))
                {
                    ModernDialog.ShowMessage(string.Format("You can select Maximum {0} seats only", Convert.ToInt32(ConfigurationSettings.AppSettings["MaxBookingSeats"])), "Alert", MessageBoxButton.OK);
                }
                else if (Seats.Where(x => x.IsEnabled && x.IsChecked).ToList().GroupBy(l => l.ScreenClassId).Count() > 1)
                {
                    ModernDialog.ShowMessage("Please Book tickets from Only one Class, You Can't book tickets from multiple classes", "Alert", MessageBoxButton.OK);
                }
                else if (Seats.Where(x => x.IsEnabled && x.IsChecked).ToList().Count() != Convert.ToInt32((lstSeats.SelectedValue as ListBoxItem).Content))
                {
                    ModernDialog.ShowMessage("Required seats and selected seats count is not matched.", "Alert", MessageBoxButton.OK);
                }
                else
                {
                    //if (ModernDialog.ShowMessage("Are you sure you want to continue booking?", string.Format("Confirmation"), MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    //{
                    var selectedSeats = Seats.Where(x => x.IsEnabled && x.IsChecked).ToList();
                    var seats         = string.Join(",", selectedSeats.Select(x => x.Id));

                    var result = new MovieTimingsRepository().InsertMovieBooking(Convert.ToInt32(lstMovie.SelectedValue), selectedSeats.Count(), Convert.ToDouble(Seats.Where(x => x.IsEnabled && x.IsChecked).ToList().Sum(x => x.TicketCost)), selectedSeats.FirstOrDefault().ScreenClassId, Convert.ToInt32(lstScreen.SelectedValue), Convert.ToInt32((lstTimes.SelectedItem as Movie).Id), seats);

                    if (result == 0)
                    {
                        if (ModernDialog.ShowMessage("Tickets already reserved, Please reload and try another seats..", "Alert", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                        {
                            LoadBookedTickets();
                        }
                    }
                    else
                    {
                        order_Id = result;
                        PrintDocument pd = new PrintDocument();
                        PaperSize     ps = new PaperSize("", 475, 550);

                        pd.PrintPage += new PrintPageEventHandler(ticket_PrintPage);

                        pd.PrintController = new StandardPrintController();
                        pd.DefaultPageSettings.Margins.Left   = 0;
                        pd.DefaultPageSettings.Margins.Right  = 0;
                        pd.DefaultPageSettings.Margins.Top    = 0;
                        pd.DefaultPageSettings.Margins.Bottom = 0;

                        pd.DefaultPageSettings.PaperSize = ps;
                        pd.Print();

                        //ModernDialog.ShowMessage("Tickets booking confired successfully", "Alert", MessageBoxButton.OK);
                        LoadBookedTickets();
                        stkBooking.Visibility = Visibility.Collapsed;
                    }
                    //}
                }

                Dispatcher.Invoke(DispatcherPriority.Background, new Action(() => ManageLoadingDataVisibility(false)));
            }
            catch (Exception ex)
            {
                ManageLoadingDataVisibility(false);
                LogExceptions.LogException(ex);
            }
        }
示例#15
0
        //Для неизвестного клиента
        private void CreateTab()
        {
            //добавление вкладки
            TabPage newTabPage = new TabPage();

            newTabPage.Text = "Клиент" + i++;
            tabControl1.TabPages.Add(newTabPage);

            Label   lbIdDriver = new Label();
            TextBox tbIdDriver = new TextBox();

            Label   lbSurnameDriver = new Label();
            TextBox tbSurnameDriver = new TextBox();

            Label   lbNameDriver = new Label();
            TextBox tbNameDriver = new TextBox();

            Label   lbPatronimycDriver = new Label();
            TextBox tbPatronimycDriver = new TextBox();

            Label   lbModelCar = new Label();
            TextBox tbModelCar = new TextBox();

            Label   lbBrandCar = new Label();
            TextBox tbBrandCar = new TextBox();

            Label   lbYearCar = new Label();
            TextBox tbYearCar = new TextBox();

            Label   lbNumberSTSCar = new Label();
            TextBox tbNumberSTSCar = new TextBox();

            Label   lbPhoneNumber = new Label();
            TextBox tbPhoneNumber = new TextBox();

            lbIdDriver.Text     = "ID водителя: ";
            lbIdDriver.Width    = 130;
            lbIdDriver.Location = new Point(10, 20);
            newTabPage.Controls.Add(lbIdDriver);

            tbIdDriver.Location = new Point(150, 20);
            newTabPage.Controls.Add(tbIdDriver);

            lbSurnameDriver.Text     = "Фамилия водителя: ";
            lbSurnameDriver.Width    = 130;
            lbSurnameDriver.Location = new Point(10, 50);
            newTabPage.Controls.Add(lbSurnameDriver);

            tbSurnameDriver.Location = new Point(150, 50);
            newTabPage.Controls.Add(tbSurnameDriver);

            lbNameDriver.Text     = "Имя водителя: ";
            lbNameDriver.Width    = 130;
            lbNameDriver.Location = new Point(10, 80);
            newTabPage.Controls.Add(lbNameDriver);

            tbNameDriver.Location = new Point(150, 80);
            newTabPage.Controls.Add(tbNameDriver);

            lbPatronimycDriver.Text     = "Отчество водителя: ";
            lbPatronimycDriver.Width    = 130;
            lbPatronimycDriver.Location = new Point(10, 110);
            newTabPage.Controls.Add(lbPatronimycDriver);

            tbPatronimycDriver.Location = new Point(150, 110);
            newTabPage.Controls.Add(tbPatronimycDriver);

            lbPhoneNumber.Text     = "Мобильный телефон: ";
            lbPhoneNumber.Width    = 130;
            lbPhoneNumber.Location = new Point(10, 140);
            newTabPage.Controls.Add(lbPhoneNumber);

            tbPhoneNumber.Location = new Point(150, 140);
            newTabPage.Controls.Add(tbPhoneNumber);

            lbModelCar.Text     = "Модель машины: ";
            lbModelCar.Width    = 130;
            lbModelCar.Location = new Point(10, 170);
            newTabPage.Controls.Add(lbModelCar);

            tbModelCar.Location = new Point(150, 170);
            newTabPage.Controls.Add(tbModelCar);

            lbBrandCar.Text     = "Марка машины: ";
            lbBrandCar.Width    = 130;
            lbBrandCar.Location = new Point(10, 200);
            newTabPage.Controls.Add(lbBrandCar);

            tbBrandCar.Location = new Point(150, 200);
            newTabPage.Controls.Add(tbBrandCar);

            lbYearCar.Text     = "Год выпуска: ";
            lbYearCar.Width    = 130;
            lbYearCar.Location = new Point(10, 230);
            newTabPage.Controls.Add(lbYearCar);

            tbYearCar.Location = new Point(150, 230);
            newTabPage.Controls.Add(tbYearCar);

            lbNumberSTSCar.Text     = "Номер СТС: ";
            lbNumberSTSCar.Width    = 130;
            lbNumberSTSCar.Location = new Point(10, 260);
            newTabPage.Controls.Add(lbNumberSTSCar);

            tbNumberSTSCar.Location = new Point(150, 260);
            newTabPage.Controls.Add(tbNumberSTSCar);


            Label lbAddRepairs = new Label();

            lbAddRepairs.Text     = "Добавить ремонтную работу:";
            lbAddRepairs.Width    = 200;
            lbAddRepairs.Location = new Point(300, 20);
            newTabPage.Controls.Add(lbAddRepairs);

            //Сотрудник, выполняющий работу
            Label lbEmployee = new Label();

            lbEmployee.Text     = "Сотрудник, выполняющий работу:";
            lbEmployee.Width    = 200;
            lbEmployee.Location = new Point(300, 170);
            newTabPage.Controls.Add(lbEmployee);

            ComboBox cbEmployee = new ComboBox();

            cbEmployee.Location      = new Point(300, 200);
            cbEmployee.Width         = 260;
            cbEmployee.DropDownStyle = ComboBoxStyle.DropDownList;
            newTabPage.Controls.Add(cbEmployee);

            //Ремонтная работа
            Label lbNameRepairs = new Label();

            lbNameRepairs.Text     = "Ремонтная работа:";
            lbNameRepairs.Width    = 200;
            lbNameRepairs.Location = new Point(300, 110);
            newTabPage.Controls.Add(lbNameRepairs);

            ComboBox cbNameRepairs = new ComboBox();

            cbNameRepairs.Location      = new Point(300, 140);
            cbNameRepairs.Width         = 260;
            cbNameRepairs.DropDownStyle = ComboBoxStyle.DropDownList;
            newTabPage.Controls.Add(cbNameRepairs);
            cbNameRepairs.SelectedIndexChanged += (sender, e) =>
            {
                cbEmployee.Items.Clear();
                db.SearchSurnameEmployeesForRepair(cbEmployee, cbNameRepairs.Text.ToString());
            };

            //Категория ремнотной работы
            Label lbCategoryRepairs = new Label();

            lbCategoryRepairs.Text     = "Категория ремнотной работы:";
            lbCategoryRepairs.Width    = 200;
            lbCategoryRepairs.Location = new Point(300, 50);
            newTabPage.Controls.Add(lbCategoryRepairs);

            ComboBox cbCategoryRepairs = new ComboBox();

            cbCategoryRepairs.Location = new Point(300, 80);
            cbCategoryRepairs.Width    = 260;
            db.SearchCategories(cbCategoryRepairs);
            cbCategoryRepairs.DropDownStyle = ComboBoxStyle.DropDownList;
            newTabPage.Controls.Add(cbCategoryRepairs);
            cbCategoryRepairs.SelectedIndexChanged += (sender, e) =>
            {
                cbNameRepairs.Items.Clear();
                db.SearchNameRepairs(cbCategoryRepairs.Text.ToString(), cbNameRepairs);
            };

            //Кнопка сохранить
            Button btSaveChanges = new Button();

            btSaveChanges.Height   = 50;
            btSaveChanges.Width    = 150;
            btSaveChanges.Text     = "Сохранить изменения";
            btSaveChanges.Location = new Point(200, 400);
            newTabPage.Controls.Add(btSaveChanges);
            btSaveChanges.Click += (sender, args) =>
            {
                if (tbSurnameDriver.Text == "" || tbNameDriver.Text == "" || tbPatronimycDriver.Text == "" || tbBrandCar.Text == "" ||
                    tbModelCar.Text == "" || tbYearCar.Text == "" || tbNumberSTSCar.Text == "")
                {
                    MessageBox.Show("Пожалуйста, заполните все поля");
                    return;
                }

                AddClientToDB(tbSurnameDriver.Text, tbNameDriver.Text, tbPatronimycDriver.Text, tbPhoneNumber.Text, tbBrandCar.Text, tbModelCar.Text,
                              tbYearCar.Text, tbNumberSTSCar.Text);
                newTabPage.Text = tbNameDriver.Text + "/" + tbModelCar.Text;
                MessageBox.Show("Изменения сохранены");
            };

            Label lbRepairs = new Label();

            lbRepairs.Text     = "Ремонтные работы по машине:";
            lbRepairs.Width    = 200;
            lbRepairs.Location = new Point(600, 20);
            newTabPage.Controls.Add(lbRepairs);

            Label labRepairsCosts = new Label();

            labRepairsCosts.Text     = "Стоимость:";
            labRepairsCosts.Width    = 70;
            labRepairsCosts.Location = new Point(910, 20);
            newTabPage.Controls.Add(labRepairsCosts);

            Label labEmployeesRepairs = new Label();

            labEmployeesRepairs.Text     = "Сотрудник:";
            labEmployeesRepairs.Width    = 200;
            labEmployeesRepairs.Location = new Point(990, 20);
            newTabPage.Controls.Add(labEmployeesRepairs);

            //Список цен на работы
            ListBox lbRepairsCosts = new ListBox();

            lbRepairsCosts.Height   = 500;
            lbRepairsCosts.Width    = 70;
            lbRepairsCosts.Location = new Point(910, 50);
            newTabPage.Controls.Add(lbRepairsCosts);

            //Список сотруников, выполняющих работу
            ListBox lbEmployeesRepairs = new ListBox();

            lbEmployeesRepairs.Height   = 500;
            lbEmployeesRepairs.Width    = 150;
            lbEmployeesRepairs.Location = new Point(990, 50);
            newTabPage.Controls.Add(lbEmployeesRepairs);

            //Список работ проводимых по машине
            CheckedListBox clbRepairs = new CheckedListBox();

            clbRepairs.Height   = 500;
            clbRepairs.Width    = 300;
            clbRepairs.Location = new Point(600, 50);
            newTabPage.Controls.Add(clbRepairs);
            clbRepairs.SelectedIndexChanged += (sender, args) =>
            {
                lbEmployeesRepairs.SelectedIndex = clbRepairs.SelectedIndex;
                lbRepairsCosts.SelectedIndex     = clbRepairs.SelectedIndex;

                if (clbRepairs.GetItemChecked(clbRepairs.SelectedIndex)) //&& clbRepairs.SelectedIndex != -1) - проверка для того чтобы нельзя было нажать на пустой clb
                {
                    string[] strEmployee = lbEmployeesRepairs.SelectedItem.ToString().Split(new char[] { ' ' });
                    int      idEmployee  = Convert.ToInt32(strEmployee[strEmployee.Length - 1]);

                    string factQuery;
                    FormWorkHoursRepairs fwhr = new FormWorkHoursRepairs();
                    factQuery = "(`work_hours_id_work_hours`, `repairs_id_repair`, `clients_id_client`, `time_start`, `time_finish`) VALUES('" +
                                db.SearchIdWorkHours(idEmployee, DateTime.Today.ToString("yyyy-MM-dd")) + "', '" +
                                db.SearchIdRepairs(clbRepairs.SelectedItem.ToString()) +
                                "', '" + tbIdDriver.Text + "', '" + timeStartRepair + "', '" + DateTime.Now.ToString("HH:mm:ss") + "');";
                    db.Add("current_repairs", factQuery, fwhr.dgvWorkHoursRepairs);
                }
            };

            //Общая стоимость
            Label lbRepairsTotalCost = new Label();

            lbRepairsTotalCost.Text     = "Итоговая стоимость:\n" + 0 + " рублей";
            lbRepairsTotalCost.Width    = 100;
            lbRepairsTotalCost.Height   = 100;
            lbRepairsTotalCost.Location = new Point(910, 550);
            newTabPage.Controls.Add(lbRepairsTotalCost);

            //Кнопка добавить ремонтные работы
            Button btAddRepairs = new Button();

            btAddRepairs.Height   = 50;
            btAddRepairs.Width    = 150;
            btAddRepairs.Text     = "Добавить работу по машине";
            btAddRepairs.Location = new Point(300, 260);
            newTabPage.Controls.Add(btAddRepairs);
            btAddRepairs.Click += (sender, args) =>
            {
                if (cbNameRepairs.Text != "" && cbEmployee.Text != "")
                {
                    clbRepairs.Items.Add(cbNameRepairs.Text);
                    db.SearchCostRepairs(cbNameRepairs.Text, lbRepairsCosts);
                    lbEmployeesRepairs.Items.Add(cbEmployee.Text);
                    int totalCost = 0;

                    for (int i = 0; i < lbRepairsCosts.Items.Count; i++)
                    {
                        totalCost += Convert.ToInt32(lbRepairsCosts.Items[i].ToString());
                    }

                    lbRepairsTotalCost.Text = "Итоговая стоимость:\n" + totalCost + " рублей";
                }
                else
                {
                    MessageBox.Show("Пожалуйста, заполните все поля", "Ошибка");
                }
            };


            //Печать
            PrintDocument printDocument1 = new PrintDocument();

            printDocument1.PrintPage += (sender, e) =>
            {
                String repairs = "";
                for (int i = 0; i < clbRepairs.Items.Count; i++)
                {
                    repairs += i + 1 + ". " + clbRepairs.Items[i].ToString() + "\n";
                }

                String result =
                    tbNameDriver.Text + ", спасибо, что выбрали именно нас!" + "\n\n" +
                    "\t" + "Счёт на оказание услуг авторемонта:" + "\n\n" +
                    repairs + "\n" +
                    "Итоговая стоимость: ";

                int    totalCost = 0;
                String costs     = "";
                for (int i = 0; i < lbRepairsCosts.Items.Count; i++)
                {
                    costs     += lbRepairsCosts.Items[i].ToString() + " рублей" + "\n";
                    totalCost += Convert.ToInt32(lbRepairsCosts.Items[i].ToString());
                }

                String resultCost = costs + "\n" + totalCost + " рублей";

                e.Graphics.DrawString(result, new Font("Arial", 12), Brushes.Black, 100, 100);
                e.Graphics.DrawString(resultCost, new Font("Arial", 12), Brushes.Black, 600, 160);
            };

            //Кнопка Печать - составление счёта на оказание услуг
            Button btPrint = new Button();

            btPrint.Height   = 50;
            btPrint.Width    = 150;
            btPrint.Text     = "Печатать счёт";
            btPrint.Location = new Point(30, 400);
            newTabPage.Controls.Add(btPrint);
            btPrint.Click += (sender, args) =>
            {
                PrintDialog printDialog = new PrintDialog();
                printDialog.Document = printDocument1;

                if (printDialog.ShowDialog() == DialogResult.OK)
                {
                    printDocument1.Print();
                }
            };

            //Кнопка завершить работу по клиенту
            Button btFinishRepair = new Button();

            btFinishRepair.Height   = 50;
            btFinishRepair.Width    = 150;
            btFinishRepair.Text     = "Завершить работу по машине";
            btFinishRepair.Location = new Point(370, 400);
            newTabPage.Controls.Add(btFinishRepair);
            btFinishRepair.Click += (sender, args) =>
            {
                tabControl1.TabPages.Remove(newTabPage);
            };
        }
示例#16
0
        public static void Print()
        {
            IsPrinting = true;

            if (!Ipaybox.WindowsPrinter)
            {
                // Печатаем
                if (Ipaybox.Printer != null && Ipaybox.Printer.port != null)
                {
                    if (Ipaybox.Printer.Test())
                    {
                        Ipaybox.AddToLog(Ipaybox.Logs.Main, "Печатаем чек");
                        Ipaybox.Printer.Print(PrintString);
                    }
                    else
                    {
                        Ipaybox.AddToLog(Ipaybox.Logs.Main, "Чек не напечатан. Ошибка");
                    }
                }
                else
                {
                    if (Ipaybox.KKMPrim21K)
                    {
                        Ipaybox.AddToLog(Ipaybox.Logs.Main, "Печатаем чек");

                        if (Ipaybox.prim21k.Model != _prim21k.KKMModel.NULL)
                        {
                            int res = Ipaybox.prim21k.PrintPND(PrintString);

                            if (res == 0)
                            {
                                Ipaybox.AddToLog(Ipaybox.Logs.Main, "Чек успешно распечатан");
                            }
                            else
                            {
                                Ipaybox.AddToLog(Ipaybox.Logs.Main, "Ошибка при печати чека. " + Ipaybox.prim21k.LastAnswer);
                            }
                        }
                        else
                        {
                            Ipaybox.AddToLog(Ipaybox.Logs.Main, "Чек не напечатан. Ошибка. Порт не определен.");
                            Ipaybox.Working = false;
                        }
                    }
                    else
                    if (Ipaybox.FiscalRegister)
                    {
                        if (Ipaybox.FRegister != null)
                        {
                            Ipaybox.AddToLog(Ipaybox.Logs.Main, "Печатаем чек");
                            Ipaybox.FRegister.PrintText(PrintString);
                        }
                    }
                    else
                    {
                        Ipaybox.AddToLog(Ipaybox.Logs.Main, "Чек не напечатан. Ошибка");
                        //new System.Threading.Thread(SendMonitoring).Start();
                    }
                }
            }
            else
            {
                try
                {
                    Ipaybox.AddToLog(Ipaybox.Logs.Main, "Печатаем чек через WINDOWS PRINTER");
                    doc.Print();
                }
                catch (Exception ex)
                {
                    Ipaybox.AddToLog(Ipaybox.Logs.Main, "Не удалось распечатать чек \r\n" + ex.Message);
                    //new System.Threading.Thread(SendMonitoring).Start();
                }
            }

            PrintString         = "";
            IsPrinting          = false;
            Ipaybox.IncassCheck = false;
        }
示例#17
0
        private void button7_Click(object sender, EventArgs e)
        {
            timer2.Stop();
            timer2.Start();

            if (Ipaybox.Printer != null)
            {
                if (Ipaybox.Printer.Test())
                {
                    // Загружаем шаблон для текущей модели прнтера
                    string   find = Ipaybox.Printer.PrnModel.ToString();
                    FileInfo fi   = new FileInfo(Ipaybox.StartupPath + "\\config\\" + find + ".prn");

                    try
                    {
                        StreamReader sr    = fi.OpenText();
                        string       check = sr.ReadToEnd();
                        sr.Close();

                        check = check.Replace("[agent_jur_name]", Ipaybox.Terminal.jur_name.Trim());
                        check = check.Replace("[agent_adress]", Ipaybox.Terminal.jur_adress.Trim());
                        check = check.Replace("[agent_inn]", "ИНН " + Ipaybox.Terminal.jur_inn.Trim());
                        check = check.Replace("[agent_support_phone]", Ipaybox.Terminal.support_phone.Trim());
                        check = check.Replace("[bank]", Ipaybox.Terminal.bank.Trim());
                        check = check.Replace("[terms_number]", Ipaybox.Terminal.terms_number.Trim());
                        check = check.Replace("[count_bill]", Ipaybox.Incass.countchecks.ToString().Trim());
                        check = check.Replace("[terminal_id]", Ipaybox.Terminal.terminal_id.Trim());
                        check = check.Replace("[trm_adress]", Ipaybox.Terminal.trm_adress.Trim());
                        check = check.Replace("[date]", DateTime.Now.ToString().Trim());
                        check = check.Replace("[amount]", Ipaybox.curPay.from_amount.ToString() + " руб.");
                        check = check.Replace("[to_amount]", Ipaybox.curPay.to_amount.ToString() + " руб.");

                        if (Ipaybox.FRS.RemoteFR)
                        {
                            byte[] bytes = remoteFR.RemoteFiscalRegister.convertToByteArray(Ipaybox.Terminal.jur_name.Trim(), Ipaybox.FRS.headertext, check, "Тест", Ipaybox.Terminal.terminal_id.Trim(), Ipaybox.Terminal.terminal_pass, "0", "0", "1", Ipaybox.FRS.RemoteFiscalRegisterURL, Ipaybox.FRS.checkWidth, Ipaybox.FRS.remoteFRtimeout);

                            if (bytes.Length > 0)
                            {
                                Ipaybox.Printer.PrintFromBytes(bytes);

                                if (remoteFR.RemoteFiscalRegister.OK)
                                {
                                    Ipaybox.AddToLog(Ipaybox.Logs.Main, "Данные с ФС получены. Печать фискального чека.");
                                }
                                else
                                {
                                    Ipaybox.AddToLog(Ipaybox.Logs.Main, "Данные с ФС НЕ получены. Печать нефискального чека с заголовком.");
                                }
                            }
                            else
                            {
                                Ipaybox.Printer.Print("ШАБЛОН " + fi.Name + "\r\n" + check);
                                Ipaybox.AddToLog(Ipaybox.Logs.Main, "Данные с ФС НЕ получены. Печать нефискального чека.");
                            }
                        }
                        else
                        {
                            Ipaybox.Printer.Print("ШАБЛОН " + fi.Name + "\r\n" + check);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Не могу найти шаблон для принтера. Поставьте терминал на обновление. " + ex.Message + " " + fi.FullName);
                    }
                }
                else
                {
                    MessageBox.Show("Принтер НЕИСПРАВЕН.");
                }
            }
            else
            if (Ipaybox.WindowsPrinter)
            {
                try
                {
                    doc.Print();
                }
                catch (Exception ex)
                {
                    Ipaybox.AddToLog(Ipaybox.Logs.Main, "Не удалось напечатать чек! " + ex.Message);
                }
            }
            else
            {
                if (Ipaybox.KKMPrim21K)
                {
                    if (Ipaybox.prim21k.Model != _prim21k.KKMModel.NULL)
                    {
                        string   find = "prm";
                        FileInfo fi   = new FileInfo(Ipaybox.StartupPath + "\\config\\" + find + ".prn");
                        if (!fi.Exists)
                        {
                            throw new Exception("Не найден шаблон! Обновите программу!");
                        }
                        StreamReader sr    = fi.OpenText();
                        string       check = sr.ReadToEnd();
                        sr.Close();

                        check = check.Replace("[agent_jur_name]", Ipaybox.Terminal.jur_name.Trim());
                        check = check.Replace("[agent_adress]", Ipaybox.Terminal.jur_adress.Trim());
                        check = check.Replace("[agent_inn]", "ИНН " + Ipaybox.Terminal.jur_inn.Trim());
                        check = check.Replace("[agent_support_phone]", Ipaybox.Terminal.support_phone.Trim());
                        check = check.Replace("[bank]", Ipaybox.Terminal.bank.Trim());
                        check = check.Replace("[terms_number]", Ipaybox.Terminal.terms_number.Trim());
                        check = check.Replace("[count_bill]", Ipaybox.Incass.countchecks.ToString().Trim());
                        check = check.Replace("[terminal_id]", Ipaybox.Terminal.terminal_id.Trim());
                        check = check.Replace("[trm_adress]", Ipaybox.Terminal.trm_adress.Trim());
                        check = check.Replace("[date]", DateTime.Now.ToString().Trim());
                        check = check.Replace("[amount]", Ipaybox.curPay.from_amount.ToString() + " руб.");
                        check = check.Replace("[to_amount]", Ipaybox.curPay.to_amount.ToString() + " руб.");

                        if (Ipaybox.FRS.RemoteFR)
                        {
                            try
                            {
                                check = remoteFR.RemoteFiscalRegister.tryFormFicsalCheck(Ipaybox.Terminal.jur_name.Trim(), Ipaybox.FRS.headertext, check, "Тест", Ipaybox.Terminal.terminal_id.Trim(), Ipaybox.Terminal.terminal_pass, "0", "0", "1", Ipaybox.FRS.RemoteFiscalRegisterURL, Ipaybox.FRS.checkWidth, Ipaybox.FRS.remoteFRtimeout);
                            }
                            catch (Exception ex) { Ipaybox.AddToLog(Ipaybox.Logs.Main, ex.Message); }
                        }

                        int res = Ipaybox.prim21k.PrintPND(check);

                        if (res != 0)
                        {
                            MessageBox.Show("Ошибка при распечатке чека! " + Ipaybox.prim21k.LastAnswer);
                        }
                    }
                    else
                    {
                        MessageBox.Show("Ошибка! Принтер не обнаружен!");
                    }
                }
                else
                if (Ipaybox.FiscalRegister)
                {
                    if (Ipaybox.FRegister != null)
                    {
                        string   find = "VKP80";
                        FileInfo fi   = new FileInfo(Ipaybox.StartupPath + "\\config\\" + find + ".prn");
                        if (!fi.Exists)
                        {
                            throw new Exception("Не найден шаблон! Обновите программу!");
                        }
                        StreamReader sr    = fi.OpenText();
                        string       check = sr.ReadToEnd();
                        sr.Close();

                        check = check.Replace("[agent_jur_name]", Ipaybox.Terminal.jur_name.Trim());
                        check = check.Replace("[agent_adress]", Ipaybox.Terminal.jur_adress.Trim());
                        check = check.Replace("[agent_inn]", "ИНН " + Ipaybox.Terminal.jur_inn.Trim());
                        check = check.Replace("[agent_support_phone]", Ipaybox.Terminal.support_phone.Trim());
                        check = check.Replace("[bank]", Ipaybox.Terminal.bank.Trim());
                        check = check.Replace("[terms_number]", Ipaybox.Terminal.terms_number.Trim());
                        check = check.Replace("[count_bill]", Ipaybox.Incass.countchecks.ToString().Trim());
                        check = check.Replace("[terminal_id]", Ipaybox.Terminal.terminal_id.Trim());
                        check = check.Replace("[trm_adress]", Ipaybox.Terminal.trm_adress.Trim());
                        check = check.Replace("[date]", DateTime.Now.ToString().Trim());
                        check = check.Replace("[amount]", Ipaybox.curPay.from_amount.ToString() + " руб.");
                        check = check.Replace("[to_amount]", Ipaybox.curPay.to_amount.ToString() + " руб.");

                        if (Ipaybox.FRegister.FiscalMode)
                        {
                            Ipaybox.FRegister.Buy("Сотовая св.", 1, 0, "ШАБЛОН " + fi.Name + "\r\n" + check);
                        }
                        else
                        {
                            string s = check;

                            try
                            {
                                s = remoteFR.RemoteFiscalRegister.tryFormFicsalCheck(Ipaybox.Terminal.jur_name.Trim(), Ipaybox.FRS.headertext, check, "Тест", Ipaybox.Terminal.terminal_id.Trim(), Ipaybox.Terminal.terminal_pass, "0", "0", "1", Ipaybox.FRS.RemoteFiscalRegisterURL, Ipaybox.FRS.checkWidth, Ipaybox.FRS.remoteFRtimeout);
                            }
                            catch (Exception ex)
                            {
                                Ipaybox.AddToLog(Ipaybox.Logs.Main, ex.Message);
                            }

                            if (!Ipaybox.FRegister.PrintText("ШАБЛОН " + fi.Name + "\r\n" + s))
                            {
                                label8.Text      = "ФР " + Ipaybox.FRegister.Model + " неисправен. #" + Ipaybox.FRegister.ErrorNumber + "(" + Ipaybox.FRegister.ErrorMessage + ")";
                                label8.ForeColor = System.Drawing.Color.Red;
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("ФИСКАЛЬНЫЙ РЕГИСТРАТОР НЕ ОБНАРУЖЕН.");
                    }
                }
                else
                {
                    MessageBox.Show("Принтер НЕ ОБНАРУЖЕН.");
                }
            }
        }
        private void btnPrintBill_Click(object sender, EventArgs e)
        {
            string path     = @"D:\RartionCard\RationCard\RationCard\image";//Directory.GetCurrentDirectory() + "/Bills_" + GetDateStamp();
            string fileName = "/" + GetDateTimeStamp() + ".pdf";

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            FileStream flStrm = new FileStream(path + fileName, FileMode.Create);

            iTextSharp.text.Rectangle pgSize = new iTextSharp.text.Rectangle(Utilities.MillimetersToPoints(80), Utilities.MillimetersToPoints(127));
            iTextSharp.text.Document  pdfDoc = new iTextSharp.text.Document(pgSize, 1, 1, 1, 1);
            PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, flStrm);

            pdfDoc.Open();

            var para = new Paragraph(lblCashMemo.Text
                                     + "                 " + lblBillNoText.Text + "  " + lblCashMemoCounter.Text
                                     + Environment.NewLine + lblDt.Text
                                     + Environment.NewLine + "-------------------------------------------------------"
                                     + Environment.NewLine + lblFpsDealer.Text
                                     + Environment.NewLine + lblFPSCodeNo.Text
                                     + Environment.NewLine + lblAddrLn1.Text
                                     + Environment.NewLine + lblAddrLn2.Text
                                     + Environment.NewLine + lblAddrLn3.Text
                                     + Environment.NewLine + "-------------------------------------------------------"
                                     , new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 11));

            //Header
            iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(@"D:\RartionCard\RationCard\RationCard\image\logo.jpg");
            jpg.ScaleToFit(80f, 60f);
            jpg.SpacingBefore = 1f;
            jpg.SpacingAfter  = 1f;
            jpg.Alignment     = Element.ALIGN_CENTER;

            //Members
            para.Add(new Chunk(Environment.NewLine + Environment.NewLine + lblMembersText.Text, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 9)));

            //Items
            foreach (DataGridViewRow lnItem in grdVwMembers.Rows)
            {
                para.Add(new Chunk(Environment.NewLine + lnItem.Cells["Name"].Value.ToString()
                                   + "        " + lnItem.Cells["Number"].Value.ToString()
                                   , new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 9)));
            }

            //Items
            para.Add(new Chunk(Environment.NewLine + Environment.NewLine + lblItemsText.Text, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 9)));
            foreach (DataGridViewRow lnItem in grdVwItems.Rows)
            {
                para.Add(new Chunk(Environment.NewLine + lnItem.Cells["Commodity"].Value.ToString()
                                   + " ( " + lnItem.Cells["Quantity"].Value.ToString() + " " + lnItem.Cells["Uom"].Value.ToString() + " )"
                                   + "    " + lnItem.Cells["Rate"].Value.ToString()
                                   + "        " + lnItem.Cells["Price"].Value.ToString()
                                   , new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 7)));
            }

            //Total Price
            para.Add(new Chunk(Environment.NewLine + "-------------------------------------------------------" + Environment.NewLine
                               + lblTotal.Text
                               + "                             " + lblCustomerToPayRs.Text
                               + Environment.NewLine + lblTotalRoundedOff.Text
                               + "                             " + lblTotalRsRounded.Text
                               + Environment.NewLine + lblDiscountText.Text
                               + "                             " + lblDiscount.Text
                               + Environment.NewLine + lblCustomerPaid.Text
                               + "                             " + txtCustPaid.Text
                               + Environment.NewLine + lblBalance.Text
                               + "                             " + lblBalRs.Text

                               , new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 9)));


            pdfDoc.Add(jpg);
            pdfDoc.Add(para);
            pdfWriter.CloseStream = false;
            pdfDoc.Close();
            flStrm.Close();
            pdfWriter.Close();

            //Process p = new Process();
            //p.StartInfo = new ProcessStartInfo()
            //{
            //    //CreateNoWindow = true,
            //    //Verb = "print",
            //    FileName = path + fileName //put the correct path here
            //};
            //p.Start();

            // initialize PrintDocument object
            PrintDocument doc = new PrintDocument()
            {
                PrinterSettings = new PrinterSettings()
                {
                    // set the printer to 'Microsoft Print to PDF'
                    PrinterName = "EPSON TM-T82 Receipt",

                    // set the filename to whatever you like (full path)
                    PrintFileName = path + "/" + "2018211161323264.pdf"
                }
            };

            doc.Print();
        }
示例#19
0
        private void button8_Click(object sender, EventArgs e)
        {
            //anamenu.ActiveForm.IsMdiContainer = false;



            if (textBox12.Text == "")
            {
                MessageBox.Show("Kitap barkod numarası girilmesi gereken bir parametredir..!");
            }
            else if (textBox3.Text == "")
            {
                MessageBox.Show("Kitap ISBN numarası girilmesi gereken bir parametredir..!");
            }
            else if (textBox2.Text == "")
            {
                MessageBox.Show("Kitabın adı girilmesi gereken bir parametredir..!");
            }
            else if (textBox5.Text == "")
            {
                MessageBox.Show("Kitab yayın evi girilmesi gereken bir parametredir..!");
            }
            else
            {
                SqlCommand kitapkaydet = new SqlCommand("insert into kitap_tablo(kitap_barkod,kitap_isbn,kitap_adi,yazar_no,kitap_ceviri,kategori_no,edinim_no,yayin_evi,baski_yili,baski_sayisi,cilt_sayisi,baski_yeri,kitap_yeri,aciklamalar,kitap_durumu) values('" + textBox12.Text + "','" + textBox3.Text + "','" + textBox2.Text + "'," + comboBox1.SelectedValue + ",'" + textBox4.Text + "'," + comboBox2.SelectedValue + "," + comboBox3.SelectedValue + ",'" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "','" + textBox9.Text + "','" + textBox11.Text + "','" + textBox10.Text + "','True') ", baglanti);
                try
                {
                    baglanti.Open();
                    kitapkaydet.ExecuteNonQuery();
                    MessageBox.Show("Kayıt başarılı bir şekilde eklendi.");
                    if (MessageBox.Show("Barkodun çıktısını almak istiyormusunuz?", "Çıktı al", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        DialogResult yazdırma;
                        yazdırma = printDialog1.ShowDialog();
                        if (yazdırma == DialogResult.OK)
                        {
                            doc.PrintPage += new PrintPageEventHandler(doc_PrintPage);
                            doc.Print();
                        }
                    }
                    baglanti.Close();

                    button8.Visible   = false;
                    button1.Visible   = true;
                    textBox2.Enabled  = false;
                    textBox4.Enabled  = false;
                    textBox5.Enabled  = false;
                    textBox6.Enabled  = false;
                    textBox7.Enabled  = false;
                    textBox8.Enabled  = false;
                    textBox9.Enabled  = false;
                    textBox10.Enabled = false;
                    textBox11.Enabled = false;
                    textBox12.Enabled = false;
                    comboBox1.Enabled = false;
                    comboBox2.Enabled = false;
                    comboBox3.Enabled = false;
                    GridDoldur();
                    textBox1.Text  = "";
                    textBox2.Text  = "";
                    textBox3.Text  = "";
                    textBox4.Text  = "";
                    textBox5.Text  = "";
                    textBox6.Text  = "";
                    textBox7.Text  = "";
                    textBox8.Text  = "";
                    textBox9.Text  = "";
                    textBox10.Text = "";
                    textBox11.Text = "";
                    textBox12.Text = "";
                    comboBox1.Text = "";
                    comboBox2.Text = "";
                    comboBox3.Text = "";
                }
                catch
                {
                    MessageBox.Show("Kayıt yapılamadı...!");
                }
            }
        }
示例#20
0
        private void menuitemFilePrint_Click(object IGNORE_sender, EventArgs IGNORE_e)
        {
            var PrintDialog = new PrintDialog();

            if (Settings.MoreSettings.PrinterSettings != null)
            {
                PrintDialog.PrinterSettings = Settings.MoreSettings.PrinterSettings;
            }

            if (PrintDialog.ShowDialog(this) != DialogResult.OK)
            {
                return;
            }
            Settings.MoreSettings.PrinterSettings = PrintDialog.PrinterSettings;
            Settings.Save();

            var PrintDocument = new PrintDocument();

            PrintDocument.DefaultPageSettings = PageSettings;
            PrintDocument.PrinterSettings     = Settings.MoreSettings.PrinterSettings;
            PrintDocument.DocumentName        = DocumentName + " - Dev Python";

            var RemainingContentToPrint = Content;
            var PageIndex = 0;

            PrintDocument.PrintPage += (sender, e) => {
                { // header
                    var HeaderText = FormatHeaderFooterText(Settings.Header, PageIndex);
                    var Top        = PageSettings.Margins.Top;
                    DrawStringAtPosition(e.Graphics, HeaderText.Left, Top, DrawStringPosition.Left);
                    DrawStringAtPosition(e.Graphics, HeaderText.Center, Top, DrawStringPosition.Center);
                    DrawStringAtPosition(e.Graphics, HeaderText.Right, Top, DrawStringPosition.Right);
                }

                { // body
                    var CharactersFitted = 0;
                    var LinesFilled      = 0;

                    var MarginBounds = new RectangleF(e.MarginBounds.X, e.MarginBounds.Y + /* header */ CurrentFont.Height, e.MarginBounds.Width, e.MarginBounds.Height - (/* header and footer */ CurrentFont.Height * 2));

                    e.Graphics.MeasureString(RemainingContentToPrint, CurrentFont, MarginBounds.Size, StringFormat.GenericTypographic, out CharactersFitted, out LinesFilled);
                    e.Graphics.DrawString(RemainingContentToPrint, CurrentFont, Brushes.Black, MarginBounds, StringFormat.GenericTypographic);

                    RemainingContentToPrint = RemainingContentToPrint.Substring(CharactersFitted);

                    e.HasMorePages = (RemainingContentToPrint.Length > 0);
                }

                { // footer
                    var FooterText = FormatHeaderFooterText(Settings.Footer, PageIndex);
                    var Top        = PageSettings.Bounds.Bottom - PageSettings.Margins.Bottom - CurrentFont.Height;
                    DrawStringAtPosition(e.Graphics, FooterText.Left, Top, DrawStringPosition.Left);
                    DrawStringAtPosition(e.Graphics, FooterText.Center, Top, DrawStringPosition.Center);
                    DrawStringAtPosition(e.Graphics, FooterText.Right, Top, DrawStringPosition.Right);
                }

                PageIndex++;
            };

            PrintDocument.Print();
        }
示例#21
0
        public static void ReceiptForOrder(OrderDto order)
        {
            SetApplicationCulture();
            PrintDialog selectPrinterDiag = new PrintDialog();

            if (selectPrinterDiag.ShowDialog() == DialogResult.OK)
            {
                PrintDocument docToPrint = new PrintDocument
                {
                    DocumentName    = $"ORDER_Table_{order.Table}",
                    PrintController = new StandardPrintController(),
                    PrinterSettings = new PrinterSettings
                    {
                        PrinterName = selectPrinterDiag.PrinterSettings.PrinterName
                    }
                };

                docToPrint.PrintPage += (s, e) =>
                {
                    float x = 10;
                    float y = 10;

                    var theTempPrint = @"ΟΥΖΕΡΙ 'ΠΑΠΑΔΗΣ'";
                    var theTempFont  = new Font("Consolas", 17, FontStyle.Bold);
                    e.Graphics.DrawString(theTempPrint, theTempFont, new SolidBrush(Color.Black), x, y);
                    y += e.Graphics.MeasureString(theTempPrint, theTempFont).Height;

                    y           += 20;
                    theTempPrint = $"ΤΡΑΠΕΖΙ: {order.Table}";
                    theTempFont  = new Font("Consolas", 12, FontStyle.Bold);
                    e.Graphics.DrawString(theTempPrint, theTempFont, new SolidBrush(Color.Black), x, y);
                    y += e.Graphics.MeasureString(theTempPrint, theTempFont).Height;

                    theTempPrint = $"{DateTime.Now.ToString("dd/MM/yyyy")} {DateTime.Now.ToString("HH:mm")}";
                    theTempFont  = new Font("Consolas", 10, FontStyle.Regular);
                    e.Graphics.DrawString(theTempPrint, theTempFont, new SolidBrush(Color.Black), x, y);
                    y += e.Graphics.MeasureString(theTempPrint, theTempFont).Height;

                    y           += 20;
                    theTempPrint = @"Ενδεικτική Παραγγελία";
                    theTempFont  = new Font("Consolas", 10, FontStyle.Bold);
                    e.Graphics.DrawString(theTempPrint, theTempFont, new SolidBrush(Color.Black), x, y);
                    e.Graphics.DrawLine(new Pen(Color.Black), new Point((int)x, ((int)y + 20)),
                                        new Point(((int)x + 300), ((int)y + 20)));
                    y += e.Graphics.MeasureString(theTempPrint, theTempFont).Height;

                    y           += 10;
                    theTempPrint = @"ΕΙΔΟΣ";
                    theTempFont  = new Font("Consolas", 14, FontStyle.Bold);
                    e.Graphics.DrawString(theTempPrint, theTempFont, new SolidBrush(Color.Black), x, y);

                    theTempPrint = @"€";
                    e.Graphics.DrawString(theTempPrint, theTempFont, new SolidBrush(Color.Black), (x + 200), y);
                    y += e.Graphics.MeasureString(theTempPrint, theTempFont).Height;

                    theTempFont = new Font("Consolas", 8, FontStyle.Bold);
                    foreach (var item in order.OrderItems)
                    {
                        theTempPrint = item.Name;
                        e.Graphics.DrawString(theTempPrint, theTempFont, new SolidBrush(Color.Black), x, y);

                        theTempPrint = $"{item.Price} x {item.Quantity}";
                        e.Graphics.DrawString(theTempPrint, theTempFont, new SolidBrush(Color.Black), (x + 170), y);
                        y += e.Graphics.MeasureString(theTempPrint, theTempFont).Height;
                    }

                    theTempFont = new Font("Consolas", 14, FontStyle.Bold);

                    y += 10;

                    e.Graphics.DrawLine(new Pen(Color.Black), new Point((int)x, (int)y),
                                        new Point(((int)x + 300), (int)y));

                    theTempPrint = "ΣΥΝΟΛΟ";
                    e.Graphics.DrawString(theTempPrint, theTempFont, new SolidBrush(Color.Black), x, y);

                    theTempPrint = order.TotalAmount.ToString(_customCulture);
                    e.Graphics.DrawString(theTempPrint, theTempFont, new SolidBrush(Color.Black), (x + 170), y);
                };

                docToPrint.Print();
                docToPrint.Dispose();
            }
        }
示例#22
0
        private void corte()
        {
            folio = GenerateRandom();

            Utilerias.LOG.acciones("genero corte de caja " + folio);

            string sql = "UPDATE VENDIDOS SET CORTE=@CORTE WHERE CORTE=0 AND VENDEDOR=@VALIDADOR AND NOT STATUS='PREVENTA' AND NOT STATUS='BLOQUEADO' ";


            db.PreparedSQL(sql);
            db.command.Parameters.AddWithValue("@CORTE", 1);

            db.command.Parameters.AddWithValue("@VALIDADOR", usuarioconsulta);


            db.execute();
            string sql3 = "UPDATE VENDIDOS SET CORTECANCELADO=@CORTECANCELADO WHERE CORTECANCELADO=0 AND CANCELADO=@VALIDADOR";


            db.PreparedSQL(sql3);
            db.command.Parameters.AddWithValue("@CORTECANCELADO", 1);

            db.command.Parameters.AddWithValue("@VALIDADOR", usuarioconsulta);


            db.execute();

            string sql2 = "UPDATE GUIA SET CORTE=@CORTE WHERE CORTE=0 AND VALIDADOR=@VALIDADOR";


            db.PreparedSQL(sql2);
            db.command.Parameters.AddWithValue("@CORTE", 1);
            db.command.Parameters.AddWithValue("@VALIDADOR", usuarioconsulta);


            db.execute();


            tamaño = 1000;

            PrintDocument pd = new PrintDocument();

            pd.PrintPage += new PrintPageEventHandler(llenarticket);
            PaperSize ps = new PaperSize("", 420, tamaño);

            pd.PrintController = new StandardPrintController();

            pd.DefaultPageSettings.Margins.Left   = 0;
            pd.DefaultPageSettings.Margins.Right  = 0;
            pd.DefaultPageSettings.Margins.Top    = 0;
            pd.DefaultPageSettings.Margins.Bottom = 0;
            pd.DefaultPageSettings.PaperSize      = ps;
            pd.PrinterSettings.PrinterName        = Settings1.Default.impresora;
            subir();

            pd.Print();
            CrearTicket ticket0 = new CrearTicket();

            ticket0.TextoIzquierda("");
            ticket0.TextoIzquierda("");
            ticket0.TextoIzquierda("");
            ticket0.TextoIzquierda("");
            ticket0.CortaTicket();
            ticket0.ImprimirTicket(Settings1.Default.impresora);
            this.Close();
        }
示例#23
0
 private void button1_Click(object sender, EventArgs e)
 {
     _prtDoc.Print();
 }
示例#24
0
        private void btnFacturar_Click(object sender, EventArgs e)
        {
            using (VENTASEntities bd = new VENTASEntities())
            {
                Venta    tbV = new Venta();
                Empleado em  = new Empleado();
                Cliente  cli = new Cliente();

                if (txtNombreCliente.Text != "" && txtApellidoCliente.Text != "" && txtTelefono.Text != "" && txtDUI.Text != "" && txtDireccion.Text != "")

                {
                    if (cbFactura.Checked == true && cbTickect.Checked == false)
                    {
                        em = bd.Empleados.Where(idBuscar => idBuscar.nombre_empleado == lblNombreCajero.Text).First();
                        int idEmpleado = em.id_empleado;

                        string buscarCliente = txtDUI.Text;
                        cli = bd.Clientes.Where(idBuscar => idBuscar.dui == buscarCliente).First();


                        tbV.id_documento = 1;
                        tbV.id_cliente   = cli.id_cliente;
                        tbV.id_empleado  = idEmpleado;
                        tbV.total_venta  = Convert.ToDecimal(lblTotal.Text);
                        tbV.fecha        = Convert.ToDateTime(dtpFecha.Text);
                        bd.Ventas.Add(tbV);
                        bd.SaveChanges();
                    }
                    else if (cbTickect.Checked == true && cbFactura.Checked == false)
                    {
                        em = bd.Empleados.Where(idBuscar => idBuscar.nombre_empleado == lblNombreCajero.Text).First();
                        int idEmpleado = em.id_empleado;

                        tbV.id_documento = 2;
                        tbV.id_cliente   = 1;
                        tbV.id_empleado  = idEmpleado;
                        tbV.total_venta  = Convert.ToDecimal(lblTotal.Text);
                        tbV.fecha        = Convert.ToDateTime(dtpFecha.Text);
                        bd.Ventas.Add(tbV);
                        bd.SaveChanges();
                    }


                    Detalle_Venta dete = new Detalle_Venta();


                    for (int i = 0; i < dgvDetalleVenta.RowCount; i++)
                    {
                        string idProducto   = dgvDetalleVenta.Rows[i].Cells[0].Value.ToString();
                        int    idConvertido = Convert.ToInt32(idProducto);

                        string Cantidad           = dgvDetalleVenta.Rows[i].Cells[3].Value.ToString();
                        int    CantidadConvertido = Convert.ToInt32(Cantidad);

                        string  Total           = dgvDetalleVenta.Rows[i].Cells[4].Value.ToString();
                        decimal TotalConvertido = Convert.ToDecimal(Total);


                        dete.id_venta    = Convert.ToInt32(lblIdVenta.Text);
                        dete.id_producto = idConvertido;
                        dete.cantidad    = CantidadConvertido;
                        dete.precio      = TotalConvertido;
                        bd.Detalle_Venta.Add(dete);
                        bd.SaveChanges();
                    }

                    Producto pro = new Producto();

                    for (int i = 0; i < dgvDetalleVenta.RowCount; i++)
                    {
                        //OBTENIENDO DATOS

                        string idProducto   = dgvDetalleVenta.Rows[i].Cells[0].Value.ToString();
                        int    idConvertido = Convert.ToInt32(idProducto);

                        string Cantidad           = dgvDetalleVenta.Rows[i].Cells[3].Value.ToString();
                        int    CantidadConvertido = Convert.ToInt32(Cantidad);

                        pro = bd.Productos.Where(BuscarId => BuscarId.id_producto == idConvertido).First();
                        int existencias = Convert.ToInt32(pro.cantidad);

                        //ELIMINANDO EN INVENTARIO

                        int restar = existencias - CantidadConvertido;

                        pro.cantidad        = restar;
                        bd.Entry(pro).State = System.Data.Entity.EntityState.Modified;
                        bd.SaveChanges();
                    }

                    //IMPRIMIENDO FACTURA

                    pdImprimir = new PrintDocument();
                    PrinterSettings ps = new PrinterSettings();
                    pdImprimir.PrinterSettings = ps;
                    pdImprimir.PrintPage      += Imprimir;
                    pdImprimir.Print();



                    limpiarproducto();
                    LimpiarCliente();
                    dgvDetalleVenta.Rows.Clear();
                    RetornarId();
                    lblTotal.Text = "";
                    MessageBox.Show("Venta Guardada con exito");
                }
                else
                {
                    MessageBox.Show("No se han definido algunos valores");
                }
            }
        }
示例#25
0
 private void button1_Click(object sender, EventArgs e)
 {
     Document.Print();
 }
            private void GenerateLettersBtn_Click(object sender, EventArgs e)
            {
                PrintDocument document = new PrintDocument();
                document.PrintPage += document_PrintPage;
                document.BeginPrint += document_BeginPrint;
                lettersTupleList = Bounced_Check_Manager_Data_Layer.LetterDAO.generateLetters();

                if (lettersTupleList.Count == 0)
                {
                    MessageBox.Show("No letters to print.");
                    return;
                }

                // Choose printer
                PrintDialog printDialog1 = new PrintDialog();
                printDialog1.Document = document;
                DialogResult result = printDialog1.ShowDialog();
                if (result != DialogResult.OK)
                {
                    return;
                }
                // Print the monster!
                document.Print();
                foreach (var tuple in lettersTupleList)
                {
                    Bounced_Check_Manager_Data_Layer.LetterDAO.create(tuple.Item1);
                }
                MessageBox.Show("Your letters are printing...");
            }
示例#27
0
        public void finalSale(string payType, Boolean isPrint)
        {
            string        printString = "";
            PrintDocument p           = new PrintDocument();


            //headerPrint
            string header =
                "      SHATTHVEES SUPERMART" +
                "\n       Main Street, Kommathurai." +
                "\n                  065-2050369";


            //"\n-------------------------------------------\n";
            p.PrintPage += delegate(object sender1, PrintPageEventArgs e1)
            {
                e1.Graphics.DrawString(header, new Font("Cooper std black", 10), new SolidBrush(Color.Black),
                                       new RectangleF(0, 0, p.DefaultPageSettings.PrintableArea.Width,
                                                      p.DefaultPageSettings.PrintableArea.Height));
            };
            //----------------------------------


            string title =
                "\n----------------------------------------------------------" +
                "\n No Item Qty\t Price \t Dis\t Amount" +
                "\n----------------------------------------------------------";

            string billId = DateTime.Now.ToString("yyMMddhhmmssMs");

            //ItemList
            string itemList = "";
            //string qGetStocks = "select itemcode, itemname, qty, rate, disa, net, cmprice from currentbill; ";

            int num = 1;

            foreach (DataGridViewRow row in dgvFinalStocks.Rows)
            {
                if (row.Cells[0].Value != null && row.Cells[0].Value.ToString() != "")
                {
                    string  barCode  = row.Cells[0].Value.ToString();
                    string  itemName = row.Cells[1].Value.ToString();
                    decimal qty      = Math.Round(decimal.Parse(row.Cells[2].Value.ToString()), 3);
                    decimal rate     = Math.Round(decimal.Parse(row.Cells[3].Value.ToString()), 2);
                    decimal dis      = Math.Round(decimal.Parse(row.Cells[4].Value.ToString()), 2);
                    decimal net      = Math.Round(decimal.Parse(row.Cells[5].Value.ToString()), 2);


                    decimal qtyValue = qty;

                    dbconn.CloseConnection();
                    dbconn.OpenConnection();
                    string qAddToBill = "insert into storedbills values('" + billId + "',"
                                        + barCode + ", '" + itemName + "'," + qty + "," + net + ",'" + DateTime.Now.ToString("yyyy-MM-dd") + "')";
                    MySqlCommand cAddToBill    = new MySqlCommand(qAddToBill, dbconn.connection);
                    int          queryAffected = cAddToBill.ExecuteNonQuery();
                    if (queryAffected > 0)
                    {
                    }


                    itemList += "\n   " + num + " - " + itemName;
                    itemList += "\n                 " + String.Format("{0:#,0.000}", qty) + "\t" + String.Format("{0:N}", rate) + "\t" +
                                String.Format("{0:N}", dis) + "\t" + String.Format("{0:N}", net);
                    num++;
                }
            }

            foreach (DataGridViewRow row in dgvFinalStocks.Rows)
            {
                if (row.Cells[0].Value != null && row.Cells[0].Value.ToString() != "")
                {
                    string  barCode = row.Cells[0].Value.ToString();
                    decimal qty     = decimal.Parse(row.Cells[2].Value.ToString());

                    dbconn.CloseConnection();
                    dbconn.OpenConnection();
                    string       qAddToBill    = "update stocks set qty=qty-" + qty + " where barcode='" + barCode + "';";
                    MySqlCommand cAddToBill    = new MySqlCommand(qAddToBill, dbconn.connection);
                    int          queryAffected = cAddToBill.ExecuteNonQuery();
                }
            }
            string payTypeBill = "";



            if (payType == "cash")
            {
                decimal revenue = Math.Round(decimal.Parse(poTotalBill.Text) - comp, 2);
                dbconn.CloseConnection();
                dbconn.OpenConnection();
                string qAddToBill1 = "INSERT INTO sales(billId, billDate, amount, revenue, payType)  VALUES ('"
                                     + billId + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "'," + poTotalBill.Text + "," + revenue + ", 'cash');delete from currentbill;";
                MySqlCommand cAddToBill1    = new MySqlCommand(qAddToBill1, dbconn.connection);
                int          queryAffected1 = cAddToBill1.ExecuteNonQuery();

                if (poCash.Text == null || poCash.Text == "")
                {
                    poCash.Text = poTotalBill.Text;
                }

                payTypeBill =
                    "\n\t\tPaid By\t: Cash   " +
                    "\n\t\tCash\t: " + String.Format("{0:N}", decimal.Parse(poCash.Text)) +
                    "\n\t\tBalance\t: " + String.Format("{0:N}", decimal.Parse(poBalance.Text));

                dbconn.CloseConnection();
                dbconn.OpenConnection();
                string       qAddToBill    = "update totalbillday set totalbill = totalbill + " + loanSettle.Text + " where day = '" + DateTime.Now.ToString("yyyy-MM-dd") + "';";
                MySqlCommand cAddToBill    = new MySqlCommand(qAddToBill, dbconn.connection);
                int          queryAffected = cAddToBill.ExecuteNonQuery();
                if (queryAffected > 0)
                {
                }
            }
            else if (payType == "card")
            {
                decimal revenue = Math.Round(decimal.Parse(poTotalBill.Text) - comp, 2);
                dbconn.CloseConnection();
                dbconn.OpenConnection();
                string qAddToBill1 = "INSERT INTO sales(billId, billDate, amount, revenue, payType)  VALUES ('"
                                     + billId + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "'," + poTotalBill.Text + "," + revenue + ", 'card');delete from currentbill;";
                MySqlCommand cAddToBill1    = new MySqlCommand(qAddToBill1, dbconn.connection);
                int          queryAffected1 = cAddToBill1.ExecuteNonQuery();

                payTypeBill =
                    "\n\t\tPaid By\t : Credit Card" +
                    "\n\t\tBank\t   : " + cmbCardType.Text +
                    "\n\t\tDeducted : " + String.Format("{0:N}", decimal.Parse(poTotalBill.Text));


                dbconn.CloseConnection();
                dbconn.OpenConnection();
                string       qAddToBill    = "update totalbillday set totalbill = totalbill + " + loanSettle.Text + " where day = '" + DateTime.Now.ToString("yyyy-MM-dd") + "';";
                MySqlCommand cAddToBill    = new MySqlCommand(qAddToBill, dbconn.connection);
                int          queryAffected = cAddToBill.ExecuteNonQuery();
                if (queryAffected > 0)
                {
                }
            }
            else if (payType == "loan")
            {
                decimal revenue = Math.Round(decimal.Parse(poTotalBill.Text) - comp, 2);
                dbconn.CloseConnection();
                dbconn.OpenConnection();
                string qAddToBill1 = "INSERT INTO sales(billId, billDate, amount, revenue, payType)  VALUES ('"
                                     + billId + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "'," + poTotalBill.Text + "," + revenue + ", 'loan');delete from currentbill;";
                MySqlCommand cAddToBill1    = new MySqlCommand(qAddToBill1, dbconn.connection);
                int          queryAffected1 = cAddToBill1.ExecuteNonQuery();

                payTypeBill =
                    "\n\t\tPaid By\t: Loan" +
                    "\n\t\tAccount\t: " + cmbLoanAccount.Text +
                    "\n\t\tPerson\t: " + cmbLoanName.Text +
                    "\n\t\tSettle\t: " + String.Format("{0:N}", decimal.Parse(loanSettle.Text)) +
                    "\n\t\tTotal Credit: " + String.Format("{0:N}", decimal.Parse(loanSettle.Text));


                dbconn.CloseConnection();
                dbconn.OpenConnection();
                string       qAddToBill    = "update totalbillday set totalbill = totalbill + " + loanSettle.Text + " where day = '" + DateTime.Now.ToString("yyyy-MM-dd") + "';";
                MySqlCommand cAddToBill    = new MySqlCommand(qAddToBill, dbconn.connection);
                int          queryAffected = cAddToBill.ExecuteNonQuery();
                if (queryAffected > 0)
                {
                }
            }

            //SELECT fields FROM table ORDER BY id DESC LIMIT 1;
            //int lastBillid = 0;
            //dbconn.CloseConnection();
            //dbconn.OpenConnection();
            //string qr_getProducta2 = "select id from sales order by id desc limit 1;";
            //MySqlCommand cm_getProducta2 = new MySqlCommand(qr_getProducta2, dbconn.connection);
            //MySqlDataReader dr_getProducta2 = cm_getProducta2.ExecuteReader();

            //if (dr_getProducta2.HasRows == true)
            //{
            //    while (dr_getProducta2.Read())
            //    {
            //        lastBillid = int.Parse(dr_getProducta2["id"].ToString());
            //    }
            //}

            string billDiscount = "";

            if (poBillDiscount.Text == "" || poBillDiscount.Text == "0" || poBillDiscount.Text == null)
            {
                billDiscount = String.Format("{0:N}", 0.00);
            }
            else
            {
                billDiscount = String.Format("{0:N}", decimal.Parse(poBillDiscount.Text));
            }


            string totalBill =
                "\n---------------------------------------------------------" +
                "\n\n\t\tGross \t : " + String.Format("{0:N}", decimal.Parse(poGross.Text)) +
                "\n\t\tItems Discount : " + String.Format("{0:N}", decimal.Parse(poItemSavings.Text)) +
                "\n\t\tBill Discount : " + billDiscount +
                "\n\t\tTotal \t : " + String.Format("{0:N}", decimal.Parse(poTotalBill.Text));

            if (poBillDiscount.Text == "" || poBillDiscount.Text == null)
            {
                poBillDiscount.Text = "0";
            }



            string bestBuy =
                "\n\n  * Best Buy Discount\t : " + String.Format("{0:N}", (decimal.Parse(poBillDiscount.Text) + decimal.Parse(poItemSavings.Text)));

            string title2 =
                "\n " + DateTime.Now.ToString("yyyy / MM / dd") + " | " + DateTime.Now.ToString("hh:mm:ss")
                + " | No: " + billId + " | " + LoginForm.loggedUser;

            string footer =
                "\n----------------------------------------------------------" +
                "\n         --------IMPORTANT NOTICE--------" +
                "\n        In case of a price discrepancy, return" +
                "\n             the item & bill within 3 days to" +
                "\n                  refund the difference." +
                "\n        <<<<  Thank You, Come Again... >>>>";

            printString += title2;
            printString += title;
            printString += itemList;
            printString += totalBill;
            printString += payTypeBill;
            printString += bestBuy;
            printString += footer;

            p.PrintPage += delegate(object sender1, PrintPageEventArgs e1)
            {
                e1.Graphics.DrawString(printString, new Font("Seqoe ui", 10), new SolidBrush(Color.Black),
                                       new RectangleF(0, 80, p.DefaultPageSettings.PrintableArea.Width,
                                                      p.DefaultPageSettings.PrintableArea.Height));
            };

            if (isPrint)
            {
                p.Print();
            }

            this.Close();
        }
示例#28
0
 public void PrintImage()
 {
     picturePrintDocument.Print();
 }
示例#29
0
 // 打印抽签结果
 private void PrintResult()
 {
     ReadFile();
     printDocument1.Print();
 }
示例#30
0
        /*
         * /// <summary>
         * /// 打印预览
         * /// </summary>
         * public static string PreView(Image image, string eventType, string direction, string printerName, string paperName)
         * {
         *  try
         *  {
         *      Setting setting = FileUtils.GetSetting();
         *      if (string.IsNullOrEmpty(setting.Name))
         *          return "请先设置默认打印机";
         *      if (image == null)
         *          return "要打印的数据不存在";
         *
         *      PrintDocument pd = new PrintDocument();
         *      pd.DefaultPageSettings.PrinterSettings.PrinterName = setting.Name;
         *      pd.DefaultPageSettings.PaperSize = getPaperSize(pd.PrinterSettings.PaperSizes, paperName) ?? pd.DefaultPageSettings.PaperSize;
         *
         *      pd.PrintPage += (o, e) =>
         *      {
         *          PrintPage(o, e, image, false, direction);
         *      };
         *
         *      PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();
         *      printPreviewDialog.WindowState = FormWindowState.Maximized;
         *      printPreviewDialog.Document = pd;
         *      printPreviewDialog.ShowDialog();
         *
         *      return "打印成功!";
         *  }
         *  catch (Exception e)
         *  {
         *      return e.Message;
         *  }
         * }
         */
        public static string PreView(string filePath, string eventType, string direction, string printerName, string paperName)
        {
            try
            {
                Setting setting = FileUtils.GetSetting();
                if (string.IsNullOrEmpty(setting.Name))
                {
                    return("请先设置默认打印机");
                }
                if (!Directory.Exists(filePath) && !File.Exists(filePath))
                {
                    return("要打印的数据不存在");
                }

                PrintDocument pd = new PrintDocument();
                pd.DefaultPageSettings.PrinterSettings.PrinterName = setting.Name;
                pd.DefaultPageSettings.PaperSize = getPaperSize(pd.PrinterSettings.PaperSizes, paperName) ?? pd.DefaultPageSettings.PaperSize;
                var fileListIndex = 0;
                //var fileList = Directory.GetFiles(filePath);

                List <string> fileList = new List <string>();
                if (File.Exists(filePath)) //路径是jpg图片
                {
                    fileList.Add(filePath);
                }
                else
                {
                    fileList = new List <string>(Directory.GetFiles(filePath).OrderBy(f => Convert.ToInt32(Path.GetFileNameWithoutExtension(f))));
                }
                if (fileList.Count == 0)
                {
                    return("要打印的数据不存在");
                }
                pd.PrintPage += (o, e) =>
                {
                    PageSettings settings = e.PageSettings;
                    var          paperHeight = settings.PaperSize.Height;
                    var          paperWidth = settings.PaperSize.Width;
                    int          margin = 10, imgHeight = 0, imgWidth = 0;

                    using (Image image = new Bitmap(fileList[fileListIndex]))
                    {
                        ImageScaling(image, paperHeight, paperWidth, margin, direction, ref imgHeight, ref imgWidth);
                        if (direction == "2")                              //2:横向打印(html转pdf的有问题,html转pdf不考虑宽度,转出来标准的pdf页,分页也已经完成,在这部分就处理不了)
                        {
                            e.Graphics.TranslateTransform(0, paperHeight); //旋转原点
                            e.Graphics.RotateTransform(-90.0F);            //旋转角度
                        }
                        e.Graphics.DrawImage(image, margin, margin, imgWidth, imgHeight);
                    }
                    if (fileListIndex < fileList.Count - 1)
                    {
                        e.HasMorePages = true;  //HaeMorePages属性为True时,PrintPage的回调函数就会被再次调用,打印一个页面。
                        fileListIndex++;
                    }
                    else
                    {
                        //预览界面点击打印需要把索引重新初始化
                        fileListIndex = 0;
                    }
                };

                //打印结束-删除一些创建的文件
                //pd.EndPrint += new PrintEventHandler();

                if (eventType == "PRINT")
                {
                    pd.Print();
                }
                else if (eventType == "PREVIEW")
                {
                    PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();
                    printPreviewDialog.WindowState = FormWindowState.Maximized;
                    printPreviewDialog.Document    = pd;
                    printPreviewDialog.ShowDialog();
                }
                deleteTemFile();
                return("打印成功!");
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
示例#31
0
 private void metroTile1_Click_1(object sender, System.EventArgs e)
 {
     CaptureScreen();
     printDay.Print();
 }
示例#32
0
        /// <summary>
        /// 表示需要打印的数据源集合
        /// </summary>
        /// <param name="mList"></param>
        public void Print(MExpress mExpress)
        {
            if (mExpress == null || string.IsNullOrEmpty(mExpress.ExpreeType))
            {
                return;
            }
            m_List = GetPrintResource(mExpress.ExpreeType, mExpress);
            if (m_List == null)
            {
                return;
            }


            PrintDocument mPrintDocument = new PrintDocument();

            //设置打印机
            mPrintDocument.PrinterSettings.PrinterName = m_MPrinter.Printer;
            //设置打印份数
            mPrintDocument.PrinterSettings.Copies = Convert.ToInt16(m_MPrinter.PrintNum);
            //设置打印用的纸张 当设置为Custom的时候,可以自定义纸张的大小,还可以选择A4,A5等常用纸型
            if (m_MPrinter.NowHeight != 0 && m_MPrinter.NowWeight != 0)
            {
                mPrintDocument.DefaultPageSettings.PaperSize = new PaperSize("Custum", Convert.ToInt32(m_MPrinter.NowWeight) / 10, Convert.ToInt32(m_MPrinter.NowHeight) / 10);
            }
            else
            {
                mPrintDocument.DefaultPageSettings.PaperSize = new PaperSize("Custum", Convert.ToInt32(m_MPrinter.IniWeight) / 10, Convert.ToInt32(m_MPrinter.IniHeight) / 10);
            }
            //设置打印方向
            if (m_MPrinter.PrintFoward == "横向")
            {
                mPrintDocument.DefaultPageSettings.Landscape = true;
            }
            else
            {
                mPrintDocument.DefaultPageSettings.Landscape = false;
            }
            //设置打印偏移量
            int topAway  = 0;
            int leftAway = 0;

            if (m_MPrinter.TopAway != 0)
            {
                topAway = Convert.ToInt32(m_MPrinter.TopAway) / 10;
            }
            if (m_MPrinter.LeftAway != 0)
            {
                leftAway = Convert.ToInt32(m_MPrinter.LeftAway) / 10;
            }
            if (topAway >= 0)
            {
                mPrintDocument.DefaultPageSettings.Margins.Top = topAway;
            }
            else
            {
                mPrintDocument.DefaultPageSettings.Margins.Bottom = topAway * -1;
            }
            if (leftAway >= 0)
            {
                mPrintDocument.DefaultPageSettings.Margins.Left = leftAway;
            }
            else
            {
                mPrintDocument.DefaultPageSettings.Margins.Right = leftAway * -1;
            }
            //设置打印内容
            mPrintDocument.PrintPage += mPrintDocument_PrintPage;
            mPrintDocument.Print();

            //更新打印状态
            mExpress.IsPrint = "是";
            m_ExpressBLL.Update(mExpress);
        }
示例#33
0
        private void button1_Click_1(object sender, EventArgs e) //Print
        {
            Bitmap b = new Bitmap(image, pictureBox1.Width, pictureBox1.Height);

            //Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),"MyFile.jpg");



            //try
            //{
            //    // Determine whether the directory exists.
            //    if (Directory.Exists(consentPath))
            //    {
            //        //Console.WriteLine("That path exists already.");
            //        //if (!Directory.Exists(Path.Combine(consentPath, "MyFile.jpg")))
            //        //{
            //        //    //Directory.CreateDirectory(@"c:\text");
            //        b.Save(Path.Combine(consentPath, LoginForm.UName + "_" + LoginForm.Email + ".jpg"));
            //        //}

            //        //return;
            //    }
            //    else
            //    {
            //        DirectoryInfo di = Directory.CreateDirectory(consentPath);
            //        b.Save(Path.Combine(consentPath, LoginForm.UName+"_"+LoginForm.Email+".jpg"));
            //    }
            //    // Try to create the directory.

            //    //Console.WriteLine("The directory was created successfully at {0}.", Directory.GetCreationTime(path));

            //    // Delete the directory.
            //    //di.Delete();
            //    //Console.WriteLine("The directory was deleted successfully.");
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine("The process failed: {0}", ex.ToString());
            //}


            try
            {
                PrintDialog   pd  = new PrintDialog();
                PrintDocument doc = new PrintDocument();
                //doc.DefaultPageSettings.Landscape = true;
                doc.PrintPage += PrintPage;

                //foreach (string s in PrinterSettings.InstalledPrinters)
                //{

                //    if ((s.ToString() != "Fax") || (s.ToString() != "Send to OneNote 2016") || (s.ToString() != "Microsoft Print to PDF") || (s.ToString() != "Microsoft XPS Document Writer"))
                //    {

                //    }
                //    else
                //    {
                //        doc.PrinterSettings.PrinterName = s;
                //        doc.Print();
                //    }

                //}
                //if (pd.ShowDialog() == DialogResult.OK)
                //{
                //    doc.Print();
                //}
                doc.Print();
                //this.Hide();
                //Permission form = new Permission(b);
                //form.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Printer disconnected", "Error");
            }
            this.Hide();
            Permission form = new Permission(b);

            form.Show();
        }
示例#34
0
        private static void printaj()
        {
            napomena = "";
            string        printerName = DTsetting.Rows[0]["windows_printer_name"].ToString();
            PrintDocument printDoc    = new PrintDocument();

            printDoc.PrinterSettings.PrinterName = printerName;

            //byte[] codeOpenCashDrawer = new byte[] { 27, 112, 48, 55, 121 };
            //IntPtr pUnmanagedBytes = new IntPtr(0);
            //pUnmanagedBytes = Marshal.AllocCoTaskMem(5);
            //Marshal.Copy(codeOpenCashDrawer, 0, pUnmanagedBytes, 5);
            //RawPrinterHelper.SendBytesToPrinter(printDoc.PrinterSettings.PrinterName, pUnmanagedBytes, 5);
            //Marshal.FreeCoTaskMem(pUnmanagedBytes);

            string _3 = "";
            // Code-iT verzija programa bottom text
            string codeIt = $"Code-iT verzija programa: {Properties.Settings.Default.verzija_programa.ToString()}";

            _3 += Environment.NewLine;
            PrintTextLine(new string('-', RecLineChars));
            string center = "";

            for (int i = 0; i < (RecLineChars - codeIt.Length) / 2; i++)
            {
                center += " ";
            }
            _3 += center + codeIt;

            string drawString = _1 + _2 + _3;

            if (DTpostavke.Rows[0]["direct_print"].ToString() == "1")
            {
                if (DTpostavke.Rows[0]["ladicaOn"].ToString() == "1")
                {
                    openCashDrawer1();
                }

                string ttx = "\r\n" + _1 + _2 + fiskal_tekst + kockice + _4 + _5 + _3;
                ttx = ttx.Replace("č", "c");
                ttx = ttx.Replace("Č", "C");
                ttx = ttx.Replace("ž", "z");
                ttx = ttx.Replace("Ž", "Z");
                ttx = ttx.Replace("ć", "c");
                ttx = ttx.Replace("Ć", "C");
                ttx = ttx.Replace("đ", "d");
                ttx = ttx.Replace("Đ", "D");
                ttx = ttx.Replace("š", "s");
                ttx = ttx.Replace("Š", "S");

                string GS  = Convert.ToString((char)29);
                string ESC = Convert.ToString((char)27);

                string COMMAND = "";
                COMMAND  = ESC + "@";
                COMMAND += GS + "V" + (char)1;

                RawPrinterHelper.SendStringToPrinter(printDoc.PrinterSettings.PrinterName, ttx + COMMAND);
            }
            else
            {
                if (!printDoc.PrinterSettings.IsValid)
                {
                    string msg = String.Format(
                        "Can't find printer \"{0}\".", printerName);
                    MessageBox.Show(msg, "Print Error");
                    return;
                }
                printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
                printDoc.Print();
            }

            //string GS = Convert.ToString((char)29);
            //string ESC = Convert.ToString((char)27);

            //string COMMAND = "";
            //COMMAND = ESC + "@";
            //COMMAND += GS + "V" + (char)1;

            //RawPrinterHelper.SendStringToPrinter(printDoc.PrinterSettings.PrinterName, COMMAND);
        }
示例#35
0
 private void button1_Click(object sender, EventArgs e)
 {
     CaptureScreen();
     printDocument1.Print();
 }
        private async void altoButton1_Click(object sender, EventArgs e)
        {
            try
            {
                // double precio = Convert.ToDouble(txtcantidad.Text) * Convert.ToDouble(txtimporte.Text);

                double cantidad = Convert.ToDouble(txtimporte.Text);

                if (cantidad > -1 && cantidad < 100)
                {
                    double d = Convert.ToDouble(txtimporte.Text, CultureInfo.InvariantCulture);
                    txtimporte.Text = d.ToString("$      .00", CultureInfo.InvariantCulture);
                }
                else if (cantidad > 99 && cantidad < 1000)
                {
                    double d = Convert.ToDouble(txtimporte.Text, CultureInfo.InvariantCulture);
                    txtimporte.Text = d.ToString("$    .00", CultureInfo.InvariantCulture);
                }
                else if (cantidad > 999 && cantidad < 10000)
                {
                    double d = Convert.ToDouble(txtimporte.Text, CultureInfo.InvariantCulture);
                    txtimporte.Text = d.ToString("$  .00", CultureInfo.InvariantCulture);
                }
                else if (cantidad > 9999 && cantidad < 100000)
                {
                    double d = Convert.ToDouble(txtimporte.Text, CultureInfo.InvariantCulture);
                    txtimporte.Text = d.ToString("$.00", CultureInfo.InvariantCulture);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex);
            }

            fechasalida   = Convert.ToDateTime(fecha);
            fechasalida2  = fechasalida.AddDays(30);
            fechadesalida = fechasalida2.ToShortDateString().ToString();


sincopia:
            string Name = txtnombre2.Text;
            var rand = new Random();

            pedido = "GARANTIA";
            //checkBoxcotizacion.Checked = false;
            ///checkBoxrevision.Checked = false;

            string firstfour = Name.Substring(0, 2);

            txtorden2.Text = firstfour;

            string iniciodepedidos = pedido.Substring(0, 2);

            //generacion  de numero aleatorio de orden
            var guid        = Guid.NewGuid();
            var justNumbers = new String(guid.ToString().Where(Char.IsDigit).ToArray());
            var seed        = int.Parse(justNumbers.Substring(0, 9));
            var random      = new Random(seed);

            txtpruibea.Text = seed.ToString();
            txtorden.Text   = iniciodepedidos + firstfour + seed.ToString();

            DocumentReference docRef   = database.Collection("Garantias").Document(txtorden.Text);
            DocumentSnapshot  snapshot = await docRef.GetSnapshotAsync();

            if (snapshot.Exists)
            {
                MessageBox.Show("Repetido");
                goto sincopia;
            }

            else
            {
                DocumentReference cityRef = database.Collection("Revisiones").Document(Orden);
                await cityRef.DeleteAsync();

                DocumentReference           DOC   = database.Collection("Garantias").Document("contador");
                Dictionary <String, Object> data1 = new Dictionary <string, object>()
                {
                    { "ID", FieldValue.Increment(1) }
                };
                await DOC.SetAsync(data1, SetOptions.MergeAll);

                DocumentReference docRef2  = database.Collection("Garantias").Document("contador");
                DocumentSnapshot  snapsho2 = await docRef2.GetSnapshotAsync();

                if (snapsho2.Exists)
                {
                    Dictionary <string, object> counter = snapsho2.ToDictionary();
                    foreach (var item in counter)
                    {
                        lblcontador.Text = string.Format("{1}", item.Key, item.Value);
                    }
                }
                // int id = (int)Convert.ToInt64(lblcontador.Text);
                BarcodeLib.Barcode Codigo = new BarcodeLib.Barcode();
                Codigo.IncludeLabel = true;
                pictureBox2.Image   = Codigo.Encode(BarcodeLib.TYPE.CODE128, txtorden.Text, Color.Black, Color.White, 230, 60);

                //Create a Bitmap and draw the DataGridView on it.
                // Bitmap bitmap = new Bitmap(this.dataGridView1.Width, this.dataGridView1.Height);
                //dataGridView1.DrawToBitmap(bitmap, new Rectangle(0, 0, this.dataGridView1.Width, this.dataGridView1.Height));

                //Resize DataGridView back to original height.
                //dataGridView1.Height = height;

                //Save the Bitmap to folder.
                //bitmap.Save(@"D:\DataGridView.png");

                //BrotherPrintThis();


                printDocument1 = new PrintDocument();
                PrinterSettings ps = new PrinterSettings();
                printDocument1.PrinterSettings = ps;
                printDocument1.PrintPage      += impresion;
                printDocument1.Print();
                altoButton1.Enabled = false;
                //MessageBox.Show("Finalizado");
                //printPreviewDialog1.Document = printDocument1;
                printDocument1.Print();
                //printDocument1.Print();
                //Add_Document_with_orden();
                altoButton1.Enabled = false;

                button1.Enabled = true;
                this.Close();
            }
        }
        /// <summary>
        /// Prints the specified document.
        /// </summary>
        /// <param name="document">The document.</param>
        public bool Print(IDocumentContract document)
        {
            var documentContract = document as MetafileDocumentContract ?? throw new ArgumentException("Invalide type", nameof(document));

            if (documentContract.PageSizes == null || documentContract.PageSizes.Count() == 0)
            {
                throw new ArgumentNullException(Resources.NoPageSizes);
            }

            var pageSizesList = documentContract.PageSizes.ToList();

            this.emfImages = MetafileHelper.GetEmfImagesToPePrinted(pageSizesList, documentContract.Contents);
            if (this.emfImages == null || this.emfImages.Count == 0)
            {
                // Issue an instrumentation error and return as there is nothing to print
                throw new ArgumentException(Resources.NoMetafilesToPrint);
            }

            // Now determine the printer settings necessary
            PageSettings pageSettingsOfPrinter = null;
            var          pageSettingsHelper    = new PageSettingsHelper();

            if (!string.IsNullOrWhiteSpace(documentContract.Settings))
            {
                pageSettingsHelper.IsLandscapeSetOnReportDesign = this.emfImages[0].Height < this.emfImages[0].Width;

                try
                {
                    pageSettingsOfPrinter = pageSettingsHelper.ProcessPageSettings(documentContract.Settings);
                }
                catch (Exception)
                {
                    // TODO Error log Resources.UnableToInitializePrinterSettings
                    return(false);
                }
            }

            // PageSettings returned after processing should not be null. Throw if it is.
            if (pageSettingsOfPrinter == null)
            {
                throw new ArgumentNullException(Resources.NoPageSettings);
            }

            // Send the print job to printer with the pagesettings obtained
            int retryCount = 1;

            try
            {
                while (retryCount <= Constants.MaximumRetry)
                {
                    try
                    {
                        this.currentPageNumber = 0;
                        using (var printDocument = new PrintDocument())
                        {
                            printDocument.DocumentName = documentContract.Name;

                            printDocument.DefaultPageSettings = pageSettingsOfPrinter;
                            printDocument.PrinterSettings     = pageSettingsOfPrinter.PrinterSettings;
                            printDocument.PrintPage          += this.PrintEachPage;

                            // use standard print controller instead of print controller with status dialog.
                            printDocument.PrintController = new StandardPrintController();
                            printDocument.Print();
                        }

                        break;
                    }
                    catch (InvalidPrinterException)
                    {
                        if (retryCount < Constants.MaximumRetry)
                        {
                            retryCount++;
                        }
                        else
                        {
                            string message = string.Format(CultureInfo.InvariantCulture, Resources.InvalidPrinter, pageSettingsOfPrinter.PrinterSettings.PrinterName);
                            //TODO Error log
                            return(false);
                        }
                    }
                }
            }
            finally
            {
                if (this.emfImages != null && this.emfImages.Count > 0)
                {
                    foreach (var page in this.emfImages)
                    {
                        if (page != null)
                        {
                            page.Dispose();
                        }
                    }
                }
            }

            return(true);
        }
示例#38
0
        public static void Main (string[] args)
        {
		PrintDocument p = new PrintDocument ();
		p.PrintPage += new PrintPageEventHandler (PrintPageEvent);
                p.Print ();
        }
示例#39
-1
	// Print the file.
	public void Printing()
	{
		try 
		{
			streamToPrint = new StreamReader (filePath);
			try 
			{
				//printFont = new Font("Arial", 10);
				PrintDocument pd = new PrintDocument(); 
				pd.PrintController = new System.Drawing.Printing.StandardPrintController();
				pd.DocumentName = @"c:\test.txt";
				//pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
				// Print the document.
				pd.Print();
			} 
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
			finally 
			{
				streamToPrint.Close() ;
			}
		} 
		catch(Exception ex) 
		{ 
			MessageBox.Show(ex.Message);
		}
	}
  public static void Main(string[] args)
  {
    Console.WriteLine("");
	if (args.Length < 2) usage();
    
	map = new mapObj(args[0]);

    Console.WriteLine("# Map layers " + map.numlayers + "; Map name = " + map.name);
    for (int i = 0; i < map.numlayers; i++) 
    {
        Console.WriteLine("Layer [" + i + "] name: " + map.getLayer(i).name);
    }

    try
    {
        PrintDocument doc = new PrintDocument();

        doc.PrintPage += new PrintPageEventHandler(doc_PrintPage);

        // Specify the printer to use.
        doc.PrinterSettings.PrinterName = args[1];

        doc.Print();
    } 
    catch (Exception ex) 
    {
                Console.WriteLine( "\nMessage ---\n{0}", ex.Message );
                Console.WriteLine( 
                    "\nHelpLink ---\n{0}", ex.HelpLink );
                Console.WriteLine( "\nSource ---\n{0}", ex.Source );
                Console.WriteLine( 
                    "\nStackTrace ---\n{0}", ex.StackTrace );
                Console.WriteLine( 
                    "\nTargetSite ---\n{0}", ex.TargetSite );	}	
    }
示例#41
-1
 protected override void OnClick(EventArgs ea)
 {
     PrintDocument prndoc = new PrintDocument();
     prndoc.DocumentName = Text;
     prndoc.PrintPage += new PrintPageEventHandler(PrintDocumentOnPrintPage);
     prndoc.Print();
 }
示例#42
-1
        public static void Main (string[] args)
        {
                stream = new StreamReader ("PrintMe.txt");
		PrintDocument p = new PrintDocument ();
		p.PrintPage += new PrintPageEventHandler (PrintPageEvent);
                p.Print ();
		stream.Close();
        }