Click here to Skip to main content
Click here to Skip to main content

Line Printer Class in C#

By , 26 Sep 2008
 

Introduction

This class simplifies the job of printing text on line printers, in C#. I had an application that needed to print on one of such printers, so I ended up writing this helper class. Basically, it's a wrapper for the spooler API (winspool.drv); the text to be printed is sent in "RAW" mode to the spooler so that no graphics printing is involved.

Using the code

The use of the class is pretty easy. First, the desired printing device is selected by either writing the PrinterName property or by calling the ChoosePrinter() method:

LPrinter MyPrinter = new LPrinter(); // creates the printer object
MyPrinter.ChoosePrinter();// let user choose the printer device

// alternatively:
MyPrinter.PrinterName = "Epson FX-80";
// uses a specific named printer

The actual printing is done like this:

MyPrinter.Open("Document Title Here"); // opens and tells the spooler the document title
MyPrinter.Print("Some text....\r\n");  // actual printing (CR+LFs are neeeded)
MyPrinter.Print("\x0C");               // sends a form feed (ejects the paper)
MyPrinter.Close();                     // Close the spooler

All methods Open(), Print(), Close(), and ChoosePrinter() return a boolean, in case you want to check if the operation was successful.

Some basic text effects can be achieved by sending control codes to the printer, according to the following table:

Code Description
14 enlarged characters on
20 enlarged characters off
15 compressed characters on
18 compressed characters off
ESC + "E" bold characters on
ESC + "F" bold characters off
12 FF (form feed)

For more codes, check the printer's manual.

Points of interest

Unfortunately, there is no easy way to tell if an installed printer is a line printer or a graphical one (laser or inkjet), so I was not able to filter the print dialog of ChoosePrinter(), making it display only line printers. This means that the user has to choose the right printer.

History

  • 29-Sep-2008: first (and possibly only one) version.

License

This article, along with any associated source code and files, is licensed under A Public Domain dedication

About the Author

Antonino Porcino
Software Developer
Italy Italy
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionFor Virtual Printer like Bullzip PDF PrintermemberMember 901324221 May '13 - 11:28 
Do you know why didn't work or Bullzip PDF printer?
 
An error occurred.
 
Error 1007: An error occured while running Ghostscript
 
Error: /undefined in This
Operand stack:
 
Execution stack:
   %interp_exit   .runexec2   --nostringval--   --nostringval--   --nostringval--   2   %stopped_push   --nostringval--   --nostringval--   --nostringval--   false   1   %stopped_push   1926   1   3   %oparray_pop   1925   1   3   %oparray_pop   1909   1   3   %oparray_pop   1803   1   3   %oparray_pop   --nostringval--   %errorexec_pop   .runexec2   --nostringval--   --nostringval--   --nostringval--   2   %stopped_push   --nostringval--
Dictionary stack:
   --dict:1187/1684(ro)(G)--   --dict:0/20(G)--   --dict:77/200(L)--
Current allocation mode is local
Current file position is 5
 

Source: GUI
 
Internal hint: Run converter to create PDF file

AnswerRe: For Virtual Printer like Bullzip PDF PrintermemberAntonino Porcino21 May '13 - 21:01 
A Virtual PDF printer expects the data to arrive in a certain protocol (e.g. postscript, PCL, or else), while the Line Printer class sends crude raw bytes to the printer's port (which is just what's is needed to work with a line printer).
 
So the error I think is due to printer driver trying to interpret the raw bytes.
 
You should look for a PDF printer that supports old epson or ibm-proprinter emulation, but I doubt there is one. The closest thing you can do is to print to a text (.txt) file.
GeneralRe: For Virtual Printer like Bullzip PDF PrintermemberMember 901324222 May '13 - 6:44 
Thanks
QuestionArabic Fonts doesn't work correctlymemberM. Mokhtar28 Apr '13 - 7:47 
When printing Arabic fonts it doesn't work correctly?
AnswerRe: Arabic Fonts doesn't work correctlymemberAntonino Porcino28 Apr '13 - 8:49 
to my knowledge, Line Printers do not support Arabic Fonts unless you switch to graphic mode (opposed to text mode).
 
