How to print a text file on thermal printer using PrintDocument?

后端 未结 3 1506
温柔的废话
温柔的废话 2020-11-29 07:57

I\'m creating an application using C# with Winforms and now I need to print the receipt of sale on a thermal printer. To do this I\'m creating a text file and reading it to

3条回答
  •  醉梦人生
    2020-11-29 08:17

    If you send a plain string to your printPage(object sender, PrintEventArgs e) method, it will just print plain text in all the same font which looks 'messy' (as you named it) If you want it to be printed well formatted with different fonts (bold, regular), you have to do it all manually:

    List itemList = new List()
    {
        "201", //fill from somewhere in your code
        "202"
    };
    
    private void printPage( object sender, PrintPageEventArgs e )
    {
        Graphics graphics = e.Graphics;
    
        Font regular = new Font( FontFamily.GenericSansSerif, 10.0f, FontStyle.Regular );
        Font bold = new Font( FontFamily.GenericSansSerif, 10.0f, FontStyle.Bold );
    
        //print header
        graphics.DrawString( "FERREIRA MATERIALS PARA CONSTRUCAO LTDA", bold, Brushes.Black, 20, 10 );
        graphics.DrawString( "EST ENGENHEIRO MARCILAC, 116, SAO PAOLO - SP", regular, Brushes.Black, 30, 30 );
        graphics.DrawString( "Telefone: (11)5921-3826", regular, Brushes.Black, 110, 50 );
        graphics.DrawLine( Pens.Black, 80, 70, 320, 70 );
        graphics.DrawString( "CUPOM NAO FISCAL", bold, Brushes.Black, 110, 80 );
        graphics.DrawLine( Pens.Black, 80, 100, 320, 100 );
    
        //print items
        graphics.DrawString( "COD | DESCRICAO                      | QTY | X | Vir Unit | Vir Total |", bold, Brushes.Black, 10, 120 );
        graphics.DrawLine( Pens.Black, 10, 140, 430, 140 );
    
        for( int i = 0; i < itemList.Count; i++ )
        {
            graphics.DrawString( itemList[i].ToString(), regular, Brushes.Black, 20, 150 + i * 20 );
        }
    
        //print footer
        //...
    
        regular.Dispose();
        bold.Dispose();
    
        // Check to see if more pages are to be printed.
        e.HasMorePages = ( itemList.Count > 20 );
    }
    

    Possible improvements on my example:

    • Centering the header strings could better be done using graphics.MeasureString().
    • List of items should better be a list of a business class insted of a plain string

    Because this all is a lot of work, you should really consider using RDLC or some third party software to design your documents.

提交回复
热议问题