// 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);
     }
 }
 // The class constructor
 public DataGridViewPrinter( DataGridView [] aDataGridList
         , PrintDocument aPrintDocument
         , bool CenterOnPage
         , bool WithTitle
         , string aTitleText
         , Font aTitleFont
         , Color aTitleColor
         , bool WithPaging
     )
 {
     TheDataGridList = aDataGridList;
     InitializeComponent(aPrintDocument, CenterOnPage, WithTitle, aTitleText, aTitleFont, aTitleColor, WithPaging );
 }
Esempio n. 4
1
    // The class constructor
    public DataGridViewPrinter(DataGridView aDataGridView,
        PrintDocument aPrintDocument,
        bool CenterOnPage, bool WithTitle,
        string aTitleText, Font aTitleFont,
        Color aTitleColor, bool WithPaging)
    {
        TheDataGridView = aDataGridView;
        ThePrintDocument = aPrintDocument;
        IsCenterOnPage = CenterOnPage;
        IsWithTitle = WithTitle;
        TheTitleText = aTitleText;
        TheTitleFont = aTitleFont;
        TheTitleColor = aTitleColor;
        IsWithPaging = WithPaging;

        PageNumber = 0;

        RowsHeight = new List<float>();
        ColumnsWidth = new List<float>();

        mColumnPoints = new List<int[]>();
        mColumnPointsWidth = new List<float>();

        // Claculating the PageWidth and the PageHeight
        if (!ThePrintDocument.DefaultPageSettings.Landscape)
        {
            PageWidth =
              ThePrintDocument.DefaultPageSettings.PaperSize.Width;
            PageHeight =
              ThePrintDocument.DefaultPageSettings.PaperSize.Height;
        }
        else
        {
            PageHeight =
              ThePrintDocument.DefaultPageSettings.PaperSize.Width;
            PageWidth =
              ThePrintDocument.DefaultPageSettings.PaperSize.Height;
        }

        // Claculating the page margins
        LeftMargin = ThePrintDocument.DefaultPageSettings.Margins.Left;
        TopMargin = ThePrintDocument.DefaultPageSettings.Margins.Top;
        RightMargin = ThePrintDocument.DefaultPageSettings.Margins.Right;
        BottomMargin = ThePrintDocument.DefaultPageSettings.Margins.Bottom;

        // First, the current row to be printed
        // is the first row in the DataGridView control
        CurrentRow = 0;
    }
Esempio n. 5
1
        public void Process(IZvtApdu requestApdu, IZvtApdu responseApdu)
        {
            PrintDocument printDocument;

            if (_printDocuments.Count == 0)
            {
                printDocument = new PrintDocument();
                _printDocuments.Add(printDocument);
            }
            else
                printDocument = (PrintDocument)_printDocuments[_printDocuments.Count - 1];

            printDocument.AddRange(((PrintLineApduResponse)responseApdu).ConvertToPrintLine());

            if (((PrintLineApduResponse)responseApdu).LastLine)
            {
                printDocument = new PrintDocument();
                _printDocuments.Add(printDocument);
            }
        }
    private void InitializeComponent( 
            PrintDocument aPrintDocument
            , bool CenterOnPage
            , bool WithTitle
            , string aTitleText
            , Font aTitleFont
            , Color aTitleColor
            , bool WithPaging
        )
    {
        ThePrintDocument = aPrintDocument;
        IsCenterOnPage = CenterOnPage;
        IsWithTitle = WithTitle;
        TheTitleText = aTitleText;
        TheTitleFont = aTitleFont;
        TheTitleColor = aTitleColor;
        IsWithPaging = WithPaging;
        TheActiveViewCount = 0;
        PageNumber = 0;

        // Claculating the PageWidth and the PageHeight
        if ( ThePrintDocument.DefaultPageSettings.Landscape ) {
            PageHeight = ThePrintDocument.DefaultPageSettings.PaperSize.Width;
            PageWidth = ThePrintDocument.DefaultPageSettings.PaperSize.Height;
        } else {
            PageWidth = ThePrintDocument.DefaultPageSettings.PaperSize.Width;
            PageHeight = ThePrintDocument.DefaultPageSettings.PaperSize.Height;
        }

        // Claculating the page margins
        LeftMargin = ThePrintDocument.DefaultPageSettings.Margins.Left;
        TopMargin = ThePrintDocument.DefaultPageSettings.Margins.Top;
        RightMargin = ThePrintDocument.DefaultPageSettings.Margins.Right;
        BottomMargin = ThePrintDocument.DefaultPageSettings.Margins.Bottom;

        // First, the current row to be printed is the first row in the DataGridView control
        CurrentRow = 0;
    }
Esempio n. 7
0
        public static void Main (string[] args)
        {                
		PrintDocument p = new PrintDocument ();
		p.PrintPage += new PrintPageEventHandler (PrintPageEvent);
		p.QueryPageSettings += new  QueryPageSettingsEventHandler (QueryPageSettings);
                p.Print ();
		
        }
Esempio n. 8
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();
    }
Esempio n. 9
0
	public MainForm ()
	{
		// 
		// _printPreviewControl
		// 
		_printPreviewControl = new PrintPreviewControl ();
		_printPreviewControl.Anchor = (AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right);
		_printPreviewControl.Dock = DockStyle.Bottom;
		_printPreviewControl.Height = 295;
		_printPreviewControl.TabIndex = 0;
		_printPreviewControl.Zoom = 1;
		Controls.Add (_printPreviewControl);
		// 
		// _printButton
		// 
		_zoomTrackBar = new TrackBar ();
		_zoomTrackBar.Location = new Point (12, 12);
		_zoomTrackBar.Maximum = 100;
		_zoomTrackBar.Minimum = 1;
		_zoomTrackBar.Size = new Size (330, 23);
		_zoomTrackBar.TabIndex = 1;
		_zoomTrackBar.Text = "Zoom";
		_zoomTrackBar.Value = 10;
		_zoomTrackBar.ValueChanged += new EventHandler (ZoomTrackBar_ValueChanged);
		Controls.Add (_zoomTrackBar);
		// 
		// _printDocument
		// 
		_printDocument = new PrintDocument ();
		_printDocument.PrintPage += new PrintPageEventHandler (PrintDocument_PrintPage);
		_printPreviewControl.Document = _printDocument;
		// 
		// MainForm
		// 
		ClientSize = new Size (350, 350);
		Location = new Point (200, 100);
		StartPosition = FormStartPosition.Manual;
		Text = "bug #81744";
		Load += new EventHandler (MainForm_Load);
	}
Esempio n. 10
0
	public MainForm ()
	{
		// 
		// _printPreviewControl
		// 
		_printPreviewControl = new PrintPreviewControl ();
		_printPreviewControl.Anchor = (AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right);
		_printPreviewControl.Dock = DockStyle.Bottom;
		_printPreviewControl.Height = 295;
		_printPreviewControl.TabIndex = 0;
		_printPreviewControl.Zoom = 1;
		Controls.Add (_printPreviewControl);
		// 
		// _printButton
		// 
		_printButton = new Button ();
		_printButton.Location = new Point (12, 12);
		_printButton.Size = new Size (75, 23);
		_printButton.TabIndex = 1;
		_printButton.Text = "Print";
		_printButton.Click += new System.EventHandler (PrintButton_Click);
		Controls.Add (_printButton);
		// 
		// _printDocument
		// 
		_printDocument = new PrintDocument ();
		_printDocument.PrintPage += new PrintPageEventHandler (PrintDocument_PrintPage);
		_printPreviewControl.Document = _printDocument;
		// 
		// MainForm
		// 
		ClientSize = new Size (350, 350);
		Location = new Point (200, 100);
		StartPosition = FormStartPosition.Manual;
		Text = "bug #81708";
		Load += new EventHandler (MainForm_Load);
	}
Esempio n. 11
0
 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);
     }
 }
Esempio n. 12
0
        public static void PrintAllOrder(OrderKassa[] orders, DateTime selectedDate)
        {
            string  strSelectedDate         = selectedDate.ToLongDateString();
            decimal totalIncomeSelectedDate = GetTotalIncomeSelectedDate(orders);

            float         fontSize  = Convert.ToSingle(ConfigurationManager.AppSettings["FontSize"]);
            Font          printFont = new Font("Arial", fontSize);
            PrintDocument pd        = new PrintDocument();

            pd.PrinterSettings.PrinterName = ConfigurationManager.AppSettings["PrinterName"];

            List <string> lines = new List <string>();

            lines.Add("Meat Compiler\n");
            lines.Add("\nAll order from date: " + strSelectedDate);
            lines.Add("\n-------------------------------------------");

            if (orders.Length <= 0)
            {
                MessageBox.Show("There is no order on the selected date.");
                return;
            }

            decimal grandTotal = 0;

            foreach (OrderKassa o in orders)
            {
                string  tableName  = o.TableSeat.TableName;
                decimal orderTotal = o.OrderTotal;
                grandTotal += orderTotal;
                lines.Add("\n(" + o.OrderNumber + ") " + tableName + ":   " + Helper.FormatPrice(orderTotal));
            }
            lines.Add("\n-------------------------------------------\n");
            lines.Add("\nGrand Total:   " + Helper.FormatPrice(grandTotal));

            int lineIndex = 0;

            pd.PrintPage += (s, ev) =>
            {
                float  linesPerPage = 0;
                float  yPos         = 0;
                int    count        = 0;
                float  leftMargin   = 10;
                float  topMargin    = 10;
                string currentLine  = null;

                // Calculate the number of lines per page.
                linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics);
                // Print each line of the file.
                if (lineIndex < lines.Count)
                {
                    while (count < linesPerPage && (lines[lineIndex] != null))
                    {
                        yPos = topMargin + (count * printFont.GetHeight(ev.Graphics));
                        ev.Graphics.DrawString(lines[lineIndex], printFont, Brushes.Black, leftMargin, yPos, new StringFormat());
                        count++;

                        currentLine = lines[lineIndex];
                        lineIndex++;

                        if (lineIndex >= lines.Count)
                        {
                            break;
                        }
                    }
                }

                // If more lines exist, print another page.
                if (currentLine != null)
                {
                    ev.HasMorePages = true;
                    currentLine     = null;
                }
                else
                {
                    ev.HasMorePages = false;
                }
            };

            pd.EndPrint += (s, ev) =>
            {
            };

            pd.Print();
        }
 public override void OnEndPrint(PrintDocument document, PrintEventArgs e)
 {
 }
            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...");
            }
 public override void OnEndPage(PrintDocument prndoc,
                                PrintPageEventArgs ppea)
 {
     base.OnEndPage(prndoc, ppea);
 }