The class presented in the article was made for text mode only, but of course you can always send commands to print in graphic mode (but in this case you have to handle that by yourself--check the other answers, we have discussed about that).
GeneralRe: Arabic Fonts doesn't work correctlymemberM. Mokhtar28 Apr '13 - 8:57 
but my printer support a lot of fonts
how can i change the font of printing?
GeneralRe: Arabic Fonts doesn't work correctlymemberAntonino Porcino28 Apr '13 - 21:05 
if your printer supports Arabic fonts, there should be an "escape code" for selecting them. Look in the printer's user guide (usually in the appendix). Once you find the code you can send it with LPrinter.Print().
 
But make sure they are true "printer fonts" and not just text transformed into graphic via software. Printer fonts are fixed-width and are stored internally in the printer's ROMs.
GeneralRe: Arabic Fonts doesn't work correctlymemberM. Mokhtar3 May '13 - 10:57 
i am using Samsung bixolon SRP-350
and in appendix to send command u shoud select font "Control"
so i can't send any command to it without using this font
GeneralRe: Arabic Fonts doesn't work correctlymemberM. Mokhtar3 May '13 - 10:54 
with wordpad arabic font appears fine on the printer
but when using code it prints worng chars
GeneralRe: Arabic Fonts doesn't work correctlymemberAntonino Porcino3 May '13 - 21:57 
I've looked at the SRP350 specifications and it seems to me it doesn't support Arabic font directly. I guess when you print in wordpard the windows printer driver translates you text into graphic first and then sends it to the printer.
 
So you can't use the class provided in this article with your printer because it was meant to print text only and not graphics. Unless of course you hack it to make it print bitmapped images, which can be done with some effort by using the printer codes (look here for a good reference).
 
Look for command "GS v" (page 8-21) that lets you print raster bitmap images. So you draw your Arabic text on a bitmap surface and then turn pixels into bytes for the "GS v" command. It can be done but it's a tedious work because you have to work at the bit level.
GeneralThanks for postingmemberPetar Srdanovic15 Mar '13 - 0:23 
You code was very helpful for me. Thanks for posting it.
QuestionBill Printing IssuememberKamran Ismail3 Mar '13 - 19:06 
I am printing bill with thermal printer. But it only print with Raw Data. I am facing two problems in below code.
if (dataGrid_product_list.RowCount > 1)
            {
 
                MyPrinter.PrinterName = "Epson LX-300+";
                    if (!MyPrinter.Open("Test Page")) return;
                    MyPrinter.Print("             ZIA BOOK SELLER\r\n");
                    MyPrinter.Print("             D-Ground FSD\r\n");
                    //MessageBox.Show("OK");
                    MyPrinter.Print("      Ph. 041-8732670, 041-8540217\r\n");
                    MyPrinter.Print("Date: " + CurrentDate + "\r\n");
                    MyPrinter.Print("Invoice No.:" + MAX + "\r\n");
                    MyPrinter.Print("----------------------------------------\r\n");
                    MyPrinter.Print(" Sr. | Product Name    | Price  | Qty |\r\n");
                    MyPrinter.Print("----------------------------------------\r\n");
                    double sum = 0;
                    string name = "";
                    double sr = 1;
                    double price = 0;
                    double amount = 0;
                    double qty = 0;
                    for (int i = 0; i < dataGrid_product_list.Rows.Count; ++i)
                    {
                        sr += 1;
                       
 
                        name = Convert.ToString(dataGrid_product_list.Rows[i].Cells[1].Value);
                        price = Convert.ToDouble(dataGrid_product_list.Rows[i].Cells[2].Value);
                        qty = Convert.ToDouble(dataGrid_product_list.Rows[i].Cells[3].Value);
                        amount = Convert.ToDouble(dataGrid_product_list.Rows[i].Cells[4].Value);
                        MyPrinter.Print(" " + sr.ToString() + "  " + Name.ToString() + " " + price.ToString() + " " + qty.ToString() + " " + amount.ToString() + "\r\n");
 
                        sum += Convert.ToDouble(dataGrid_product_list.Rows[i].Cells[4].Value);
 
                    }
                    MyPrinter.Print("----------------------------------------\r\n");
                    MyPrinter.Print("Total:                         " + sum.ToString() + "\r\n");
                    MyPrinter.Print("----------------------------------------\r\n");
                    MyPrinter.Print("   Thanks For visit Zia Book Seller.\r\n");
                    MyPrinter.Print("  Change and Return is possible within \r\n");
                    MyPrinter.Print("         2 days with this bill\r\n");
                    MyPrinter.Print("_________________________________________\r\n");
                    MyPrinter.Print("\r\n");
                    MyPrinter.Print("\r\n");
                    MyPrinter.Print("\r\n");
                    MyPrinter.Print("\r\n");
                    MyPrinter.Print("\r\n");
                    MyPrinter.Print("\r\n");
                    MyPrinter.Print("\r\n");
                    MyPrinter.Print("\r\n");
 
                    MyPrinter.Close();
 
                    inserting_process();
 

                    ResetControl(this);
                
               
 

            }
            else
            {
                MessageBox.Show("Please add product to start process", "Empty Sale", MessageBoxButtons.OK, MessageBoxIcon.Hand);
               
            }
 
