Dalam mengembangkan aplikasi menggunakan C#, mungkin kita menginginkan cetak langsung ke printer tanpa melalui printer dialog. Pada tutorial kali ini kita akan membuat aplikasi yang langsung mencetak ke printer default dari komputer kita sehingga tidak perlu membuka printer dialog.

Artikel ini berdasarkan informasi yang ada di https://msdn.microsoft.com/en-us/library/system.drawing.printing.printdocument.print(v=vs.110).aspx

Langkah-langkah pembuatan aplikasi mencetak langsung pada C# adalah

  1. Silahkan membuat project baru dengan tipe ‘Windows Forms Application’ 
  2. Pola source code seperti berikut ini:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.IO;
    using System.Drawing;
    using System.Drawing.Printing;
    namespace ContohCetak
    {
         public class PrintingExample
        {
             private Font printFont;
             private StreamReader streamToPrint;
             static string filePath;

             public PrintingExample()
            {
                 Printing();
            }

            // The PrintPage event is raised for each page to be printed.
           private void pd_PrintPage(object sender, PrintPageEventArgs ev)
           {
               float linesPerPage = 0;
               float yPos = 0;
               int count = 0;
               float leftMargin = ev.MarginBounds.Left;
               float topMargin = ev.MarginBounds.Top;
               String line = null;

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

              // Iterate over the file, printing each line.
              while (count < linesPerPage &&
                   ((line = streamToPrint.ReadLine()) != null))
              {
                   yPos = topMargin + (count * printFont.GetHeight(ev.Graphics));
                   ev.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, new StringFormat());
                   count++;
              }

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

           // Print the file.
              public void Printing()
             {
                try
                {
                    streamToPrint = new StreamReader(filePath);
                    try
                   {
                        printFont = new Font(“Arial”, 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);
                 }
             }

             // This is the main entry point for the application.
             public static void Main(string[] args)
             {
                 string sampleName = Environment.GetCommandLineArgs()[0];
                 if (args.Length != 1)
                 {
                       Console.WriteLine(“Usage: ” + sampleName + ” <file path>”);
                       return;
                 }
                 filePath = args[0];
                 new PrintingExample();
             }
        }

         static class Program
         {
              /// <summary>
              /// The main entry point for the application.
              /// </summary>
              [STAThread]
               static void Main2()
              {
               Application.EnableVisualStyles();
               Application.SetCompatibleTextRenderingDefault(false);
               Application.Run(new Form1());
              }
         }
    }

  3. Silahkan Rebuild Program

  4. Jalankan dengan argumen pertama teks file misal seperti berikut ini:

    D:\vs2012\ContohCetak\ContohCetak\bin\Debug>ContohCetak.exe ContohCetak.exe.config

    D:\vs2012\ContohCetak\ContohCetak\bin\Debug>

  5. Maka aplikasi kita akan mencetak ke default printer kita

Kunjungi www.proweb.co.id untuk menambah wawasan anda.

 

Mencetak langsung ke printer pada C#
× Ada yang dapat saya bantu ? Available on SundayMondayTuesdayWednesdayThursdayFridaySaturday