Esempio n. 16
0
        private void butPrint_Click(object sender, System.EventArgs e)
        {
#if DISABLE_MICROSOFT_OFFICE
            MessageBox.Show(this, "This version of Open Dental does not support Microsoft Word.");
            return;
#endif
            if (listLetters.SelectedIndex == -1)
            {
                MsgBox.Show(this, "Please select a letter first.");
                return;
            }
            LetterMerge letterCur    = ListForCat[listLetters.SelectedIndex];
            string      templateFile = ODFileUtils.CombinePaths(PrefC.GetString(PrefName.LetterMergePath), letterCur.TemplateName);
            string      dataFile     = ODFileUtils.CombinePaths(PrefC.GetString(PrefName.LetterMergePath), letterCur.DataFileName);
            if (!File.Exists(templateFile))
            {
                MsgBox.Show(this, "Template file does not exist.");
                return;
            }
            PrintDocument pd = new PrintDocument();
            if (!PrinterL.SetPrinter(pd, PrintSituation.Default))
            {
                return;
            }
            if (!CreateDataFile(dataFile, letterCur))
            {
                return;
            }
            Word.MailMerge wrdMailMerge;
            //Create an instance of Word.
            Word.Application WrdApp = LetterMerges.WordApp;
            //Open a document.
            Object oName = templateFile;
            wrdDoc = WrdApp.Documents.Open(ref oName, ref oMissing, ref oMissing,
                                           ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                           ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            wrdDoc.Select();
            wrdMailMerge = wrdDoc.MailMerge;
            //Attach the data file.
            wrdDoc.MailMerge.OpenDataSource(dataFile, ref oMissing, ref oMissing, ref oMissing,
                                            ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                            ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            wrdMailMerge.Destination = Word.WdMailMergeDestination.wdSendToPrinter;
            //WrdApp.ActivePrinter=pd.PrinterSettings.PrinterName;
            //replaced with following 4 lines due to MS bug that changes computer default printer
            object   oWBasic   = WrdApp.WordBasic;
            object[] oWBValues = new object[] { pd.PrinterSettings.PrinterName, 1 };
            String[] sWBNames  = new String[] { "Printer", "DoNotSetAsSysDefault" };
            oWBasic.GetType().InvokeMember("FilePrintSetup", BindingFlags.InvokeMethod, null, oWBasic, oWBValues, null, null, sWBNames);
            wrdMailMerge.Execute(ref oFalse);
            //Close the original form document since just one record.
            wrdDoc.Saved = true;
            wrdDoc.Close(ref oFalse, ref oMissing, ref oMissing);
            //At this point, Word remains open with no documents.
            WrdApp.WindowState = Word.WdWindowState.wdWindowStateMinimize;
            wrdMailMerge       = null;
            wrdDoc             = null;
            Commlog CommlogCur = new Commlog();
            CommlogCur.CommDateTime   = DateTime.Now;
            CommlogCur.CommType       = Commlogs.GetTypeAuto(CommItemTypeAuto.MISC);
            CommlogCur.Mode_          = CommItemMode.Mail;
            CommlogCur.SentOrReceived = CommSentOrReceived.Sent;
            CommlogCur.PatNum         = PatCur.PatNum;
            CommlogCur.Note           = "Letter sent: " + letterCur.Description + ". ";
            CommlogCur.UserNum        = Security.CurUser.UserNum;
            Commlogs.Insert(CommlogCur);
            DialogResult = DialogResult.OK;
        }
    public void SetLayoutType(LayoutModes eViewMode)
    {
        PrintDocument pd = new PrintDocument();
        PrinterSettings ps = new PrinterSettings();
        
        //int* y = (int*)500;

        switch (eViewMode)
        {
            case LayoutModes.WYSIWYG:
                //SendMessage(this.Handle, EM_SETTARGETDEVICE, ps.GetHdevmode(), new IntPtr(y));
                break;
            case LayoutModes.WordWrap:
                SendMessage(new HandleRef(this, this.Handle), EM_SETTARGETDEVICE, 0, 0);
                break;
            case LayoutModes.Default:
                SendMessage(new HandleRef(this, this.Handle), EM_SETTARGETDEVICE, 0, 1);
                break;
        }
    }
Esempio n. 18
0
 static PrintSupport()
 {
     _printDoc            = new PrintDocument();
     _printDoc.PrintPage += printDoc_PrintPage;
 }
Esempio n. 19
0
 /// <summary>
 /// Завершает печать
 /// </summary>
 private void EndPrintig(PrintDocument doc)
 {
     doc.PrintPage -= new PrintPageEventHandler(Document_PrintPage);
     doc.EndPrint  -= new PrintEventHandler(Document_EndPrint);
 }
        private void navPrint_Click(object sender, EventArgs e)
        {
            PrintPreviewDialog curPreviewDialog = new PrintPreviewDialog();
            PrintDialog        curPrintDialog   = new PrintDialog();
            Font saveShowDefaultCellStyle       = scoreSummaryDataGridView.DefaultCellStyle.Font;

            scoreSummaryDataGridView.DefaultCellStyle.Font = new Font("Tahoma", 10, FontStyle.Regular);

            bool CenterOnPage    = true;
            bool WithTitle       = true;
            bool WithPaging      = true;
            Font fontPrintTitle  = new Font("Arial Narrow", 14, FontStyle.Bold);
            Font fontPrintFooter = new Font("Times New Roman", 10);

            curPrintDialog.AllowCurrentPage = true;
            curPrintDialog.AllowPrintToFile = false;
            curPrintDialog.AllowSelection   = true;
            curPrintDialog.AllowSomePages   = true;
            curPrintDialog.PrintToFile      = false;
            curPrintDialog.ShowHelp         = false;
            curPrintDialog.ShowNetwork      = false;
            curPrintDialog.UseEXDialog      = true;
            curPrintDialog.PrinterSettings.DefaultPageSettings.Landscape = true;

            if (curPrintDialog.ShowDialog() == DialogResult.OK)
            {
                String printTitle = Properties.Settings.Default.Mdi_Title
                                    + "\n Sanction " + mySanctionNum + " held on " + myTourRow["EventDates"].ToString()
                                    + "\n" + this.Text;
                myPrintDoc = new PrintDocument();
                myPrintDoc.DocumentName = this.Text;
                myPrintDoc.DefaultPageSettings.Margins   = new Margins(25, 25, 25, 25);
                myPrintDoc.DefaultPageSettings.Landscape = true;
                myPrintDataGrid = new DataGridViewPrinter(scoreSummaryDataGridView, myPrintDoc,
                                                          CenterOnPage, WithTitle, printTitle, fontPrintTitle, Color.DarkBlue, WithPaging);

                myPrintDataGrid.SubtitleList();
                StringRowPrinter mySubtitle;
                StringFormat     SubtitleStringFormat = new StringFormat();
                SubtitleStringFormat.Trimming    = StringTrimming.Word;
                SubtitleStringFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
                SubtitleStringFormat.Alignment   = StringAlignment.Center;

                int curLabelLocSlalom = 0, curLabelLocTrick = 0, curLabelLocJump = 0, curLabelLocOverall = 0;
                if (myTourRules.ToLower().Equals("ncwsa"))
                {
                    curLabelLocSlalom  = 295;
                    curLabelLocTrick   = 572;
                    curLabelLocJump    = 737;
                    curLabelLocOverall = 887;
                }
                else
                {
                    if (EventGroup.Visible)
                    {
                        curLabelLocSlalom  = 244;
                        curLabelLocTrick   = 550;
                        curLabelLocJump    = 729;
                        curLabelLocOverall = 897;
                    }
                    else
                    {
                        curLabelLocSlalom  = 204;
                        curLabelLocTrick   = 517;
                        curLabelLocJump    = 697;
                        curLabelLocOverall = 862;
                    }
                }

                mySubtitle = new StringRowPrinter(SlalomLabel.Text,
                                                  curLabelLocSlalom, 0, Convert.ToInt32(SlalomLabel.Width * .8), SlalomLabel.Size.Height,
                                                  SlalomLabel.ForeColor, SlalomLabel.BackColor, SlalomLabel.Font, SubtitleStringFormat);
                myPrintDataGrid.SubtitleRow = mySubtitle;
                mySubtitle = new StringRowPrinter(TrickLabel.Text,
                                                  curLabelLocTrick, 0, Convert.ToInt32(TrickLabel.Width * .65), TrickLabel.Size.Height,
                                                  TrickLabel.ForeColor, TrickLabel.BackColor, TrickLabel.Font, SubtitleStringFormat);
                myPrintDataGrid.SubtitleRow = mySubtitle;
                mySubtitle = new StringRowPrinter(JumpLabel.Text,
                                                  curLabelLocJump, 0, Convert.ToInt32(JumpLabel.Width * .65), JumpLabel.Size.Height,
                                                  JumpLabel.ForeColor, JumpLabel.BackColor, JumpLabel.Font, SubtitleStringFormat);
                myPrintDataGrid.SubtitleRow = mySubtitle;
                mySubtitle = new StringRowPrinter(OverallLabel.Text,
                                                  curLabelLocOverall, 0, OverallLabel.Size.Width, OverallLabel.Size.Height,
                                                  OverallLabel.ForeColor, OverallLabel.BackColor, OverallLabel.Font, SubtitleStringFormat);
                myPrintDataGrid.SubtitleRow = mySubtitle;

                myPrintDoc.PrinterSettings     = curPrintDialog.PrinterSettings;
                myPrintDoc.DefaultPageSettings = curPrintDialog.PrinterSettings.DefaultPageSettings;
                myPrintDoc.PrintPage          += new PrintPageEventHandler(printDoc_PrintPage);
                curPreviewDialog.Document      = myPrintDoc;
                curPreviewDialog.ShowDialog();
            }

            scoreSummaryDataGridView.DefaultCellStyle.Font = saveShowDefaultCellStyle;
        }
Esempio n. 21
0
        public Game()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            boxes = new ComboBox[9, 9];
            Font font = null;


            for (int x = 0; x < 9; x++)
            {
                for (int y = 0; y < 9; y++)
                {
                    ComboBox comboBox = new ComboBox();
                    if (font == null)
                    {
                        font = new Font(comboBox.Font, FontStyle.Bold);
                    }
                    comboBox.Font = font;

                    String[] items = new String[] { "-", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
                    comboBox.Items.AddRange(items);
                    comboBox.DropDownStyle    = ComboBoxStyle.DropDownList;
                    comboBox.Location         = new Point(x * 40 + 10, y * 30 + 10);
                    comboBox.Size             = new Size(36, 21);
                    comboBox.SelectedIndex    = 0;
                    comboBox.MaxDropDownItems = 10;
                    this.Controls.Add(comboBox);
                    boxes[y, x] = comboBox;
                }
            }

            Sudoku s = new Sudoku();

            byte[,] d = s.read_from_file();


            /*
             *
             * tbHistory.AppendText("-------------------------------\r\n");
             *          if(!s.IsSudokuFeasible())
             *          {//
             *                  tbHistory.AppendText("Sudoku not feasible\r\n");
             *                  return;
             *          }
             *
             * DateTime now = DateTime.Now;
             *          tbHistory.AppendText("Solve started: " + now.ToLongTimeString() + "\r\n");
             *
             *          if(s.Solve())
             *          {
             *                  // Solve successful
             *                  tbHistory.AppendText("Solve successful\r\n");
             *
             *                  d = s.Data;
             *                  SetData(d);
             *          }
             *          else
             *          {
             *                  // Solve failed
             *                  tbHistory.AppendText("Solve failed\r\n");
             *          }
             * tbHistory.AppendText(String.Format("{0} seconds\r\n", (DateTime.Now - now).TotalSeconds));
             *
             *          // Add blank
             * tbHistory.AppendText("\r\n");
             */
            SetData(d);
            s.Data = d;
            if (!s.IsSudokuFeasible())
            {//
                tbHistory.AppendText("Sudoku not feasible\r\n");
                return;
            }
            if (s.Solve())
            {
                // Solve successful
                tbHistory.AppendText("Solve successful\r\n");

                d = s.Data;
                SetData(d);
            }
            else
            {
                // Solve failed
                tbHistory.AppendText("Solve failed\r\n");
            }

            m_printDocument            = new PrintDocument();
            m_printDocument.PrintPage += new PrintPageEventHandler(PrintPage);
        }
Esempio n. 22
0
        // Main conversion routine
        public static new int Convert(String inputFile, String outputFile, Hashtable options)
        {
            Boolean running = (Boolean)options["noquit"];

            Microsoft.Office.Interop.Excel.Application app       = null;
            Microsoft.Office.Interop.Excel.Workbooks   workbooks = null;
            Microsoft.Office.Interop.Excel.Workbook    workbook  = null;
            System.Object activeSheet       = null;
            Window        activeWindow      = null;
            Windows       wbWin             = null;
            Hashtable     templatePageSetup = new Hashtable();

            String  tmpFile  = null;
            object  oMissing = System.Reflection.Missing.Value;
            Boolean nowrite  = (Boolean)options["readonly"];

            try
            {
                // Excel can be very slow to start up, so try to get the COM
                // object a few times
                int tries = 10;
                app = new Microsoft.Office.Interop.Excel.Application();
                while (tries > 0)
                {
                    try
                    {
                        // Try to set a property on the object
                        app.ScreenUpdating = false;
                    }
                    catch (COMException)
                    {
                        // Decrement the number of tries and have a bit of a snooze
                        tries--;
                        Thread.Sleep(500);
                        continue;
                    }
                    // Looks ok, so bail out of the loop
                    break;
                }
                if (tries == 0)
                {
                    ReleaseCOMObject(app);
                    return((int)ExitCode.ApplicationError);
                }

                app.Visible                   = true;
                app.DisplayAlerts             = false;
                app.AskToUpdateLinks          = false;
                app.AlertBeforeOverwriting    = false;
                app.EnableLargeOperationAlert = false;
                app.Interactive               = false;
                app.FeatureInstall            = Microsoft.Office.Core.MsoFeatureInstall.msoFeatureInstallNone;

                var     onlyActiveSheet       = (Boolean)options["excel_active_sheet"];
                Boolean includeProps          = !(Boolean)options["excludeprops"];
                Boolean skipRecalculation     = (Boolean)options["excel_no_recalculate"];
                Boolean showHeadings          = (Boolean)options["excel_show_headings"];
                Boolean showFormulas          = (Boolean)options["excel_show_formulas"];
                Boolean isHidden              = (Boolean)options["hidden"];
                Boolean screenQuality         = (Boolean)options["screen"];
                Boolean fitToPageWidth        = (Boolean)options["excel_fit_to_page_width"];
                Boolean updateLinks           = !(Boolean)options["excel_no_link_update"];
                int     maxRows               = (int)options[@"excel_max_rows"];
                int     worksheetNum          = (int)options["excel_worksheet"];
                int     sheetForConversionIdx = 0;
                activeWindow = app.ActiveWindow;
                Sheets               allSheets = null;
                XlFileFormat         fmt       = XlFileFormat.xlOpenXMLWorkbook;
                XlFixedFormatQuality quality   = XlFixedFormatQuality.xlQualityStandard;
                if (isHidden)
                {
                    // Try and at least minimise it
                    app.WindowState = XlWindowState.xlMinimized;
                    app.Visible     = false;
                }

                String readPassword = "";
                if (!String.IsNullOrEmpty((String)options["password"]))
                {
                    readPassword = (String)options["password"];
                }
                Object oReadPass = (Object)readPassword;

                String writePassword = "";
                if (!String.IsNullOrEmpty((String)options["writepassword"]))
                {
                    writePassword = (String)options["writepassword"];
                }
                Object oWritePass = (Object)writePassword;

                // Check for password protection and no password
                if (Converter.IsPasswordProtected(inputFile) && String.IsNullOrEmpty(readPassword))
                {
                    Console.WriteLine("Unable to open password protected file");
                    return((int)ExitCode.PasswordFailure);
                }

                app.EnableEvents = (bool)options["excel_auto_macros"];
                workbooks        = app.Workbooks;
                // If we have no write password and we're attempting to open for writing, we might be
                // caught out by an unexpected write password
                if (writePassword == "" && !nowrite)
                {
                    oWritePass = (Object)"FAKEPASSWORD";
                    try
                    {
                        workbook = workbooks.Open(inputFile, updateLinks, nowrite, oMissing, oReadPass, oWritePass, true, oMissing, oMissing, oMissing, oMissing, oMissing, false, oMissing, oMissing);
                    }
                    catch (System.Runtime.InteropServices.COMException)
                    {
                        // Attempt to open it in read-only mode
                        workbook = workbooks.Open(inputFile, updateLinks, true, oMissing, oReadPass, oWritePass, true, oMissing, oMissing, oMissing, oMissing, oMissing, false, oMissing, oMissing);
                    }
                }
                else
                {
                    workbook = workbooks.Open(inputFile, updateLinks, nowrite, oMissing, oReadPass, oWritePass, true, oMissing, oMissing, oMissing, oMissing, oMissing, false, oMissing, oMissing);
                }

                // Add in a delay to let Excel sort itself out
                AddCOMDelay(options);

                // Unable to open workbook
                if (workbook == null)
                {
                    return((int)ExitCode.FileOpenFailure);
                }

                if (app.EnableEvents)
                {
                    workbook.RunAutoMacros(XlRunAutoMacro.xlAutoOpen);
                }
                // Get any template options
                SetPageOptionsFromTemplate(app, workbooks, options, ref templatePageSetup);

                // Get the sheets
                allSheets = workbook.Sheets;

                // Try and avoid xls files raising a dialog
                var temporaryStorageDir = Path.GetTempFileName();
                File.Delete(temporaryStorageDir);
                Directory.CreateDirectory(temporaryStorageDir);
                // We will save as xlsb (binary format) since this doesn't raise some errors when processing
                tmpFile = Path.Combine(temporaryStorageDir, Path.GetFileNameWithoutExtension(inputFile) + ".xlsb");
                fmt     = XlFileFormat.xlExcel12;

                // Set up the print quality
                if (screenQuality)
                {
                    quality = XlFixedFormatQuality.xlQualityMinimum;
                }

                // If a worksheet has been specified, try and use just the one
                if (worksheetNum > 0)
                {
                    // Force us just to use the active sheet
                    onlyActiveSheet = true;
                    try
                    {
                        if (worksheetNum > allSheets.Count)
                        {
                            // Sheet count is too big
                            return((int)ExitCode.WorksheetNotFound);
                        }
                        if (allSheets[worksheetNum] is _Worksheet)
                        {
                            ((_Worksheet)allSheets[worksheetNum]).Activate();
                            sheetForConversionIdx = ((_Worksheet)allSheets[worksheetNum]).Index;
                        }
                        else if (allSheets[worksheetNum] is _Chart)
                        {
                            ((_Chart)allSheets[worksheetNum]).Activate();
                            sheetForConversionIdx = ((_Chart)allSheets[worksheetNum]).Index;
                        }
                    }
                    catch (Exception)
                    {
                        return((int)ExitCode.WorksheetNotFound);
                    }
                }
                if (showFormulas)
                {
                    // Determine whether to show formulas
                    try
                    {
                        activeWindow.DisplayFormulas = true;
                    }
                    catch (Exception) { }
                }

                // Keep the windows hidden
                if (isHidden)
                {
                    wbWin = workbook.Windows;
                    if (null != wbWin)
                    {
                        if (wbWin.Count > 0)
                        {
                            wbWin[1].Visible = false;
                        }
                    }
                    if (null != activeWindow)
                    {
                        activeWindow.Visible = false;
                    }
                }
                // Keep track of the active sheet
                if (workbook.ActiveSheet != null)
                {
                    activeSheet = workbook.ActiveSheet;
                }

                // Large excel files may simply not print reliably - if the excel_max_rows
                // configuration option is set, then we must close up and forget about
                // converting the file. However, if a print area is set in one of the worksheets
                // in the document, then assume the author knew what they were doing and
                // use the print area.

                // We may need to loop through all the worksheets in the document
                // depending on the options given. If there are maximum row restrictions
                // or formulas are being shown, then we need to loop through all the
                // worksheets
                if (maxRows > 0 || showFormulas || showHeadings)
                {
                    var row_count_check_ok = true;
                    var found_rows         = 0;
                    var found_worksheet    = "";
                    // Loop through all the sheets (worksheets and charts)
                    for (int wsIdx = 1; wsIdx <= allSheets.Count; wsIdx++)
                    {
                        var ws = allSheets.Item[wsIdx];

                        // Skip anything that is not the active sheet
                        if (onlyActiveSheet)
                        {
                            // Have to be careful to treat _Worksheet and _Chart items differently
                            try
                            {
                                int itemIndex = 1;
                                if (activeSheet is _Worksheet)
                                {
                                    itemIndex = ((Worksheet)activeSheet).Index;
                                }
                                else if (activeSheet is _Chart)
                                {
                                    itemIndex = ((Microsoft.Office.Interop.Excel.Chart)activeSheet).Index;
                                }
                                if (wsIdx != itemIndex)
                                {
                                    ReleaseCOMObject(ws);
                                    continue;
                                }
                            }
                            catch (Exception)
                            {
                                if (ws != null)
                                {
                                    ReleaseCOMObject(ws);
                                }
                                continue;
                            }
                            sheetForConversionIdx = wsIdx;
                        }

                        if (showHeadings && ws is _Worksheet)
                        {
                            PageSetup pageSetup = null;
                            try
                            {
                                pageSetup = ((Worksheet)ws).PageSetup;
                                pageSetup.PrintHeadings = true;
                            }
                            catch (Exception) { }
                            finally
                            {
                                ReleaseCOMObject(pageSetup);
                            }
                        }

                        // If showing formulas, make things auto-fit
                        if (showFormulas && ws is _Worksheet)
                        {
                            Range cols = null;
                            try
                            {
                                ((_Worksheet)ws).Activate();
                                activeWindow.DisplayFormulas = true;
                                cols = ((Worksheet)ws).Columns;
                                cols.AutoFit();
                            }
                            catch (Exception) { }
                            finally
                            {
                                ReleaseCOMObject(cols);
                            }
                        }

                        // If there is a maximum row count, make sure we check each worksheet
                        if (maxRows > 0 && ws is _Worksheet)
                        {
                            // Check for a print area
                            var pageSetup = ((Worksheet)ws).PageSetup;
                            var printArea = pageSetup.PrintArea;
                            ReleaseCOMObject(pageSetup);
                            if (string.IsNullOrEmpty(printArea))
                            {
                                // There is no print area, check that the row count is <= to the
                                // excel_max_rows value. Note that we can't just take the range last
                                // row, as this may return a huge value, rather find the last non-blank
                                // row.
                                var row_count = 0;
                                var range     = ((Worksheet)ws).UsedRange;
                                if (range != null)
                                {
                                    var rows = range.Rows;
                                    if (rows != null && rows.Count > maxRows)
                                    {
                                        var cells = range.Cells;
                                        if (cells != null)
                                        {
                                            var cellSearch = cells.Find("*", oMissing, oMissing, oMissing, oMissing, Microsoft.Office.Interop.Excel.XlSearchDirection.xlPrevious, false, oMissing, oMissing);
                                            // Make sure we actually get some results, since the worksheet may be totally blank
                                            if (cellSearch != null)
                                            {
                                                row_count       = cellSearch.Row;
                                                found_worksheet = ((Worksheet)ws).Name;
                                            }
                                            ReleaseCOMObject(cellSearch);
                                        }
                                        ReleaseCOMObject(cells);
                                    }
                                    ReleaseCOMObject(rows);
                                }
                                ReleaseCOMObject(range);

                                if (row_count > maxRows)
                                {
                                    // Too many rows on this worksheet - mark the workbook as unprintable
                                    row_count_check_ok = false;
                                    found_rows         = row_count;
                                    Converter.ReleaseCOMObject(ws);
                                    break;
                                }
                            }
                        } // End of row check
                        Converter.ReleaseCOMObject(ws);
                    }

                    // Make sure we are not converting a document with too many rows
                    if (row_count_check_ok == false)
                    {
                        throw new Exception(String.Format("Too many rows to process ({0}) on worksheet {1}", found_rows, found_worksheet));
                    }
                }

                // Allow for re-calculation to be skipped
                if (skipRecalculation)
                {
                    app.Calculation         = XlCalculation.xlCalculationManual;
                    app.CalculateBeforeSave = false;
                }

                workbook.SaveAs(tmpFile, fmt, Type.Missing, Type.Missing, Type.Missing, false, XlSaveAsAccessMode.xlNoChange, Type.Missing, false, Type.Missing, Type.Missing, Type.Missing);

                // Fit to to one page wide.
                if (fitToPageWidth)
                {
                    templatePageSetup["FitToPagesWide"] = 1;
                    templatePageSetup["FitToPagesTall"] = false;
                    templatePageSetup["Zoom"]           = false;
                }

                if (onlyActiveSheet)
                {
                    // Set up a delegate function for times we want to print
                    PrintDocument printFunc = delegate(string destination, string printer)
                    {
                        ((Worksheet)activeSheet).PrintOut(ActivePrinter: printer, PrintToFile: true, PrToFileName: destination);
                    };

                    if (sheetForConversionIdx > 0)
                    {
                        activeSheet = allSheets.Item[sheetForConversionIdx];
                    }
                    if (activeSheet is _Worksheet)
                    {
                        var wps = ((_Worksheet)activeSheet).PageSetup;
                        SetPageSetupProperties(templatePageSetup, wps);
                        if (String.IsNullOrEmpty((string)options["printer"]))
                        {
                            try
                            {
                                ((Worksheet)activeSheet).ExportAsFixedFormat(XlFixedFormatType.xlTypePDF,
                                                                             outputFile, quality, includeProps, false, Type.Missing, Type.Missing, false, Type.Missing);
                            }
                            catch (Exception)
                            {
                                if (!String.IsNullOrEmpty((string)options["fallback_printer"]))
                                {
                                    PrintToGhostscript((string)options["fallback_printer"], outputFile, printFunc);
                                }
                                else
                                {
                                    throw;
                                }
                            }
                        }
                        else
                        {
                            PrintToGhostscript((string)options["printer"], outputFile, printFunc);
                        }
                        ReleaseCOMObject(wps);
                    }
                    else if (activeSheet is _Chart)
                    {
                        var wps = ((_Chart)activeSheet).PageSetup;
                        SetPageSetupProperties(templatePageSetup, wps);
                        ((Microsoft.Office.Interop.Excel.Chart)activeSheet).ExportAsFixedFormat(XlFixedFormatType.xlTypePDF,
                                                                                                outputFile, quality, includeProps, false, Type.Missing, Type.Missing, false, Type.Missing);
                        ReleaseCOMObject(wps);
                    }
                    else
                    {
                        return((int)ExitCode.UnknownError);
                    }
                    AddCOMDelay(options);
                }
                else
                {
                    PrintDocument printFunc = delegate(string destination, string printer)
                    {
                        workbook.PrintOutEx(ActivePrinter: printer, PrintToFile: true, PrToFileName: destination);
                    };

                    // Set up the template page setup options on all the worksheets
                    // in the workbook
                    var worksheets = workbook.Worksheets;
                    for (int wsIdx = 1; wsIdx <= worksheets.Count; wsIdx++)
                    {
                        var ws  = worksheets[wsIdx];
                        var wps = (ws is _Worksheet) ? ((_Worksheet)ws).PageSetup : ((_Chart)ws).PageSetup;
                        SetPageSetupProperties(templatePageSetup, wps);
                        ReleaseCOMObject(wps);
                        ReleaseCOMObject(ws);
                    }
                    ReleaseCOMObject(worksheets);

                    if (String.IsNullOrEmpty((string)options["printer"]))
                    {
                        try
                        {
                            workbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF,
                                                         outputFile, quality, includeProps, false, Type.Missing, Type.Missing, false, Type.Missing);
                        }
                        catch (Exception)
                        {
                            if (!String.IsNullOrEmpty((string)options["fallback_printer"]))
                            {
                                PrintToGhostscript((string)options["fallback_printer"], outputFile, printFunc);
                            }
                            else
                            {
                                throw;
                            }
                        }
                    }
                    else
                    {
                        PrintToGhostscript((string)options["printer"], outputFile, printFunc);
                    }
                }

                ReleaseCOMObject(allSheets);
                ReleaseCOMObject(fmt);
                ReleaseCOMObject(quality);

                return((int)ExitCode.Success);
            }
            catch (COMException ce)
            {
                if ((uint)ce.ErrorCode == 0x800A03EC)
                {
                    return((int)ExitCode.EmptyWorksheet);
                }
                else
                {
                    Console.WriteLine(ce.Message);
                    return((int)ExitCode.UnknownError);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return((int)ExitCode.UnknownError);
            }
            finally
            {
                if (workbook != null)
                {
                    ReleaseCOMObject(activeSheet);
                    ReleaseCOMObject(activeWindow);
                    ReleaseCOMObject(wbWin);
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    // Excel sometimes needs a bit of a delay before we close in order to
                    // let things get cleaned up
                    workbook.Saved = true;
                    CloseExcelWorkbook(workbook);
                }

                if (!running)
                {
                    if (workbooks != null)
                    {
                        workbooks.Close();
                    }

                    if (app != null)
                    {
                        ((Microsoft.Office.Interop.Excel._Application)app).Quit();
                    }
                }

                // Clean all the COM leftovers
                ReleaseCOMObject(workbook);
                ReleaseCOMObject(workbooks);
                ReleaseCOMObject(app);
                GC.Collect();
                GC.WaitForPendingFinalizers();

                if (tmpFile != null && File.Exists(tmpFile))
                {
                    System.IO.File.Delete(tmpFile);
                    // Remove the temporary path to the temp file
                    Directory.Delete(Path.GetDirectoryName(tmpFile));
                }
            }
        }
Esempio n. 23
0
 public override void OnEndPage(PrintDocument document, PrintPageEventArgs e)
 {
     base.OnEndPage(document, e);
     e.Graphics.Dispose();
 }
Esempio n. 24
0
        public void Print()
        {
            foreach (var report in _localReports)
            {
                Warning[] warnings;
                var       streams          = new List <Stream>();
                var       currentPageIndex = 0;

                report.Render("Image", Export(report), (name, fileNameExtension, encoding, mimeType, willSeek) =>
                {
                    var stream = new MemoryStream();
                    streams.Add(stream);
                    return(stream);
                }, out warnings);

                foreach (Stream stream in streams)
                {
                    stream.Position = 0;
                }

                if (streams == null || streams.Count == 0)
                {
                    throw new Exception("Error: no stream to print.");
                }

                var printDocument = new PrintDocument
                {
                    DefaultPageSettings = new PageSettings(_printerSettings),
                    PrinterSettings     = _printerSettings
                };


                if (!printDocument.PrinterSettings.IsValid)
                {
                    throw new Exception("SSSSSS");
                }
                else
                {
                    printDocument.PrintPage += (sender, e) =>
                    {
                        Metafile  pageImage    = new Metafile(streams[currentPageIndex]);
                        Rectangle adjustedRect = new Rectangle(
                            e.PageBounds.Left - (int)e.PageSettings.HardMarginX,
                            e.PageBounds.Top - (int)e.PageSettings.HardMarginY,
                            e.PageBounds.Width,
                            e.PageBounds.Height);
                        e.Graphics.FillRectangle(Brushes.White, adjustedRect);
                        e.Graphics.DrawImage(pageImage, adjustedRect);
                        currentPageIndex++;
                        e.HasMorePages = (currentPageIndex < streams.Count);
                        e.Graphics.DrawRectangle(Pens.Red, adjustedRect);
                    };
                    printDocument.EndPrint += (Sender, e) =>
                    {
                        if (streams != null)
                        {
                            foreach (Stream stream in streams)
                            {
                                stream.Close();
                            }

                            streams = null;
                        }
                    };

                    printDocument.Print();
                }
            }
        }
Esempio n. 25
0
        public static void PrintAllOrderWithBTW(OrderKassa[] orders, DateTime selectedDate)
        {
            string  strSelectedDate         = selectedDate.ToLongDateString();
            decimal totalIncomeSelectedDate = GetTotalIncomeSelectedDate(orders);

            float         fontSize  = Convert.ToSingle(ConfigurationManager.AppSettings["FontSize"]);
            Font          printFont = new Font("Arial", fontSize);
            PrintDocument pd        = new PrintDocument();

            pd.PrinterSettings.PrinterName = ConfigurationManager.AppSettings["PrinterName"];

            List <string> lines = new List <string>();

            lines.Add("Meat Compiler\n");
            lines.Add("\nAll order from date: " + strSelectedDate);
            lines.Add("\n-------------------------------------------");

            if (orders.Length <= 0)
            {
                MessageBox.Show("There is no order on the selected date.");
                return;
            }

            decimal grandTotal         = 0;
            decimal grandSubtotal      = 0;
            decimal grandSubtotal6     = 0;
            decimal grandTotalBTW6     = 0;
            decimal grandSubtotalDrink = 0;
            decimal grandTotalBTW19    = 0;
            decimal grandSubtotal19    = 0;

            foreach (OrderKassa o in orders)
            {
                string  tableName  = o.TableSeat.TableName;
                decimal orderTotal = o.OrderTotal;
                grandTotal += orderTotal;
                lines.Add("\n(" + o.OrderNumber + ") " + tableName + ":   " + Helper.FormatPrice(orderTotal));

                var     orderDetails = o.OrderDetails.ToList();
                decimal orderTotal6  = 0;
                decimal orderTotal19 = 0;
                foreach (OrderDetail orderDetail in orderDetails)
                {
                    if (orderDetail.MenuCard.MenuGroupId != 16 && orderDetail.MenuCard.MenuGroupId != 19 && orderDetail.MenuCard.MenuGroupId != 20)
                    {
                        if (orderDetail.CustomMenuPrice > 0)
                        {
                            orderTotal6 += orderDetail.CustomMenuPrice * orderDetail.Quantity;
                        }
                        else
                        {
                            orderTotal6 += orderDetail.MenuCard.Price * orderDetail.Quantity;
                        }
                    }
                    else
                    {
                        if (orderDetail.CustomMenuPrice > 0)
                        {
                            orderTotal19 += orderDetail.CustomMenuPrice * orderDetail.Quantity;
                        }
                        else
                        {
                            orderTotal19 += orderDetail.MenuCard.Price * orderDetail.Quantity;
                        }
                    }
                }

                decimal btwAmount6 = orderTotal6 * (decimal)((decimal)6 / (decimal)106);
                decimal subTotal6  = orderTotal6 - btwAmount6;

                decimal btwAmount19 = orderTotal19 * (decimal)((decimal)19 / (decimal)119);
                decimal subTotal19  = orderTotal19 - btwAmount19;

                grandSubtotal  += orderTotal6;
                grandSubtotal6 += subTotal6;
                grandTotalBTW6 += btwAmount6;

                grandSubtotalDrink += orderTotal19;
                grandSubtotal19    += subTotal19;
                grandTotalBTW19    += btwAmount19;
            }
            lines.Add("\n-------------------------------------------\n");
            if (grandSubtotal > 0)
            {
                lines.Add("\nSubtotal: " + Helper.FormatPrice(grandSubtotal6));
                lines.Add("\nBTW 6%: " + Helper.FormatPrice(grandTotalBTW6));
            }

            if (grandSubtotalDrink > 0)
            {
                lines.Add("\nSubtotal Alcoholic Drink: " + Helper.FormatPrice(grandSubtotal19));
                lines.Add("\nBTW 19%: " + Helper.FormatPrice(grandTotalBTW19));
            }
            lines.Add("\nGrand Total:   " + Helper.FormatPrice(grandTotal));

            int lineIndex = 0;

            pd.PrintPage += (s, ev) =>
            {
                float  linesPerPage = 0;
                float  yPos         = 0;
                int    count        = 0;
                float  leftMargin   = 10;
                float  topMargin    = 10;
                string currentLine  = null;

                // Calculate the number of lines per page.
                linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics);
                // Print each line of the file.
                if (lineIndex < lines.Count)
                {
                    while (count < linesPerPage && (lines[lineIndex] != null))
                    {
                        yPos = topMargin + (count * printFont.GetHeight(ev.Graphics));
                        ev.Graphics.DrawString(lines[lineIndex], printFont, Brushes.Black, leftMargin, yPos, new StringFormat());
                        count++;

                        currentLine = lines[lineIndex];
                        lineIndex++;

                        if (lineIndex >= lines.Count)
                        {
                            break;
                        }
                    }
                }

                // If more lines exist, print another page.
                if (currentLine != null)
                {
                    ev.HasMorePages = true;
                    currentLine     = null;
                }
                else
                {
                    ev.HasMorePages = false;
                }
            };

            pd.EndPrint += (s, ev) =>
            {
            };

            pd.Print();
        }
Esempio n. 26
0
        /// <summary>
        /// See https://stackoverflow.com/questions/25823910/pscmdlet-dynamic-auto-complete-a-parameter-like-get-process
        /// </summary>
        /// <returns></returns>
        public object GetDynamicParameters()
        {
            // We can't report errors here
            if (WinPrint.Core.Models.ModelLocator.Current.Settings == null)
            {
                //System.Console.WriteLine($"Settings are not valid. Check {ServiceLocator.Current.SettingsService.SettingsFileName}.");
                return(null);
            }

            var runtimeDict = new RuntimeDefinedParameterDictionary();

            // -PrinterName
            var printerNames = new List <string>();

            using var pd = new PrintDocument();

            if (!string.IsNullOrEmpty(PrinterName))
            {
                PrinterName = PrinterName.Trim('\"').Trim('\'');
                pd.PrinterSettings.PrinterName = PrinterName;

                foreach (PaperSize size in pd.PrinterSettings.PaperSizes)
                {
                    printerNames.Add(size.PaperName);
                }
            }

            runtimeDict.Add("PaperSize", new RuntimeDefinedParameter("PaperSize", typeof(string), new Collection <Attribute>()
            {
                new ParameterAttribute()
                {
                    HelpMessage      = "The paper size name. E.g. \"Letter\"",
                    ParameterSetName = "Print"
                },
                printerNames.Count > 0 ? new ValidateSetAttribute(printerNames.ToArray()) : null
            }));

            // -SheetDefinition
            //  [Parameter(HelpMessage = "Name of the WinPrint sheet definition to use (e.g. \"Default 2-Up\")",
            //    ParameterSetName = "Print")]
            runtimeDict.Add("SheetDefinition", new RuntimeDefinedParameter("SheetDefinition", typeof(string), new Collection <Attribute>()
            {
                new ParameterAttribute()
                {
                    HelpMessage      = "Name of the WinPrint sheet definition to use (e.g. \"Default 2-Up\").",
                    ParameterSetName = "Print"
                },
                ModelLocator.Current.Settings.Sheets.Count > 0 ? new ValidateSetAttribute(ModelLocator.Current.Settings.Sheets.Values.Select(s => s.Name).ToArray()) : null
            }));

            // -ContentTypeEngine
            runtimeDict.Add("ContentTypeEngine", new RuntimeDefinedParameter("ContentTypeEngine", typeof(string), new Collection <Attribute>()
            {
                new ParameterAttribute()
                {
                    HelpMessage      = "Optional name of the WinPrint Content Type Engine to use. If specified, automatic selection will be overridden. E.g. \"TextCte\".",
                    ParameterSetName = "Print"
                },
                new ValidateSetAttribute(ContentTypeEngineBase.GetDerivedClassesCollection().Select(cte => cte.GetType().Name).ToArray())
            }));
            return(runtimeDict);
        }
Esempio n. 27
0
 public override void OnEndPrint(PrintDocument document, PrintEventArgs e)
 {
     base.OnEndPrint(document, e);
 }
Esempio n. 28
0
 public TestForm()
 {
     InitializeComponent();
     _printer = new PrintDocument();
 }
Esempio n. 29
0
        private void button3_Click(object sender, EventArgs e)
        {
            PrintDocument fPrintDocument = new PrintDocument();     //获取默认打印机的方法

            label3.Text = fPrintDocument.PrinterSettings.PrinterName;
        }
Esempio n. 30
0
        private void AddPasien_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            _mDaftarBaru = new MDaftarBaru(" ", " ", " ", " ", " ");
            var ci = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name);

            ci.DateTimeFormat.ShortDatePattern  = "yyyy-MM-dd";
            Thread.CurrentThread.CurrentCulture = ci;

            var cmd = new DBCommand(conn);

            if (checkTextBoxValue() && dtTanggalLahir.SelectedDate != null)
            {
                var cbp      = (ComboboxPairs)cbPoliklinik.SelectedItem;
                var policode = cbp.nama_poliklinik;
                //DateTime dt = DateTime.ParseExact(, "dd-MM-yyyy", CultureInfo.InvariantCulture);

                var norm = TxtNoRm.Text.ToUpper();
                no_rm = norm;
                var identitas    = TxtNoIdentitas.Text;
                var namaPasien   = TxtNamaPasien.Text;
                var noTelp       = TxtNoTelp.Text;
                var alamat       = TextAlamat.Text;
                var tglLahir     = dtTanggalLahir.SelectedDate.Value.Date.ToString("yyyy-MM-dd");
                var jenisKelamin = cbJenisKelamin.Text;
                var poliklinik   = policode;
                var golDarah     = cbGolDarah.Text;
                var jenis_id     = "";

                Debug.WriteLine(norm.Length);
                Debug.WriteLine(identitas.Length);
                Debug.WriteLine(namaPasien.Length);
                Debug.WriteLine(noTelp.Length);
                Debug.WriteLine(alamat.Length);
                Debug.WriteLine(jenisKelamin.Length);
                Debug.WriteLine(poliklinik.Length);
                Debug.WriteLine(golDarah.Length);


                if (chkKtp.IsChecked ?? true)
                {
                    jenis_id = chkKtp.Content.ToString();
                }

                if (chkSim.IsChecked ?? true)
                {
                    jenis_id = chkSim.Content.ToString();
                }

                if (chkKartuPelajar.IsChecked ?? true)
                {
                    jenis_id = chkKartuPelajar.Content.ToString();
                }

                if (chkLainnya.IsChecked ?? true)
                {
                    jenis_id = chkLainnya.Content.ToString();
                }

                if (!Regex.IsMatch(identitas, "^[A-Za-z]+$") && !Regex.IsMatch(noTelp, "^[A-Za-z]+$") &&
                    Regex.IsMatch(namaPasien, @"^[a-zA-Z\s]*$"))
                {
                    if (cmd.CountIdPasienExists(identitas) != 1)
                    {
                        if (cmd.CountRmPasienExists(norm) != 1)
                        {
                            if (cmd.InsertDataPasien(identitas, norm, namaPasien, tglLahir, jenisKelamin, noTelp,
                                                     alamat,
                                                     golDarah, jenis_id))
                            {
                                var last    = cmd.GetLastNoUrut(policode);
                                var no_urut = 0;

                                if (last == 0)
                                {
                                    no_urut = 1;
                                }
                                else
                                {
                                    no_urut = last + 1;
                                }

                                this.no_urut = no_urut;
                                poli         = cbp.kode_poliklinik;

                                if (cmd.InsertAntrian(norm, no_urut, policode))
                                {
                                    var isPrinted = false;

                                    if (chkCetakKartu.IsChecked == true)
                                    {
                                        while (!isPrinted)
                                        {
                                            try
                                            {
                                                if (!string.IsNullOrEmpty(identitas))
                                                {
                                                    if (sp.WriteBlock(Msb, blockIdPasien,
                                                                      Util.ToArrayByte16(identitas)))
                                                    {
                                                        isPrinted = true;
                                                    }
                                                    else
                                                    {
                                                        MessageBox.Show("ID pasien gagal ditulis");
                                                    }
                                                }

                                                if (!string.IsNullOrEmpty(jenis_id))
                                                {
                                                    if (sp.WriteBlock(Msb, blockJenisId, Util.ToArrayByte16(jenis_id)))
                                                    {
                                                        isPrinted = true;
                                                    }
                                                    else
                                                    {
                                                        MessageBox.Show("Jenis Identitas pasien gagal ditulis");
                                                    }
                                                }

                                                if (!string.IsNullOrEmpty(golDarah))
                                                {
                                                    if (sp.WriteBlock(Msb, blockGolDarah,
                                                                      Util.ToArrayByte16(" " + golDarah)))
                                                    {
                                                    }
                                                    else
                                                    {
                                                        MessageBox.Show("Golongan Darah gagal ditulis");
                                                    }
                                                }

                                                if (!string.IsNullOrEmpty(norm))
                                                {
                                                    if (sp.WriteBlock(Msb, blockNoRekamMedis, Util.ToArrayByte16(norm)))
                                                    {
                                                        isPrinted = true;
                                                    }
                                                    else
                                                    {
                                                        MessageBox.Show("Nomor rekam medis gagal ditulis");
                                                    }
                                                }

                                                if (namaPasien.Length > 48)
                                                {
                                                    namaPasien = namaPasien.Substring(0, 47);
                                                }

                                                if (!string.IsNullOrEmpty(namaPasien))
                                                {
                                                    if (sp.WriteBlockRange(Msb, blockNamaFrom, blockNamaTo,
                                                                           Util.ToArrayByte48(namaPasien)))
                                                    {
                                                        isPrinted = true;
                                                    }
                                                    else
                                                    {
                                                        MessageBox.Show("Nama pasien gagal ditulis");
                                                    }
                                                }

                                                if (!string.IsNullOrEmpty(tglLahir))
                                                {
                                                    if (sp.WriteBlock(Msb, blockTglLahir, Util.ToArrayByte16(tglLahir)))
                                                    {
                                                        isPrinted = true;
                                                    }
                                                    else
                                                    {
                                                        MessageBox.Show("Tanggal lahir pasien gagal ditulis");
                                                    }
                                                }

                                                if (!string.IsNullOrEmpty(jenisKelamin))
                                                {
                                                    if (sp.WriteBlock(Msb, blockJenisKelamin,
                                                                      Util.ToArrayByte16(jenisKelamin)))
                                                    {
                                                        isPrinted = true;
                                                    }
                                                    else
                                                    {
                                                        MessageBox.Show("Jenis kelamin pasien gagal ditulis");
                                                    }
                                                }

                                                if (!string.IsNullOrEmpty(noTelp))
                                                {
                                                    if (sp.WriteBlock(Msb, blockNoTelp, Util.ToArrayByte16(noTelp)))
                                                    {
                                                        isPrinted = true;
                                                    }
                                                    else
                                                    {
                                                        MessageBox.Show("Nomor telepon pasien gagal ditulis");
                                                    }
                                                }

                                                if (alamat.Length > 64)
                                                {
                                                    alamat = alamat.Substring(0, 63);
                                                }

                                                if (!string.IsNullOrEmpty(alamat))
                                                {
                                                    if (sp.WriteBlockRange(Msb, blockAlamatForm, blockAlamatTo,
                                                                           Util.ToArrayByte64(alamat)))
                                                    {
                                                        isPrinted = true;
                                                    }
                                                    else
                                                    {
                                                        MessageBox.Show("Alamat pasien gagal ditulis");
                                                    }
                                                }

                                                isPrinted = true;
                                                if (isPrinted)
                                                {
                                                    break;
                                                }
                                            }
                                            catch (Exception)
                                            {
                                                var ans = MessageBox.Show(
                                                    "Penulisan kartu gagal, pastikan kartu sudah berada pada jangkauan reader.\nApakah anda ingin menulis kartu lain kali?",
                                                    "Error",
                                                    MessageBoxButton.YesNo, MessageBoxImage.Error);

                                                if (ans == MessageBoxResult.Yes)
                                                {
                                                    break;
                                                }

                                                sp.isoReaderInit();
                                            }
                                        }

                                        MessageBox.Show(
                                            "Pasien berhasil didaftarkan.\nKartu pasien berhasil ditulis.\nNomor Antri: " +
                                            no_urut + "", "Informasi", MessageBoxButton.OK,
                                            MessageBoxImage.Information);
                                        DataContext = _mDaftarBaru;
                                        cbPoliklinik.SelectedIndex   = 0;
                                        cbGolDarah.SelectedIndex     = 0;
                                        cbJenisKelamin.SelectedIndex = 0;
                                        cbPoliklinik.SelectedIndex   = 0;

                                        var pd = new PrintDocument();
                                        var ps = new PaperSize("", 300, 540);

                                        pd.PrintPage      += Pd_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();

                                        try
                                        {
                                            //sck.Send(Encoding.ASCII.GetBytes("Update"));
                                            //sck2.Send(Encoding.ASCII.GetBytes("Update"));
                                            clientPoli.WriteLine("Update");
                                        }
                                        catch
                                        {
                                        }
                                    }
                                    else
                                    {
                                        MessageBox.Show("Pasien berhasil didaftarkan.\nNomor Antri: " + no_urut,
                                                        "Informasi", MessageBoxButton.OK, MessageBoxImage.Information);
                                        DataContext                  = _mDaftarBaru;
                                        dtTanggalLahir.Text          = string.Empty;
                                        cbGolDarah.SelectedIndex     = 0;
                                        cbJenisKelamin.SelectedIndex = 0;
                                        cbPoliklinik.SelectedIndex   = 0;

                                        try
                                        {
                                            //sck.Send(Encoding.ASCII.GetBytes("Update"));
                                            //sck2.Send(Encoding.ASCII.GetBytes("Update"));
                                            clientPoli.WriteLine("Update");
                                        }
                                        catch
                                        {
                                        }

                                        var pd = new PrintDocument();
                                        var ps = new PaperSize("", 300, 540);

                                        pd.PrintPage      += Pd_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();
                                    }
                                }
                                else
                                {
                                    MessageBox.Show("Data berhasil didaftarkan.", "Informasi", MessageBoxButton.OK,
                                                    MessageBoxImage.Information);

                                    try
                                    {
                                        //sck.Send(Encoding.ASCII.GetBytes("Update"));
                                        clientPoli.WriteLine("Update");
                                    }
                                    catch
                                    {
                                    }

                                    var pd = new PrintDocument();
                                    var ps = new PaperSize("", 300, 540);

                                    pd.PrintPage      += Pd_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();
                                }
                            }
                            else
                            {
                                MessageBox.Show("Data pasien gagal didaftartkan.", "Error", MessageBoxButton.OK,
                                                MessageBoxImage.Error);
                            }
                        }
                        else
                        {
                            MessageBox.Show("No rekam medis sudah terdaftar.", "Informasi", MessageBoxButton.OK,
                                            MessageBoxImage.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show("No indentitas sudah terdaftar.", "Informasi", MessageBoxButton.OK,
                                        MessageBoxImage.Error);
                    }
                }
                else
                {
                    MessageBox.Show("Harap periksa kembali data yang ingin di inputkan, pastikan semua sudah diisi.",
                                    "Perhatian", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
            else
            {
                MessageBox.Show("Harap periksa kembali data yang ingin di inputkan, pastikan semua sudah diisi.",
                                "Perhatian", MessageBoxButton.OK, MessageBoxImage.Warning);
            }

            e.Handled = true;
        }
Esempio n. 31
0
        private bool executePrintJob(JobFile job)
        {
            string strFile = Path.Combine(Properties.Settings.Default.LabFilesPath, job.LabelDocument);

            if (!System.IO.File.Exists(strFile))
            {
                Log(".Lab file: " + strFile + " not found: ", EnumLogType.Error);
                return(false);
            }

            var lbl = new LabelManager2.Application();

            lbl.Documents.Open(strFile, false);

            if (lbl.ActiveDocument == null)
            {
                Log("Could not get active document from Labfile ( CodeSoft Version? )", EnumLogType.Error);
                return(false);
            }

            var doc = lbl.ActiveDocument;
            //doc.Printer.SwitchTo(targetPrinterName, targetPrinterPort);

            //Get all the name of the printer Strings
            var allPrinterVars = lbl.PrinterSystem().Printers(enumKindOfPrinters.lppxAllPrinters);
            //To obtain the printer name printer can be fixed directly to the name value //
            string        printName = allPrinterVars.Item(2);
            PrintDocument prtdoc    = new PrintDocument();

            //use default system printer
            //string strDefaultPrinter = prtdoc.PrinterSettings.PrinterName;
            string usedprinter       = "";
            string strDefaultPrinter = Properties.Settings.Default.PrinterName;

            if (job.UseDefaultPrinter == false)
            {
                doc.Printer.SwitchTo(job.PrinterName);
                usedprinter = job.PrinterName;
            }
            else
            {
                usedprinter = strDefaultPrinter;
            }


            ////Gets the default printer name
            //bool foundPrinter = false;
            //for (int j = 0; j < allPrinterVars.Count; j++)
            //{
            //    string[] arryString = allPrinterVars.Item(j).Split(',');
            //    if (!string.IsNullOrEmpty(job.PrinterName))
            //    {
            //        if (arryString[0] == job.PrinterName)
            //        {
            //            foundPrinter = true;
            //            doc.Printer.SwitchTo(job.PrinterName, arryString[1], true);
            //            usedprinter = job.PrinterName;
            //            break;
            //        }
            //    }
            //    if (arryString[0] == strDefaultPrinter)
            //    {
            //        foundPrinter = true;
            //        doc.Printer.SwitchTo(strDefaultPrinter, arryString[1], true);
            //        usedprinter = strDefaultPrinter;
            //        break;
            //    }

            //}


            var ci = new CultureInfo("en-US");

            Log("start processing document", EnumLogType.Debug);
            foreach (var vitem in job.Variables)
            {
                string beginswith = vitem.Name.Substring(0, vitem.Name.Length - 1);
                //when % is in variable name, overwrite all matching vars
                if (vitem.Name.EndsWith("%"))
                {
                    var varcnt = doc.Variables.Count;
                    for (int i = 1; i <= varcnt; i++)
                    {
                        var vx = doc.Variables.Item(i);
                        if (vx != null)
                        {
                            if (vx.Name.StartsWith(beginswith, true, ci))
                            {
                                vx.Value = vitem.Value;
                            }
                        }
                    }
                }
                else
                {
                    //try to find exact value
                    var varInDoc = doc.Variables.Item(vitem.Name);
                    if (varInDoc != null)
                    {
                        if (string.IsNullOrEmpty(vitem.Value) || vitem.Printable == false)
                        {
                            doc.Variables.Remove(vitem.Name);
                        }
                        else
                        {
                            doc.Variables.Item(vitem.Name).Value = vitem.Value;
                        }
                    }
                }


                //look for images
                if (vitem.Name.EndsWith("%"))
                {
                    var varcnt = doc.DocObjects.Images.Count;
                    for (int i = 1; i <= varcnt; i++)
                    {
                        var aimgInDoc = doc.DocObjects.Images.Item(i);
                        if (aimgInDoc != null)
                        {
                            if (aimgInDoc.Name.StartsWith(beginswith, true, ci))
                            {
                                if (vitem.Printable)
                                {
                                    aimgInDoc.Printable = 1;
                                }
                                else
                                {
                                    aimgInDoc.Printable = 0;
                                }
                            }
                        }
                    }
                }
                else
                {
                    var imgInDoc = doc.DocObjects.Images.Item(vitem.Name);
                    if (imgInDoc != null)
                    {
                        if (vitem.Printable)
                        {
                            imgInDoc.Printable = 1;
                        }
                        else
                        {
                            imgInDoc.Printable = 0;
                        }
                    }
                }

                //look for texts
                if (vitem.Name.EndsWith("%"))
                {
                    var varcnt = doc.DocObjects.Texts.Count;
                    for (int i = 1; i <= varcnt; i++)
                    {
                        var atextInDoc = doc.DocObjects.Texts.Item(i);
                        if (atextInDoc != null)
                        {
                            if (atextInDoc.Name.StartsWith(beginswith, true, ci))
                            {
                                if (vitem.Printable)
                                {
                                    atextInDoc.Printable = 1;
                                }
                                else
                                {
                                    atextInDoc.Printable = 0;
                                }
                            }
                        }
                    }
                }
                else
                {
                    var textInDoc = doc.DocObjects.Texts.Item(vitem.Name);
                    if (textInDoc != null)
                    {
                        if (vitem.Printable)
                        {
                            textInDoc.Printable = 1;
                        }
                        else
                        {
                            textInDoc.Printable = 0;
                        }
                    }
                }

                //look for barcodes
                if (vitem.Name.EndsWith("%"))
                {
                    var varcnt = doc.DocObjects.Barcodes.Count;
                    for (int i = 1; i <= varcnt; i++)
                    {
                        var abarcodeInDoc = doc.DocObjects.Barcodes.Item(i);
                        if (abarcodeInDoc != null)
                        {
                            if (abarcodeInDoc.Name.StartsWith(beginswith, true, ci))
                            {
                                if (vitem.Printable)
                                {
                                    abarcodeInDoc.Printable = 1;
                                }
                                else
                                {
                                    abarcodeInDoc.Printable = 0;
                                }
                            }
                        }
                    }
                }
                else
                {
                    var barcodeInDoc = doc.DocObjects.Barcodes.Item(vitem.Name);
                    if (barcodeInDoc != null)
                    {
                        if (vitem.Printable)
                        {
                            barcodeInDoc.Printable = 1;
                        }
                        else
                        {
                            barcodeInDoc.Printable = 0;
                        }
                    }
                }

                Log("element not found in document " + vitem.Name, EnumLogType.Debug);
            }


            Log("end processing document", EnumLogType.Debug);

            //doc.PrintLabel(job.NrOfCopies);
            Log("printing " + job.NrOfCopies + " items on " + usedprinter, EnumLogType.Info);

            doc.HorzPrintOffset = job.MoveX;
            doc.VertPrintOffset = job.MoveY;
            doc.Rotate(job.Rotate);

            doc.PrintDocument(job.NrOfCopies);

            //  PrintDocument pd = new PrintDocument();
            //  pd.Print();

            lbl.Documents.CloseAll();

            lbl.Quit();
            //DataTable dt = codeInfo_DAL.GetData(this.cbb.SelectedValue.ToString());
            //if (dt != null && dt.Rows.Count > 0)
            //{
            //    foreach (DataRow dr in dt.Rows)
            //    { //codesoftLabel variables in the template
            //        doc.Variables.FormVariables.Item("var0").Value = dr["CodeID"].ToString();
            //        doc.Variables.FormVariables.Item("var1").Value =dr["Name"].ToString();
            //        // doc.PrintDocument(3);
            //        doc.PrintLabel(1, 1, 1, 1, 1, "");
            //    }
            //    //Continuous batch print labels. FormFeed()The parameters such as the output variable must be after the execution, output to the printer.
            //    doc.FormFeed();
            //    lbl.Quit();
            //}
            return(true);
        }
Esempio n. 32
0
 public PrintPreviewGraphics(PrintDocument document, PrintPageEventArgs e)
 {
     this.printPageEventArgs = e;
     this.printDocument      = document;
 }
 void PrintEnd(object sender, PrintEventArgs e)
 {
     this.Document = new PrintDocument();
 }
Esempio n. 34
0
        private void Imprimir_Recepcion(E_Recepcion_Encabezado encabezado_recepcion, E_Recepcion_Detalle detalle_recepcion)
        {
            DateTime fecha = DateTime.ParseExact(encabezado_recepcion.Fecha, "yyyy-MM-ddTHH:mm:ss",
                                                 System.Globalization.CultureInfo.InvariantCulture);

            N_Imprimir             imprimir   = new N_Imprimir();
            N_Recepcion_Encabezado encabezado = new N_Recepcion_Encabezado()
            {
                Chofer           = encabezado_recepcion.Chofer,
                Codigo_productor = encabezado_recepcion.Codigo_Productor,
                Correlativo      = encabezado_recepcion.Lote,
                Exportador       = encabezado_recepcion.Cliente,
                //    s Format Specifier      de-DE Culture                      2008-10-01T17:04:32

                Fecha         = fecha.ToShortDateString(),
                Guia_despacho = encabezado_recepcion.Guia,
                Hora          = encabezado_recepcion.Hora,
                Productor     = encabezado_recepcion.Productor,
                Especie       = encabezado_recepcion.Especie,
                Responsable   = encabezado_recepcion.Responsable,
                Tipo          = encabezado_recepcion.Tipo
            };
            N_Recepcion_Detalle detalle = new N_Recepcion_Detalle()
            {
                Cantidad             = detalle_recepcion.Cantidad_Bandejas,
                Comentario           = detalle_recepcion.Comentario,
                Descarga             = encabezado_recepcion.Descarga,
                Destino              = encabezado_recepcion.Destino,
                Folio                = detalle_recepcion.Folio,
                Hora_recepcion       = detalle_recepcion.Hora,
                Kilos_brutos         = detalle_recepcion.Kilos_Brutos,
                Tara                 = detalle_recepcion.Tara,
                Kilos_netos          = detalle_recepcion.Kilos_Netos,
                Numero_lote          = encabezado_recepcion.Lote,
                Peso_pallet          = detalle_recepcion.Peso_Pallet,
                Peso_promedio        = detalle_recepcion.Peso_Promedio,
                Peso_rejillas        = detalle_recepcion.Peso_Bandeja,
                Responsable          = encabezado_recepcion.Responsable,
                Sub_lote             = detalle_recepcion.Sublote,
                Temperatura          = encabezado_recepcion.Temperatura,
                Tipo_rejilla_bandeja = detalle_recepcion.Bandeja,
                Posicion_Pallet      = detalle_recepcion.Item
            };
            N_Coordenadas_Impresion coordenadas = new N_Coordenadas_Impresion()
            {
                PosicionX = "-3",
                PosicionY = "0"
            };

            imprimir.Detalle               = detalle;
            imprimir.Encabezado            = encabezado;
            imprimir.Fuente                = new Font("Verdana", 10);
            imprimir.Coordenadas_impresion = coordenadas;
            imprimir.Numero                = "0"; // numero_actual.ToString();
            imprimir.Limite                = encabezado_recepcion.Cantidad_Pallets;
            PrintDocument pd = new PrintDocument();

            pd.PrintPage += new PrintPageEventHandler(imprimir.PrintTextFileHandlerRecepcion);
            pd.DefaultPageSettings.PrinterSettings.PrinterName = N_Impresora.Nombre;
            if (pd.PrinterSettings.IsValid)
            {
                pd.Print();
            }
            else
            {
                MessageBox.Show("Impresora " + N_Impresora.Nombre + " no esta instalada");
                return;
            }
            //para utilizar con printdialog
            //printDialog1.Document = pd;
            //Llamar al printDialog
            //if (printDialog1.ShowDialog() == DialogResult.OK) pd.Print();
        }
Esempio n. 35
0
        // Print out a document to a file which we will pass to ghostscript
        protected static void PrintToGhostscript(string printer, string outputFilename, PrintDocument printFunc)
        {
            String postscriptFilePath = "";
            String postscriptFile     = "";

            try
            {
                // Create a temporary location to output to
                postscriptFilePath = Path.GetTempFileName();
                File.Delete(postscriptFilePath);
                Directory.CreateDirectory(postscriptFilePath);
                postscriptFile = Path.Combine(postscriptFilePath, Guid.NewGuid() + ".ps");

                // Set up the printer
                PrintDialog printDialog = new PrintDialog
                {
                    AllowPrintToFile = true,
                    PrintToFile      = true
                };
                System.Drawing.Printing.PrinterSettings printerSettings = printDialog.PrinterSettings;
                printerSettings.PrintToFile   = true;
                printerSettings.PrinterName   = printer;
                printerSettings.PrintFileName = postscriptFile;

                // Call the appropriate printer function (changes based on the office application)
                printFunc(postscriptFile, printerSettings.PrinterName);
                ReleaseCOMObject(printerSettings);
                ReleaseCOMObject(printDialog);

                // Call ghostscript
                GhostscriptProcessor gsproc = new GhostscriptProcessor();
                List <string>        gsArgs = new List <string>
                {
                    "gs",
                    "-dBATCH",
                    "-dNOPAUSE",
                    "-dQUIET",
                    "-dSAFER",
                    "-dNOPROMPT",
                    "-sDEVICE=pdfwrite",
                    String.Format("-sOutputFile=\"{0}\"", string.Join(@"\\", outputFilename.Split(new string[] { @"\" }, StringSplitOptions.None))),
                    @"-f",
                    postscriptFile
                };
                gsproc.Process(gsArgs.ToArray());
            }
            finally {
                // Clean up the temporary files
                if (!String.IsNullOrWhiteSpace(postscriptFilePath) && Directory.Exists(postscriptFilePath))
                {
                    if (!String.IsNullOrWhiteSpace(postscriptFile) && File.Exists(postscriptFile))
                    {
                        // Make sure ghostscript is not holding onto the postscript file
                        for (var i = 0; i < 60; i++)
                        {
                            try
                            {
                                File.Delete(postscriptFile);
                                break;
                            }
                            catch (IOException)
                            {
                                Thread.Sleep(500);
                            }
                        }
                    }
                    Directory.Delete(postscriptFilePath);
                }
            }
        }
 public override void OnEndPage(PrintDocument document, PrintPageEventArgs e)
 {
 }
Esempio n. 37
0
        public bool OnPrint(object args)
        {
            CheckDisposed();

            if (m_printLayout == null || Clerk.CurrentObject == null)
            {
                return(false);
            }
            // Don't bother; this edit view does not specify a print layout, or there's nothing to print.

            var    area = m_mediator.PropertyTable.GetStringProperty("areaChoice", null);
            string toolId;

            switch (area)
            {
            case "notebook":
                toolId = "notebookDocument";
                break;

            case "lexicon":
                toolId = "lexiconDictionary";
                break;

            default:
                return(false);
            }
            var docViewConfig = FindToolInXMLConfig(toolId);

            if (docViewConfig == null)
            {
                return(false);
            }
            var innerControlNode = GetToolInnerControlNodeWithRightLayout(docViewConfig);

            if (innerControlNode == null)
            {
                return(false);
            }
            using (var docView = CreateDocView(innerControlNode))
            {
                if (docView == null)
                {
                    return(false);
                }

                using (var pd = new PrintDocument())
                    using (var dlg = new PrintDialog())
                    {
                        dlg.Document                 = pd;
                        dlg.AllowSomePages           = true;
                        dlg.AllowSelection           = false;
                        dlg.PrinterSettings.FromPage = 1;
                        dlg.PrinterSettings.ToPage   = 1;
                        if (dlg.ShowDialog() == DialogResult.OK)
                        {
                            // REVIEW: .NET does not appear to handle the collation setting correctly
                            // so for now, we do not support non-collated printing.  Forcing the setting
                            // seems to work fine.
                            dlg.Document.PrinterSettings.Collate = true;
                            docView.PrintFromDetail(pd, Clerk.CurrentObject.Hvo);
                        }
                    }
                return(true);
            }
        }
Esempio n. 38
0
        public static void PrintReceiptForTransaction(string line)
        {
            JArray  a      = (JArray.Parse(line));
            var     nombre = a.Children <JObject>().Properties().FirstOrDefault(z => z.Name == "printer");
            JObject obj2   = JObject.Parse(a.First.ToString());
            string  type   = (string)obj2["type"];

            if (type == "ticket")
            {
                string imagen = a.Children <JObject>().Properties().FirstOrDefault(z => z.Name == "zone").Value.ToString();
                Font   prueba = new Font("Arial", 20, FontStyle.Regular);
                System.Drawing.Image img;
                JArray b = JArray.Parse(a.Children <JObject>().Properties().FirstOrDefault(z => z.Name == "ticket").Value.ToString());
                if (!String.IsNullOrEmpty(imagen))
                {
                    img = DrawText(imagen, prueba, Color.White, Color.Black);
                }
                else
                {
                    img = null;
                }
                foreach (JObject o2 in b.Children <JObject>())
                {
                    PrintDocument recordDoc = new PrintDocument();
                    recordDoc.DocumentName    = "Customer Receipt";
                    recordDoc.PrintController = new StandardPrintController(); // hides status dialog popup
                    PrinterSettings ps = new PrinterSettings();
                    ps.PrinterName            = nombre.Value.ToString();
                    recordDoc.PrinterSettings = ps;
                    recordDoc.PrintPage      += (sender, args) => PrintReceiptPage(sender, args, o2, img, a);
                    recordDoc.Print();
                    recordDoc.Dispose();

                    bool coleta = (bool)(obj2["coleta"]);
                    if (coleta)
                    {
                        PrintDocument recordDoc2 = new PrintDocument();
                        recordDoc2.DocumentName    = "Customer Receipt";
                        recordDoc2.PrintController = new StandardPrintController(); // hides status dialog popup
                        PrinterSettings ps2 = new PrinterSettings();
                        ps2.PrinterName            = nombre.Value.ToString();
                        recordDoc2.PrinterSettings = ps2;
                        string serie = (string)(o2["serie"]);
                        string sc = (string)(o2["sc"]);
                        string station = (string)(obj2["station"]);
                        string price = (string)(obj2["price"]);
                        string iva = (string)(obj2["iva"]);
                        string total = (string)(obj2["total"]);
                        float  x = 10, y = 0, w = 255.59F, h = 0F;
                        recordDoc2.PrintPage += (sender, args) => Coleta(ref args, x, ref y, w, h, sc, serie, station, price, iva, total);
                        recordDoc2.Print();
                    }
                }
            }
            else if (type == "report")
            {
                JArray        header    = JArray.Parse(a.Children <JObject>().Properties().FirstOrDefault(z => z.Name == "header").Value.ToString());
                JArray        content   = JArray.Parse(a.Children <JObject>().Properties().FirstOrDefault(z => z.Name == "content").Value.ToString());
                string[]      h1        = header.ToObject <string[]>();
                string[]      c1        = content.ToObject <string[]>();
                PrintDocument recordDoc = new PrintDocument();
                recordDoc.DocumentName    = "Customer Receipt";
                recordDoc.PrintController = new StandardPrintController(); // hides status dialog popup
                PrinterSettings ps = new PrinterSettings();
                ps.PrinterName            = nombre.Value.ToString();
                recordDoc.PrinterSettings = ps;
                recordDoc.PrintPage      += (sender, args) => PrintReport(sender, args, h1, c1, a);
                recordDoc.Print();
                recordDoc.Dispose();
            }
            else if (type == "test")
            {
                float      x = 4, y = 0, w = 255.59F, h = 0F;
                Font       bold_16   = new Font("Arial", 16, FontStyle.Bold);
                SolidBrush drawBrush = new SolidBrush(Color.Black);
                Font       regular   = new Font("Arial", 8, FontStyle.Regular);

                StringFormat center = new StringFormat();
                center.Alignment = StringAlignment.Center;
                PrintDocument recordDoc = new PrintDocument();
                recordDoc.DocumentName    = "Customer Receipt";
                recordDoc.PrintController = new StandardPrintController(); // hides status dialog popup
                PrinterSettings ps = new PrinterSettings();
                ps.PrinterName            = nombre.Value.ToString();
                recordDoc.PrinterSettings = ps;
                recordDoc.PrintPage      += (sender, args) => imprimir(ref args, "prueba", bold_16, drawBrush, x, ref y, w, h, center);
                recordDoc.Print();
                recordDoc.Dispose();
            }
        }
Esempio n. 39
0
        /// <summary>
        /// This is the event handler for PrintDocument.GetPrintPreviewPage. It provides a specific print preview page,
        /// in the form of an UIElement, to an instance of PrintDocument. PrintDocument subsequently converts the UIElement
        /// into a page that the Windows print system can deal with.
        /// </summary>
        /// <param name="sender">PrintDocument</param>
        /// <param name="e">Arguments containing the preview requested page</param>
        protected virtual void GetPrintPreviewPage(object sender, GetPreviewPageEventArgs e)
        {
            PrintDocument printDoc = (PrintDocument)sender;

            printDoc.SetPreviewPage(e.PageNumber, printPreviewPages[e.PageNumber - 1]);
        }
Esempio n. 40
0
        private void tlvAnaliza_PrintPage(object sender, PrintPageEventArgs e)
        {
            #region -------------------------- Print variables definitions -----------------------
            PH.G = e.Graphics;
            PrintDocument Doc                 = (PrintDocument)sender;
            float         x                   = IsPreview ? UserSession.User.Settings.LeftMargin : UserSession.User.Settings.LeftMargin - e.PageSettings.PrintableArea.Left;
            float         y                   = IsPreview ? UserSession.User.Settings.TopMargin : UserSession.User.Settings.TopMargin - e.PageSettings.PrintableArea.Top;
            Font          TextFont            = UserSession.User.Settings.TextFont;
            Font          SubHeaderFont       = UserSession.User.Settings.SubHeaderFont;
            Font          HeaderFont          = UserSession.User.Settings.HeaderFont;
            float         LineHeight          = TextFont.GetHeight(e.Graphics);
            float         SubHeaderLineHeight = SubHeaderFont.GetHeight(e.Graphics);
            float         HeaderLineHeight    = HeaderFont.GetHeight(e.Graphics);
            int           PrintWidth          = e.MarginBounds.Width;
            int           PrintHeight         = e.MarginBounds.Bottom;
            #endregion

            PageNumber += 1;

            #region --------------------------- Document header and footer -----------------------
            PH.DrawHeader(x, y, PrintWidth);
            PH.DrawFooter(x, PrintHeight, PrintWidth);
            PH.DrawPageNumber("- " + PageNumber.ToString() + " -", x, PrintHeight, PrintWidth, PageNumberLocation.Footer);
            #endregion
            #region ------------------------------ Report header -----------------------------------
            if (PageNumber == 1)
            {
                y += LineHeight;
                PH.DrawText(ReportHeader[0], HeaderFont, x, y, PrintWidth, HeaderLineHeight, StringAlignment.Center, Brushes.Black, false);
                y += HeaderLineHeight * 2;
            }
            #endregion
            #region ------------------------------- Column Settings --------------------------
            List <TableCell> Kolumna = new List <TableCell>();
            foreach (OLVColumn Col in tlvStudent.Columns)
            {
                Kolumna.Add(new TableCell {
                    Name = Col.AspectName, Label = Col.Text, Size = Col.Width - 20
                });
            }
            int FirstColWidth = PrintWidth - Kolumna.Where(K => K.Name != "Label").Sum(K => K.Size);
            if (FirstColWidth > 0)
            {
                Kolumna.Where(K => K.Name == "Label").First().Size = FirstColWidth;
            }
            #endregion

            #region ------------------------------- Table header --------------------------------
            float MultiplyLine = 3;
            int   ColOffset    = 0;
            if (PageNumber == 1)
            {
                for (int i = 0; i < Kolumna.Count(); i++)
                {
                    PH.DrawText(Kolumna[i].Label, new Font(TextFont, FontStyle.Bold), x + ColOffset, y, Kolumna[i].Size, LineHeight * MultiplyLine, StringAlignment.Center, Brushes.Black);
                    ColOffset += Kolumna[i].Size;
                }
                y += LineHeight * MultiplyLine;
            }
            ColOffset = 0;
            for (int i = 0; i < Kolumna.Count(); i++)
            {
                PH.DrawText((i + 1).ToString(), new Font(TextFont, FontStyle.Bold | FontStyle.Italic), x + ColOffset, y, Kolumna[i].Size, LineHeight, StringAlignment.Center, Brushes.Black);
                ColOffset += Kolumna[i].Size;
            }
            y += LineHeight * 1.5F;
            #endregion

            #region ------------------------ Table body --------------------------------
            int  index     = 0;
            int  Indent    = 0;
            bool Shade     = false;
            Font PrintFont = null;
            var  ListItems = tlvStudent.FilteredObjects.Cast <ScoreBranch>();
            while (y + LineHeight * 2 < PrintHeight && Offset[0] < ListItems.Count())
            {
                var ListItem = ListItems.ToArray()[Offset[0]];
                y        += LineHeight * 0.5f;
                PrintFont = new Font(TextFont, FontStyle.Bold);
                switch (ListItem.Level)
                {
                case 0:
                    Indent       = 0;
                    MultiplyLine = 2;
                    Shade        = true;
                    index        = 0;
                    break;

                case 1:
                    Indent       = 20;
                    MultiplyLine = 2;
                    Shade        = false;
                    index        = 0;
                    break;

                case 2:
                    Indent       = 40;
                    MultiplyLine = 1;
                    Shade        = false;
                    PrintFont    = TextFont;
                    if (index > 0)
                    {
                        y -= LineHeight * 0.5f;
                    }
                    index++;
                    break;
                }
                PrintModelObjectData(ListItem, x, ref y, Kolumna, PrintFont, LineHeight * MultiplyLine, Indent, Shade);
                Offset[0]++;
            }
            if (Offset[0] < ListItems.Count())
            {
                PrintNextPage(Doc, e);
            }

            #endregion
        }
Esempio n. 41
0
        public static void PrintOrder(POSDataContext ctx, OrderKassa order, bool btw, bool isKitchen, bool bni = false)
        {
            var orderdetails = from a in ctx.OrderDetails where a.OrderID == order.OrderID select a;
            List <OrderDetail> orderDetails = new List <OrderDetail>(orderdetails.ToArray());

            float fontSize = Convert.ToSingle(ConfigurationManager.AppSettings["FontSize"]);

            Font          printFont = new Font("Arial", fontSize);
            PrintDocument pd        = new PrintDocument();

            pd.PrinterSettings.PrinterName = ConfigurationManager.AppSettings["PrinterName"];

            if (isKitchen)
            {
                pd.PrinterSettings.PrinterName = ConfigurationManager.AppSettings["PrinterNameKitchen"];
            }

            string tableNameHeader = order.TableSeat.TableName + ": " + order.Name;
            string dateHeader      = "\nTanggal : " + order.OrderDate.ToLongDateString();

            decimal grandTotal            = 0;
            string  strBillSubtotal       = "";
            string  strBillSubtotalAmount = "";
            string  strBillBTW            = "";
            string  strBillBTWAmount      = "";
            string  strBillDrink          = "";
            string  strBillDrinkAmount    = "";
            string  strBillBTWDrink       = "";
            string  strBillBTWDrinkAmount = "";
            string  strBillTotal          = "";
            string  strBillTotalAmount    = "";
            string  strBillFooter         = "Terima kasih dan sampai jumpa";
            string  strBillDiskon         = "";
            string  strBillDiskonAmount   = "";

            pd.PrintPage += (s, ev) =>
            {
                float linesPerPage = 0;
                //not using
                //float yPos = 0;
                //int count = 0;
                float  leftMargin    = 10;
                float  topMargin     = 10;
                string currentLine   = null;
                Pen    p             = new Pen(Color.White, 1);
                float  lineHeight    = printFont.GetHeight(ev.Graphics);
                int    intLineHeight = (int)lineHeight;

                // Calculate the number of lines per page.
                linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics);

                StringFormat sfHeader = new StringFormat();
                sfHeader.Alignment = StringAlignment.Center;

                StringFormat sf = new StringFormat();
                sf.Alignment = StringAlignment.Near;

                StringFormat sfFar = new StringFormat();
                sfFar.Alignment = StringAlignment.Far;

                // header
                Rectangle rectHeader  = new Rectangle((int)leftMargin, (int)topMargin, 260, 50);
                Rectangle rectHeader2 = new Rectangle((int)leftMargin, rectHeader.Height + 20, 260, 35);
                ev.Graphics.DrawString("Meat Compiler", printFont, Brushes.Black, rectHeader, sfHeader);
                ev.Graphics.DrawString("\nTel: 0817-6328-000", printFont, Brushes.Black, rectHeader, sfHeader);
                ev.Graphics.DrawString("\n\nwww.meatcompiler.id", printFont, Brushes.Black, rectHeader, sfHeader);
                ev.Graphics.DrawString(tableNameHeader, printFont, Brushes.Black, rectHeader2, sf);
                ev.Graphics.DrawString(dateHeader, printFont, Brushes.Black, rectHeader2, sf);
                ev.Graphics.DrawRectangle(p, rectHeader);
                ev.Graphics.DrawRectangle(p, rectHeader2);

                int topMarginBody1 = 100;

                ev.Graphics.DrawLine(Pens.Black, (int)leftMargin, topMarginBody1, (int)leftMargin + 260, topMarginBody1);

                decimal orderTotal      = 0;
                decimal orderTotalDrink = 0;

                int topMarginBody = topMarginBody1 + 10;

                foreach (OrderDetail orderDetail in orderDetails)
                {
                    Rectangle rectBodyLeft  = new Rectangle((int)leftMargin, topMarginBody, 200, intLineHeight);
                    Rectangle rectBodyright = new Rectangle(rectBodyLeft.Width + 5 - 40, topMarginBody, 100, intLineHeight);

                    string menuNameBill   = "";
                    string menuAmountBill = "";

                    if (orderDetail.CustomMenuPrice > 0)
                    {
                        orderTotal    += orderDetail.CustomMenuPrice * orderDetail.Quantity;
                        menuNameBill   = orderDetail.Quantity + "x " + orderDetail.CustomMenuName;
                        menuAmountBill = Helper.FormatPrice(orderDetail.CustomMenuPrice * orderDetail.Quantity);
                    }
                    else
                    {
                        orderTotal    += orderDetail.MenuCard.Price * orderDetail.Quantity;
                        menuNameBill   = orderDetail.Quantity + "x " + orderDetail.MenuCard.MenuName;
                        menuAmountBill = Helper.FormatPrice(orderDetail.MenuCard.Price * orderDetail.Quantity);
                    }

                    ev.Graphics.DrawString(menuNameBill, printFont, Brushes.Black, rectBodyLeft, sf);
                    ev.Graphics.DrawString(menuAmountBill, printFont, Brushes.Black, rectBodyright, sfFar);

                    ev.Graphics.DrawRectangle(p, rectBodyLeft);
                    ev.Graphics.DrawRectangle(p, rectBodyright);

                    topMarginBody = topMarginBody + intLineHeight + 5;
                }


                grandTotal         = orderTotalDrink + orderTotal;
                strBillTotal       = "Total ";
                strBillTotalAmount = Helper.FormatPrice(grandTotal);

                int topMarginFooter1     = topMarginBody + 15; // bodyHeight + 5;
                int topMarginFooter      = topMarginFooter1 + 15;
                int topMarginFooterFinal = topMarginFooter;

                ev.Graphics.DrawLine(Pens.Black, (int)leftMargin, topMarginFooter1, (int)leftMargin + 260, topMarginFooter1);

                POSDataContext db       = new POSDataContext();
                var            theOrder = db.OrderKassas.FirstOrDefault(x => x.OrderID == order.OrderID);
                if (theOrder.Discount > 0)
                {
                    strBillSubtotal       = "Subtotal: ";
                    strBillSubtotalAmount = Helper.FormatPrice(grandTotal);
                    int subTotalTopMargin = topMarginFooter + intLineHeight + 5;

                    Rectangle rectFooterSubtotal       = new Rectangle((int)leftMargin, subTotalTopMargin, 200, intLineHeight);
                    Rectangle rectFooterSubtotalAmount = new Rectangle(rectFooterSubtotal.Width + 5 - 40, topMarginFooter, 100, intLineHeight);

                    ev.Graphics.DrawString(strBillSubtotal, printFont, Brushes.Black, rectFooterSubtotal, sf);
                    ev.Graphics.DrawString(strBillSubtotalAmount, printFont, Brushes.Black, rectFooterSubtotalAmount, sfFar);

                    strBillDiskon       = "Diskon: ";
                    strBillDiskonAmount = (grandTotal * (order.Discount / 100)).ToString("N0");
                    int diskonTopMargin = subTotalTopMargin + intLineHeight + 5;

                    grandTotal         = grandTotal - (grandTotal * (order.Discount / 100));
                    strBillTotalAmount = Helper.FormatPrice(grandTotal);

                    Rectangle rectFooterDiskon       = new Rectangle((int)leftMargin, diskonTopMargin, 200, intLineHeight);
                    Rectangle rectFooterDiskonAmount = new Rectangle(rectFooterDiskon.Width + 5 - 40, diskonTopMargin, 100, intLineHeight);

                    ev.Graphics.DrawString(strBillDiskon, printFont, Brushes.Black, rectFooterDiskon, sf);
                    ev.Graphics.DrawString(strBillDiskonAmount, printFont, Brushes.Black, rectFooterDiskonAmount, sfFar);
                }

                if (bni)
                {
                    decimal cardChargeAmount = grandTotal * (decimal)(0.02);
                    decimal subTotal         = grandTotal;

                    strBillSubtotal       = "Subtotal: ";
                    strBillSubtotalAmount = Helper.FormatPrice(subTotal);

                    strBillBTW       = "Card Charge 2%: ";
                    strBillBTWAmount = Helper.FormatPrice(cardChargeAmount);

                    Rectangle rectFooterSubtotal       = new Rectangle((int)leftMargin, topMarginFooter, 200, intLineHeight);
                    Rectangle rectFooterSubtotalAmount = new Rectangle(rectFooterSubtotal.Width + 5 - 40, topMarginFooter, 100, intLineHeight);
                    int       btwTopMargin             = topMarginFooter + intLineHeight + 5;

                    Rectangle rectFooterBTW       = new Rectangle((int)leftMargin, btwTopMargin, 200, intLineHeight);
                    Rectangle rectFooterBTWAmount = new Rectangle(rectFooterBTW.Width + 5 - 40, btwTopMargin, 100, intLineHeight);

                    ev.Graphics.DrawString(strBillSubtotal, printFont, Brushes.Black, rectFooterSubtotal, sf);
                    ev.Graphics.DrawString(strBillSubtotalAmount, printFont, Brushes.Black, rectFooterSubtotalAmount, sfFar);
                    ev.Graphics.DrawString(strBillBTW, printFont, Brushes.Black, rectFooterBTW, sf);
                    ev.Graphics.DrawString(strBillBTWAmount, printFont, Brushes.Black, rectFooterBTWAmount, sfFar);

                    ev.Graphics.DrawRectangle(p, rectFooterSubtotal);
                    ev.Graphics.DrawRectangle(p, rectFooterSubtotalAmount);
                    ev.Graphics.DrawRectangle(p, rectFooterBTW);
                    ev.Graphics.DrawRectangle(p, rectFooterBTWAmount);

                    topMarginFooterFinal = btwTopMargin + intLineHeight + 5;

                    grandTotal         = subTotal + cardChargeAmount;
                    strBillTotalAmount = Helper.FormatPrice(grandTotal);
                }

                if (btw)
                {
                    decimal btwAmount = orderTotal * (decimal)((decimal)6 / (decimal)106);
                    decimal subTotal  = orderTotal - btwAmount;

                    strBillSubtotal       = "Subtotal: ";
                    strBillSubtotalAmount = Helper.FormatPrice(subTotal);

                    strBillBTW       = "BTW 6%: ";
                    strBillBTWAmount = Helper.FormatPrice(btwAmount);

                    Rectangle rectFooterSubtotal       = new Rectangle((int)leftMargin, topMarginFooter, 200, intLineHeight);
                    Rectangle rectFooterSubtotalAmount = new Rectangle(rectFooterSubtotal.Width + 5, topMarginFooter, 60, intLineHeight);
                    int       btwTopMargin             = topMarginFooter + intLineHeight + 5;

                    Rectangle rectFooterBTW       = new Rectangle((int)leftMargin, btwTopMargin, 200, intLineHeight);
                    Rectangle rectFooterBTWAmount = new Rectangle(rectFooterBTW.Width + 5, btwTopMargin, 60, intLineHeight);

                    ev.Graphics.DrawString(strBillSubtotal, printFont, Brushes.Black, rectFooterSubtotal, sf);
                    ev.Graphics.DrawString(strBillSubtotalAmount, printFont, Brushes.Black, rectFooterSubtotalAmount, sfFar);
                    ev.Graphics.DrawString(strBillBTW, printFont, Brushes.Black, rectFooterBTW, sf);
                    ev.Graphics.DrawString(strBillBTWAmount, printFont, Brushes.Black, rectFooterBTWAmount, sfFar);

                    ev.Graphics.DrawRectangle(p, rectFooterSubtotal);
                    ev.Graphics.DrawRectangle(p, rectFooterSubtotalAmount);
                    ev.Graphics.DrawRectangle(p, rectFooterBTW);
                    ev.Graphics.DrawRectangle(p, rectFooterBTWAmount);

                    topMarginFooterFinal = btwTopMargin + intLineHeight + 5;

                    if (orderTotalDrink > 0)
                    {
                        decimal btwAmountDrink = orderTotalDrink * (decimal)((decimal)19 / (decimal)119);
                        decimal subTotalDrink  = orderTotalDrink - btwAmountDrink;
                        strBillDrink          = "Alcoholic Drink: ";
                        strBillDrinkAmount    = Helper.FormatPrice(subTotalDrink);
                        strBillBTWDrink       = "BTW 19%: ";
                        strBillBTWDrinkAmount = Helper.FormatPrice(btwAmountDrink);

                        Rectangle rectFooterDrink       = new Rectangle((int)leftMargin, topMarginFooterFinal, 200, intLineHeight);
                        Rectangle rectFooterDrinkAmount = new Rectangle(rectFooterDrink.Width + 5, topMarginFooterFinal, 60, intLineHeight);

                        topMarginFooterFinal = topMarginFooterFinal + intLineHeight + 5;
                        Rectangle rectFooterBTWDrink       = new Rectangle((int)leftMargin, topMarginFooterFinal, 200, intLineHeight);
                        Rectangle rectFooterBTWDrinkAmount = new Rectangle(rectFooterBTW.Width + 5, topMarginFooterFinal, 60, intLineHeight);

                        ev.Graphics.DrawString(strBillDrink, printFont, Brushes.Black, rectFooterDrink, sf);
                        ev.Graphics.DrawString(strBillDrinkAmount, printFont, Brushes.Black, rectFooterDrinkAmount, sfFar);
                        ev.Graphics.DrawString(strBillBTWDrink, printFont, Brushes.Black, rectFooterBTWDrink, sf);
                        ev.Graphics.DrawString(strBillBTWDrinkAmount, printFont, Brushes.Black, rectFooterBTWDrinkAmount, sfFar);

                        ev.Graphics.DrawRectangle(p, rectFooterDrink);
                        ev.Graphics.DrawRectangle(p, rectFooterDrinkAmount);
                        ev.Graphics.DrawRectangle(p, rectFooterBTWDrink);
                        ev.Graphics.DrawRectangle(p, rectFooterBTWDrinkAmount);

                        topMarginFooterFinal = topMarginFooterFinal + intLineHeight + 5;
                    }
                }

                Rectangle rectFooterTotal       = new Rectangle((int)leftMargin, topMarginFooterFinal, 200, intLineHeight);
                Rectangle rectFooterTotalAmount = new Rectangle(rectFooterTotal.Width + 5 - 40, topMarginFooterFinal, 100, intLineHeight);
                Rectangle rectFooterClose       = new Rectangle((int)leftMargin, topMarginFooterFinal + intLineHeight + 30, 260, intLineHeight);

                ev.Graphics.DrawString(strBillTotal, printFont, Brushes.Black, rectFooterTotal, sf);
                ev.Graphics.DrawString(strBillTotalAmount, printFont, Brushes.Black, rectFooterTotalAmount, sfFar);
                ev.Graphics.DrawString(strBillFooter, printFont, Brushes.Black, rectFooterClose, sfHeader);

                ev.Graphics.DrawRectangle(p, rectFooterTotal);
                ev.Graphics.DrawRectangle(p, rectFooterTotalAmount);
                ev.Graphics.DrawRectangle(p, rectFooterClose);

                // If more lines exist, print another page.
                if (currentLine != null)
                {
                    ev.HasMorePages = true;
                    currentLine     = null;
                }
                else
                {
                    ev.HasMorePages = false;
                }
            };

            pd.EndPrint += (s, ev) =>
            {
            };

            pd.Print();
        }
Esempio n. 42
0
 /*
  *                     if (bingoTable.printCallList == true)
             {
                 printBingoCallList(pt, sz, bingoTable, Color.Black, ref graphicsObj, licenseInfo, "Oranges are pink", false);
                 //print the call list here - msk
             }
             bingoTable.RandSeed = 0;
  * */
 public BingoPrint()
 {
     printBingoDocument = new PrintDocument();
     //printCallList = new PrintDocument();
     printBingoPreviewDialog = new PrintPreviewDialog();
     printBingoDialog = new PrintDialog();
     pageBingoSetupDialog = new PageSetupDialog();
     PrintPageSettings = new PageSettings();
     printBingoDocument.PrintPage += new PrintPageEventHandler(this.PrintPage);
        // printCallList.PrintPage += new PrintPageEventHandler(this.PrintCallList);
        //printBingoDocument.QueryPageSettings += new QueryPageSettingsEventHandler(this.QueryPageSettings);
     numCardsToPrint = 0;
     return;
 }
Esempio n. 43
0
        private void frmPrintPreView_Load(object sender, EventArgs e)
        {

            int i;
            string defultPrinterName = "";

            try
            {
                var printDoc = new PrintDocument();
                for (i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
                {
                    // pkInstalledPrinters = PrinterSettings.InstalledPrinters[i];
                    //  comboInstalledPrinters.Items.Add(pkInstalledPrinters);
                    if (printDoc.PrinterSettings.IsDefaultPrinter)
                    {
                        defultPrinterName = printDoc.PrinterSettings.PrinterName;
                        break;
                    }
                }
            }
            catch
            { }
            
            try
            {

                var localPrintServer1 = new PrintServer();
            }
            catch
            {
                MessageBox.Show("invalid Framwork 3.5");
            }

            try
            {
                PrintQueue printQueue = null;



                var localPrintServer = new PrintServer();
                
                var FiltterPrinterType = new EnumeratedPrintQueueTypes[2];
                FiltterPrinterType[0] = EnumeratedPrintQueueTypes.Connections;
                FiltterPrinterType[1] = EnumeratedPrintQueueTypes.Local;
                

               
                
              

                // Retrieving collection of local printer on user machine
                var localPrinterCollection = new PrintQueueCollection();
                
                try
                {
                    localPrinterCollection  = localPrintServer.GetPrintQueues(FiltterPrinterType);
                }
                catch
                {
                    MessageBox.Show("vvv");
                }

                
                //printQueue = localPrintServer.;


                IEnumerator<PrintQueue> all = null;

                try
                {
                    all = localPrinterCollection.GetEnumerator();
                }
                catch
                {
                    MessageBox.Show("ss");
                }
                var AllPrinter = new Collection<PrintQueue>();
                PrintQueue defultPrinter = null; 


                while (all.MoveNext())
                {

                    try
                    {
                       // printQueue = all.Current;

                        //  if (printQueue.DefaultPrintTicket )
                        //  this.comboBox1.Items.Add(printQueue.FullName);

                        if (defultPrinterName == all.Current.Name)
                        {
                            defultPrinter = all.Current;
                        }

                        AllPrinter.Add(all.Current);
                    }
                    catch
                    {
                        MessageBox.Show("kkk");
                    }
                }

                //System.Printing.LocalPrintServer lPrint = new System.Printing.LocalPrintServer();
                //System.Printing.PrintQueueCollection pCol = lPrint.GetPrintQueues();

              



                try
                {
                    cmbPrinters.DataSource = AllPrinter;
                    cmbPrinters.DisplayMember = "FullName";

                    try
                    {
                        if (defultPrinter != null)
                        {
                            this.cmbPrinters.SelectedItem = defultPrinter;
                        }
                    }
                    catch
                    { }
                }
                catch
                {
                    MessageBox.Show("tttt");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            Image = CurrentViewImage;// AllImage[0];
            rbtnCurrentView.Checked = true;
           // 
            
            cmbPrinters.Enabled = true;
            cboxFitToPage.Checked = true;
            cboxCenter.Checked = true;




          

        }
Esempio n. 44
0
 public virtual void Print()
 {
     PrintDocument.Print();
 }
Esempio n. 45
0
        public static void Main (string[] args)
        {
		PrintDocument p = new PrintDocument ();
		p.PrintPage += new PrintPageEventHandler (PrintPageEvent);
                p.Print ();
        }
Esempio n. 46
0
        private void MenuItem_PrintPreview_Click(object sender, RoutedEventArgs e)
        {
            PrintDocument pd = new PrintDocument();
            pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);

            PrintDialog printdlg = new PrintDialog();

            PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();
        }
Esempio n. 47
0
 public MultiPrintDocument(PrintDocument[] documents)
 {
     _documents = documents;
 }
Esempio n. 48
0
		internal Printing(Scintilla scintilla) : base(scintilla) 
		{
			_printDocument = new PrintDocument(scintilla);
		}
	public virtual void OnEndPage(PrintDocument document, PrintPageEventArgs e) {}
Esempio n. 50
0
 // constructors
 public MultiPrintDocument(PrintDocument document1, PrintDocument document2)
 {
     _documents = new PrintDocument[] { document1, document2 };
 }
	public virtual System.Drawing.Graphics OnStartPage(PrintDocument document, PrintPageEventArgs e) {}
	// Methods
	public virtual void OnStartPrint(PrintDocument document, PrintEventArgs e) {}
    // The class constructor
    public DataGridViewPrinter( DataGridView inDataGridView
            , PrintDocument aPrintDocument
            , bool inCenterOnPage
            , int inPageHeight
            , int inPageWidth
            , int inTopMargin
            , int inBottomMargin
            , int inLeftMargin
            , int inRightMargin
        )
    {
        TheDataGridList = new DataGridView[1];
        TheDataGridList[0] = inDataGridView;
        InitializeComponent( aPrintDocument, inCenterOnPage, false, "", null, Color.Black, false );

        // Page margins
        PageHeight = inPageHeight;
        PageWidth = inPageWidth;
        TopMargin = inTopMargin;
        BottomMargin = inBottomMargin;
        LeftMargin = inLeftMargin;
        RightMargin = inRightMargin;
    }
Esempio n. 54
-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 );	}	
    }
Esempio n. 56
-1
 protected override void OnClick(EventArgs ea)
 {
     PrintDocument prndoc = new PrintDocument();
     prndoc.DocumentName = Text;
     prndoc.PrintPage += new PrintPageEventHandler(PrintDocumentOnPrintPage);
     prndoc.Print();
 }
Esempio n. 57
-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();
        }
Esempio n. 58
-1
 /// <summary>
 /// Creates a new print document
 /// </summary> 
 public static PrintDocument CreatePrintDocument()
 {
     PrintPageNumber = 0;
     PrintPageLastChar = 0;
     PrintDocument printDocument = new PrintDocument();
     printDocument.DocumentName = Globals.CurrentDocument.Text;
     printDocument.PrintPage += new PrintPageEventHandler(OnPrintDocumentPrintPage);
     return printDocument;
 }
 // The class constructor
 public DataGridViewPrinter(DataGridView dataGridView, PrintDocument printDocument, string headerText, bool printPageNumbers)
 {
     _dataGridView = dataGridView;
     _printDocument = printDocument;
     _headerText = headerText;
     _cellHeight = _bodyFont.Height + 5;
     _pageNumber = 0;
     _currentRow = 0;
     _printPageNumbers = printPageNumbers;
 }
Esempio n. 60
-1
 // use reflection to call protected methods of child documents
 private void CallMethod(PrintDocument document, string methodName, object args)
 {
     typeof(PrintDocument).InvokeMember(methodName,
       BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic,
       null, document, new object[] { args });
 }