One when I tried to add name of product It does not shows correct name but it shows form name even Name is correctly shown in gridview and even displaying good in message box.
Other problem is that I want to fix with of name in bill. If name is small than other would be spaces and if name is large than extra words would be eliminated.
AnswerRe: Bill Printing IssuememberAntonino Porcino3 Mar '13 - 21:28 
First problem is because you use "Name" (capitalized) instead of "name" (lowercase). C# is a case sensitive language, and you can have both "Name" and "name" defined and being two different things. In this case "Name" is the property Form.Name, and "name" is your defined string. Please note that "name" is already a string, so there's no need to write: name.ToString();
 
You can solve the second issue by using the "String.Format()" function, making also the code more readable. For example:
 
MyPrinter.Print(String.Format("{0:000} {1,-20:} {2:###0.00} {3:000} {4:######,00}\r\n",sr,name,price,qty,amount));
 
Check the guide on how to use the formatting codes.
 
Hope it helps
QuestionNot working in VB.NETmemberPeter Yulius10 Jan '13 - 3:37 
How to using in VB.NET? I try but it not working.
AnswerRe: Not working in VB.NETmemberAntonino Porcino10 Jan '13 - 6:48 
for VB.net you have to build a dll for it, as the code was written in C# (sorry).
 
If you have Visual Studio with C# installed do the following:
 
1) open the attached example project
2) from project property page, change from "winform application" to "library class" project.
3) recompile the application
4) now you have the needed .dll in the bin/Debug or bin/Release
5) add reference to this .dll in your VB project
6) Use namespace LPrinterTest and start using the LPrinter class
GeneralMy vote of 5memberwkiess0115 Jan '12 - 15:37 
This class is just perfect for what I needed to do. It's easy to use and works brilliantly! Thank you so much.
QuestionMake gujrati print in C#memberCHAVADA SURAJ12 Dec '11 - 15:03 
Plz answer How to Make Gujrati Print out using Line Printer Class using C# >
AnswerRe: Make gujrati print in C#memberAntonino Porcino12 Dec '11 - 21:36 
you can't directly print Gujurati characters, because line printer predefined fonts are only for occidental languages.
 
But you can use the printer in "graphic mode", although it's more complex and you don't take full advantage of line printing speed. Essentially you plot your text characters onto a bitmap and then send it to the printer. My line printer C# class does't cover this, but if you read past comments in this article you'll find how to extend the class for graphic printing.
AnswerRe: Make gujrati print in C#memberlukac23 Dec '11 - 0:39 
Hi!
This sample code helps me to print Croatian (localised) characters. I searched a lot but cant find solution. Finally I got idea and will share with you guys. It works for me. I think that you should have printer with code page for your country installed in room. If not You should deal with loading soft fonts in printer then print.
 
public bool Print(string outputstring)
      {
         if(HandlePrinter==IntPtr.Zero) return false;
 
         Encoding enc852 = System.Text.Encoding.GetEncoding(852) ;
         byte[] bytes852 = enc852.GetBytes(outputstring);
         int nLength = Convert.ToInt32(bytes852.Length);
         // Allocate unmanaged memory for those bytes.
         IntPtr pBytes = Marshal.AllocCoTaskMem(nLength);
         // Moral copy direct without any changes to string or bytes
         Marshal.Copy(bytes852, 0, pBytes, nLength);
         // Send the unmanaged bytes to the printer
         int dwWritten = 0;
         bool bSuccess = WritePrinter(HandlePrinter, pBytes, nLength, out dwWritten);
         // Free the unmanaged memory that you allocated earlier.
         Marshal.FreeCoTaskMem(pBytes);
         if (!bSuccess) return false;
         else return true;
      }
public bool PrintLine(string outputstring)
       {
           // add string for LFCR or use ESC seq this could be faster for lot of lines
           outputstring += "\r\n";
           return this.Print(outputstring);
       }
 
 
This is ESC sequences class so you can make one class for each specific printer if like. I use this for POSIFLEX aura 8000 pos printer.
 
sing System;
using System.Collections.Generic;
using System.Text;
 
namespace lucach.Printing
{
    public  class CEscape
    {
        //konstructor
        public CEscape() { }
 

 

        public String OpenCashDrawer2Pin()
        {
 
            StringBuilder sequence = new StringBuilder();
            sequence.Append((char)27);
            sequence.Append((char)112);
            // 0-pin 2 ; 1- pin 5
            sequence.Append((char)0);
            sequence.Append((char)30);
            sequence.Append((char)30);
 
            return sequence.ToString();
 
        }
 

 
        public  String OpenCashDrawer5Pin()
        {
 
            StringBuilder sequence = new StringBuilder();
            sequence.Append((char)27);
            sequence.Append((char)112);
            // 0-pin 2 ; 1- pin 5
            sequence.Append((char)1);
            sequence.Append((char)30);
            sequence.Append((char)30);
 
            return sequence.ToString();
 
        }
 

 
        public String InitializePrinter()
        {
 
            StringBuilder sequence = new StringBuilder();
            sequence.Append((char)27);
            sequence.Append((char)64);
 
            return sequence.ToString();
 
        }
 
        public String PrintCenterText()
        {
            //The printer will continue printing at center
            StringBuilder sequence = new StringBuilder();
            sequence.Append((char)27);
            sequence.Append((char)97);
            sequence.Append((char)1);
 
            return sequence.ToString();
        }
 

        public String BoldON()
        {
            //The printer will continue printing Bolded characters
            StringBuilder sequence = new StringBuilder();
            sequence.Append((char)27);
            sequence.Append((char)69);
            sequence.Append((char)1);
 
            return sequence.ToString();
        }
 

        public String BoldOFF()
        {
            //The printer will stop printing Bold
            StringBuilder sequence = new StringBuilder();
            sequence.Append((char)27);
            sequence.Append((char)69);
            sequence.Append((char)0);
 
            return sequence.ToString();
        }
 
        public String PrintLeftText()
        {
 
            //The printer will continue printing at left
            StringBuilder sequence = new StringBuilder();
            sequence.Append((char)27);
            sequence.Append((char)97);
            sequence.Append((char)0);
            
            return sequence.ToString();
 
        }
 
        public String PrintRightText()
        {
 
            //The printer will continue printing Right
            StringBuilder sequence = new StringBuilder();
            sequence.Append((char)27);
            sequence.Append((char)97);
            sequence.Append((char)2);
 
            return sequence.ToString();
 
        }
 

        public String SelectCP437()
        {
            StringBuilder sequence = new StringBuilder();
            
            sequence.Append((char)27);
            sequence.Append((char)82);
            sequence.Append((char)15);
 
            return sequence.ToString();
        }
 
        public String SelectTextMode()
        {
            StringBuilder sequence = new StringBuilder();
            // ESC S
            sequence.Append((char)27);
            sequence.Append((char)83);
            
            return sequence.ToString();
        }
 

        public String SelectCP852()
        {
            StringBuilder sequence = new StringBuilder();
            sequence.Append((char)27);
            sequence.Append((char)116);
            sequence.Append((char)18);
 
            return sequence.ToString();
        }
 
        public String CutPaper()
        {
            StringBuilder sequence = new StringBuilder();
            sequence.Append((char)27);
            sequence.Append((char)105);
            sequence.Append((char)0);
            sequence.Append((char)25);
 
            return sequence.ToString();
 
        }
 

 
        public String FeedPaper(int pNumLines)
        {
 
            StringBuilder sequence = new StringBuilder();
            sequence.Append((char)27);
            sequence.Append((char)100);
            sequence.Append((char)pNumLines);
 
            return sequence.ToString();
 
        }
 
        public String PrintAndFeedPaper(int pNumLines)
        {
            // Print and feed pNumLines
            StringBuilder sequence = new StringBuilder();
            sequence.Append((char)27);
            sequence.Append((char)100);
            sequence.Append((char)pNumLines);
 
            return sequence.ToString();
        }
 

        public String SelectFontB()
        {
            //normalni font 
            StringBuilder sequence = new StringBuilder();
            sequence.Append((char)27);
            sequence.Append((char)77);
            sequence.Append((char)1);
 
            return sequence.ToString();
        }
 
        public String SelectFontA()
        {
            //normalni font
            StringBuilder sequence = new StringBuilder();
            sequence.Append((char)27);
            sequence.Append((char)77);
            sequence.Append((char)0);
 
            return sequence.ToString();
        }
 

        public String SetDoubleHeightFontA()
        {
            StringBuilder sequence = new StringBuilder();
            // Nesto drugacije sekvence od setprint mode
            sequence.Append((char)27);
            sequence.Append((char)33);
            sequence.Append((char)16);
 
            return sequence.ToString();
        }
 

        public String SetDoubleHeightFontB()
        {
            StringBuilder sequence = new StringBuilder();
            // Nesto drugacije sekvence od setprint mode
            sequence.Append((char)27);
            sequence.Append((char)33);
            sequence.Append((char)17);
 
            return sequence.ToString();
        }
 

        public String SetDoubleWidthFontA()
        {
            StringBuilder sequence = new StringBuilder();
            // Nesto drugacije sekvence od setprint mode
            sequence.Append((char)27);
            sequence.Append((char)33);
            sequence.Append((char)32);
 
            return sequence.ToString();
        }
 

        public String Set2H2WFontA()
        {
            //double h double w
            StringBuilder sequence = new StringBuilder();
            // Nesto drugacije sekvence od setprint mode
            sequence.Append((char)27);
            sequence.Append((char)33);
            sequence.Append((char)56);
 
            return sequence.ToString();
        }
 

        public String Set2H2WFontB()
        {
            StringBuilder sequence = new StringBuilder();
            // something diff. from setprint mode
            sequence.Append((char)27);
            sequence.Append((char)33);
            sequence.Append((char)39);
 
            return sequence.ToString();
        }
 
        public String SetNormalFont()
        {
            StringBuilder sequence = new StringBuilder();
            
            sequence.Append((char)29);
            sequence.Append((char)33);
            sequence.Append((char)0);
 
            return sequence.ToString();
        }
 
        public String SetLeftMarginTo0()
        {
            StringBuilder sequence = new StringBuilder();
 
            sequence.Append((char)29);
            sequence.Append((char)76);
            sequence.Append((char)0);
 
            return sequence.ToString();
        }
 
        public String SetEXYuFont()
        {
            // this set international character table
            // select an international character 15 for EX-Yu foreign Yugoslavia
            StringBuilder sequence = new StringBuilder();
            sequence.Append((char)27);
            sequence.Append((char)82);
            sequence.Append((char)15);
 
            return sequence.ToString();
        }
 

        public String TurnOnReversePrinting()
        {
            StringBuilder sequence = new StringBuilder();
            
            sequence.Append((char)29);
            sequence.Append((char)66);
            sequence.Append((char)1);
 
            return sequence.ToString();
        }
 

        public String TurnOffReversePrinting()
        {
            StringBuilder sequence = new StringBuilder();
           
            sequence.Append((char)29);
            sequence.Append((char)66);
            sequence.Append((char)0);
 
            return sequence.ToString();
        }
 

        public String UnderlineOFF()
        {
            StringBuilder sequence = new StringBuilder();
 
            sequence.Append((char)27);
            sequence.Append((char)45);
            sequence.Append((char)0);
 
            return sequence.ToString();
        }
 

        public String Underline1Dot()
        {
            StringBuilder sequence = new StringBuilder();
 
            sequence.Append((char)27);
            sequence.Append((char)45);
            sequence.Append((char)1);
 
            return sequence.ToString();
        }
 

        public String Underline2Dot()
        {
            StringBuilder sequence = new StringBuilder();
 
            sequence.Append((char)27);
            sequence.Append((char)45);
            sequence.Append((char)2);
 
            return sequence.ToString();
        }
 
        public String SetLeftMarginInTextMode()
        {
            StringBuilder sequence = new StringBuilder();
            
            sequence.Append((char)29);
            sequence.Append((char)76);
            sequence.Append((char)0);
            sequence.Append((char)0);
 
            return sequence.ToString();
        }
 
        public String CR()
        {
            StringBuilder sequence = new StringBuilder();
            
            sequence.Append((char)13);
            
            return sequence.ToString();
        }
 
        public String FF()
        {
            // Print and return to text mode in page mode
            StringBuilder sequence = new StringBuilder();
 
            sequence.Append((char)12);
 
            return sequence.ToString();
        }
 
        public String LF()
        {
            // Print and line feed
            StringBuilder sequence = new StringBuilder();
 
            sequence.Append((char)10);
 
            return sequence.ToString();
        }
 
        public String LFCR()
        {
            // Print and line feed and new line
            StringBuilder sequence = new StringBuilder();
 
            sequence.Append((char)10);
            sequence.Append((char)13);
 
            return sequence.ToString();
        }
   
 
    }
}
 
Use this code like this:
 
LPrinter lp = new LPrinter();
CEscape esq = new CEscape();
// use this to initialize printer and set code page for your country and international table
// ask your dealer for ESC POS sequences table - documentation
lp.Print(esq.InitializePrinter()+ esq.SelectCP852()+ esq.SetEXYuFont()+ esq.SetNormalFont());
lp.Print(esq.SetDoubleHeightFontA() + esq.BoldON() + esq.PrintCenterText() + "Select font A and print bolded double height + "\r\n");
lp.PrintLine(esq.PrintCenterText() + esq.SetNormalFont() + "This is printed centered on paper");
lp.Print(esq.OpenCashDrawer2Pin());
lp.Print(esq.OpenCashDrawer5Pin()); 
lp.Print(esq.PrintAndFeedPaper(2));
lp.Print(esq.CutPaper());
 
On the end very BIG thanks to Antonio because i got an idea when saw his article.
lucach

QuestionLine Printer Class problemmemberZil-e-Huma16 Aug '11 - 1:03 
Hi,
The Line Printer class given by u was useful in printing string in real time, can you please tell me that how can i change this code to plot graphical data at real time. As in the code there is WritePrinter() function but in the Windows Spooler API no such function is available which tells the printer to draw a plot (instead of printing string) and then stop the spooler at the middle of the page. Please tell me how can i do that. please reply me as soon as possible.
AnswerRe: Line Printer Class problemmemberAntonino Porcino16 Aug '11 - 3:55 
there is no easy way to print graphics on a line printer (keep in mind they were firstly designed to print text-only). Basically you have to draw your image onto a monochromatic bitmap canvas and then convert such canvas into special printer codes (that can be later sent with the LinePrinter class). You convert line by line, scanning from top to bottom, turning pixels into bytes and sending them after a special ESC sequence.
 
The details are described in this manual, paragraph 5.4 "Graphics" on page 18. Note the the examples are written in GW-BASIC where the LPRINT command is the equivalent of LinePrinter.Print() method.
 
Hope it helps someway.
GeneralRe: Line Printer Class problemmemberZil-e-Huma16 Aug '11 - 17:50 
Ok thank you. But how can i draw my points (locations) onto a monochrome bitmap canvas for converting into special printer codes. This thing is really new for me. I think you are asking me to store my coordinates as a graph into a bmp file and then to print it through LPrinter Class. How you tell me how can i do that. I ll be very thankful if you solve my problem. Thanks in advance.
GeneralRe: Line Printer Class problemmemberZil-e-Huma16 Aug '11 - 19:42 
I am able to create a bitmap out of the coordinates which i want to plot and also can store it in an image file (bmp,jpeg, etc). Now can you please guide me that how can i step forward.. which you said as... """and then convert such canvas into special printer codes (that can be later sent with the LinePrinter class). You convert line by line, scanning from top to bottom, turning pixels into bytes and sending them after a special ESC""".
can you please tel me how can i do this all?
GeneralRe: Line Printer Class problemmemberAntonino Porcino16 Aug '11 - 20:57 
Sorry, I don't have access to a physical Line Printer right now, so I can't write and test the code for you. More or less it should be something like this:
 
First, you need to be able to send "bytes" to the printer with a method like this:
 
      public void PrintByte(LinePrinter PRN, int b)
      {
         byte[] buf = new byte[1];
         buf[0] = (byte) b;         
         System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
         string str = enc.GetString(buf);
         PRN.Print(str);
      }
 
then you need a bitmap scanning routine that converts pixels into printer codes:
 
      public void PrintBitmap(LinePrinter PRN, Bitmap bmp)
      {
         int width  = bmp.Width;
         int height = bmp.Height - bmp.Height % 8;
 
         int numbytes = height;
         int lo = numbytes & 255;
         int hi = numbytes >> 8;        
         
         for(int y=0;y<height;y+=8)
         {             
             PrintByte(27);
             PrintByte(75);
             PrintByte(lo);
             PrintByte(hi);
 
             for(int x=0;x<width;x++)
             {
                int b = 0;
                for(int i=0;i<=7;i++)
                {
                   Color c = bmp.GetPixel(x,y+i);
                   if(c==Color.Black) b = b | (1 << (7-i));
                }
                PrintByte(b);
             }
         }         
      }
 
Short explanation: scanning is done from top to bottom, each line is composed of 8 vertical pixel. All is done with the "ESC K" printer command, that enables you to define and print a single line raster bit image on a single text line. From the printer manual:
 
• n1 and n2 define the number of bytes that comprise the image.
• The image consists of 256*n2+n1 bytes of data, each byte representing a single vertical column of
4/30".
• Images are printed left to right.
• Images are printed at a horizontal resolution of 60 dots per inch and at an approximate vertical resolution of 72 dots per inch.
• Each byte represents a vertical column of eight dots, the most significant bit representing the dot at the top. Simply set a bit to 1 if you want a dot to appear in that position, and to 0 if you want white space to appear.

 
As said above, I have not tested the code on a real printer so I won't be surprised if it doesn't work at first try.
GeneralRe: Line Printer Class problemmemberZil-e-Huma17 Aug '11 - 0:06 
Thankyou so much for providing me the solution, but i am really sorry i cannot understand the logic, that what are you trying to do. I have tried to understand that but i am not getting command over it so as to use it for my purpose, i have called the PrintBitmap() at the place where there we were calling MyPrinter.Print() in the LPrinter class. But (as you already anticipated), the code is not working. It isnt printing out anything. i have tried to make some changes in it but as i dont really understand the logic behind this code so i am not succesful in making modification in the code in such a way as to serve my purpose.
Please guide me, i am new in this thing. i am sending you the code so that you may point out the point where i am making mistake, i am saying again that as i dont understand the logic so i cant make this code work to serve my purpose. please help me out.
 
//Code..
 
////////////////////////////
//This is the main function where i am creating object to your LPrinter class, here i have introduced the two functions that you indicated..
 
using System;
using System.Windows.Forms;
using System.Drawing.Printing;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
 
namespace LPrinterTest
{
public partial class Form1 : Form
{
LPrinter MyPrinter;

public Form1()
{
InitializeComponent();
MyPrinter = new LPrinter();
}
 
private void button1_Click(object sender, EventArgs e)
{
MyPrinter.ChoosePrinter();
}
 
System.Drawing.Bitmap CreateBitmap()
{ // here the bitmap is being created
 
int x, y;
 
System.Drawing.Bitmap flag = new System.Drawing.Bitmap(8, 8);
for (x = 0; x < flag.Height; ++x)
for (y = 0; y < flag.Width; ++y)
flag.SetPixel(x, y, Color.Black);
 
for (x = 0; x < flag.Height; ++x)
flag.SetPixel(x, x, Color.Red);
 
return flag;
}
 
private void button2_Click(object sender, EventArgs e)
{
if (!MyPrinter.Open("Test Page")) return;
PrintBitmap();
MyPrinter.Close();
}
 
public void PrintByte(int b)
{
byte[] buf = new byte[1];
buf[0] = (byte)b;
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
string str = enc.GetString(buf);
MyPrinter.Print(str);
}
 
public void PrintBitmap()
{
System.Drawing.Bitmap flag;
flag = CreateBitmap();

int width = flag.Width;
 
int height = flag.Height - flag.Height % 8;
 
int numbytes = height;
int lo = numbytes & 255;
int hi = numbytes >> 8;
 
for (int y = 0; y < height; y += 8)
{
PrintByte(27);
PrintByte(75);
PrintByte(lo);
PrintByte(hi);
 
for (int x = 0; x < width; x++)
{
int b = 0;
for (int i = 0; i <= 7; i++)
{
Color c = flag.GetPixel(x, y + i);
if (c == Color.White)
b = b | (1 << (7 - i));
}
PrintByte(b);
}
}

}
}
}

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 26 Sep 2008
Article Copyright 2008 by Antonino Porcino
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid