c#简单打印机程序

1,在Form中加入一个印刷的控件PrintDocument,取名为MyPrintDocument

2,新建一个一般类(不是窗体类),名叫MyPrinter,内容如下:

public class MyPrinter

    {

        private PrintDocument ThePrintDocument;

        private Font titleFont;

        private Font theFont;

        private Color FontColor;

        private float CurrentY;

        static int PageNumber;

        private int PageWidth;

        private int PageHeight;

        private int LeftMargin;

        private int TopMargin;

        private int RightMargin;

        private int BottomMargin;

        private ArrayList textList = new ArrayList();

        private int currentIndex = 0;

        public MyPrinter(PrintDocument _thePrintDocument, Font _theFont, Font _titleFont,Color _FontColor, ArrayList _textList)

        {

            ThePrintDocument = _thePrintDocument;

            theFont = _theFont;

            titleFont = _titleFont;

            FontColor = _FontColor;

            PageNumber = 0;

            textList = _textList;

            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;

            }

            LeftMargin = ThePrintDocument.DefaultPageSettings.Margins.Left;

            TopMargin = ThePrintDocument.DefaultPageSettings.Margins.Top;

            RightMargin = ThePrintDocument.DefaultPageSettings.Margins.Right;

            BottomMargin = ThePrintDocument.DefaultPageSettings.Margins.Bottom;

        }

        public bool DrawDocument(Graphics g)

        {

            try

            {

                DrawHeader(g);

                bool bContinue = DrawItems(g);

                g.Dispose();

                return bContinue;

            }

            catch (Exception ex)

            {

                MessageBox.Show("失败" + ex.Message.ToString(), " - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                g.Dispose();

                return false;

            }

        }

        public void DrawHeader(Graphics g)

        {

            CurrentY = (float)TopMargin;

            PageNumber++;

            string PageString = "第" + PageNumber+"页";

            StringFormat PageStringFormat = new StringFormat();

            PageStringFormat.Trimming = StringTrimming.Word;

            PageStringFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;

            PageStringFormat.Alignment = StringAlignment.Far;

            RectangleF PageStringRectangle = new RectangleF((float)LeftMargin, CurrentY, (float)PageWidth - (float)RightMargin - (float)LeftMargin, g.MeasureString(PageString, theFont).Height);

            g.DrawString(PageString, theFont, new SolidBrush(Color.Black), PageStringRectangle, PageStringFormat);

            CurrentY += g.MeasureString(PageString, theFont).Height;

            StringFormat TitleFormat = new StringFormat();

            TitleFormat.Trimming = StringTrimming.Word;

            TitleFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;

            TitleFormat.Alignment = StringAlignment.Center;

            RectangleF TitleRectangle = new RectangleF((float)LeftMargin, CurrentY, (float)PageWidth - (float)RightMargin - (float)LeftMargin, g.MeasureString("收费单", titleFont).Height);

            g.DrawString("收费单",titleFont,new SolidBrush(FontColor),TitleRectangle,TitleFormat);

            CurrentY +=g.MeasureString("收费单",titleFont).Height;

        }

        public bool DrawItems(Graphics g)

        {

            StringFormat TextFormat = new StringFormat();

            TextFormat.Trimming = StringTrimming.Word;

            TextFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;

            TextFormat.Alignment = StringAlignment.Near;

            for (int i = currentIndex; i < textList.Count; i++)

            {

                string var = textList[i].ToString();

                RectangleF TextRectangle = new RectangleF((float)LeftMargin, CurrentY, (float)PageWidth - (float)RightMargin - (float)LeftMargin, g.MeasureString("收费单", titleFont).Height);

                g.DrawString(var, theFont, new SolidBrush(FontColor), TextRectangle, TextFormat);

                CurrentY = CurrentY + g.MeasureString(var, theFont).Height;

                if ((int)CurrentY > (PageHeight - TopMargin - BottomMargin))

                {

                    currentIndex = i+1;

                    return true;

                }

            }

            return false;

        }

    }

3,回到原来的Form中,给MyPrintDocument添加PrintPage事件

private void MyPrintDocument_PrintPage(object sender, PrintPageEventArgs e)

        {

            bool hasNextPage = mp.DrawDocument(e.Graphics);

            if (hasNextPage)

            {

                e.HasMorePages = true;

            }

        }

4,撰写打印机设置对话框函数

private bool SetupThePrinting()

        {

            PrintDialog MyPrintDialog = new PrintDialog();

            MyPrintDialog.AllowCurrentPage = false;

            MyPrintDialog.AllowPrintToFile = false;

            MyPrintDialog.AllowSelection = false;

            MyPrintDialog.AllowSomePages = false;

            MyPrintDialog.PrintToFile = false;

            MyPrintDialog.ShowHelp = false;

            MyPrintDialog.ShowNetwork = false;

            if (MyPrintDialog.ShowDialog() != DialogResult.OK)

                return false;

            MyPrintDocument.DocumentName = "收费单 ";

            MyPrintDocument.PrinterSettings = MyPrintDialog.PrinterSettings;

            MyPrintDocument.DefaultPageSettings = MyPrintDialog.PrinterSettings.DefaultPageSettings;

            MyPrintDocument.DefaultPageSettings.Margins = new Margins(100, 40, 100, 40);

            ArrayList textList = new ArrayList();

            mp = new MyPrinter(MyPrintDocument, new Font("Tahoma", 8, FontStyle.Regular, GraphicsUnit.Point), new Font(FontFamily.GenericSerif, 18, FontStyle.Bold, GraphicsUnit.Point), Color.Black, textList);

            return true;

        }

5,最后加上打印按钮,打印预览按钮的单击事件

    1),打印按钮的单击事件

         private void btnPrint_Click(object sender, EventArgs e)

        {           

            if (SetupThePrinting())

                MyPrintDocument.Print();

        }

    2)打印预览按钮的单击事件(根据需要)

         private void btnPrintPreview_Click(object sender, EventArgs e)

        {

            if (SetupThePrinting())

            {

                PrintPreviewDialog MyPrintPreviewDialog = new PrintPreviewDialog();

                MyPrintPreviewDialog.Document = MyPrintDocument;

                MyPrintPreviewDialog.ShowDialog();

            }

        }

6,现在你或许要问,那我的打印数据如何加入呢?其实就在刚才写的打印机设置对话框函数里面,如下:

ArrayList textList = new ArrayList();

            //textList.Add("收费单");

            //textList.Add("2009-04-01");

            //textList.Add("开始时间:12:00 ");

            //textList.Add("结束时间:13:00 ");

            //textList.Add("时间单位:4 ");

            //textList.Add("单位时间价格:20.00元 ");

            //textList.Add("消费价格:80.00元 ");

            //textList.Add("------------------------------------------------------------- ");

            //textList.Add("2009-04-01 ");

            //textList.Add("开始时间:12:20 ");

            //textList.Add("开始时间:12:20 ");

            //textList.Add("时间单位:3 ");

            //textList.Add("单位时间价格:20.00元 ");

            //textList.Add("消费金额:60.00元  ");

            //textList.Add("------------------------------------------------------------- ");

            //textList.Add("合计:140.00元 ");

            //textList.Add("2");

            mp = new MyPrinter(MyPrintDocument, new Font("Tahoma", 8, FontStyle.Regular, GraphicsUnit.Point), new Font(FontFamily.GenericSerif, 18, FontStyle.Bold, GraphicsUnit.Point), Color.Black, textList);

            return true;

也就是,你只要自己根据你现有的数据将信息一行一行Add到textList中,就可以了

楼上的,1万行你复制一万行?for循环留着干嘛的啊?个人觉得不一定现成的东西都是对自己最有利的。

付参考效果图。

C#中,要让程序通过指定的打印机打印Excel文件(.xls或.xlsx),你需要使用`System.Printing`命名空间中的功能,结合第三方库如EPPlus (for .xlsx) 或 NPOI (for .xls) 来读取和操作Excel文件。以下是一个简单的步骤: 1. **添加依赖**: - 对于`.xlsx`文件,你需要安装EPPlus库:`Install-Package EPPlus` - 对于`.xls`文件,可以使用NPOI:`Install-Package NPOI` 2. **读取并转换Excel内容**: 使用EPPlus或NPOI打开Excel文件,选择需要打印的工作表,并将其数据读取到内存中的DataTable或其他适合的数据结构。 ```csharp using OfficeOpenXml; // 或者 using NPOI.SS.UserModel; // 示例1 (EPPlus) FileInfo fileInfo = new FileInfo("path_to_your_excel_file.xlsx"); using (var package = new ExcelPackage(fileInfo)) { ExcelWorksheet worksheet = package.Workbook.Worksheets[0]; DataTable data = worksheet.Cells.Cast<Range>().Select(cell => cell.Value).ToList(); } // 示例2 (NPOI) FileInfo fileInfo = new FileInfo("path_to_your_excel_file.xls"); IXLSWorkbook workbook = new HSSFWorkbook(fileInfo); IXLSWorksheet sheet = workbook.GetSheetAt(0); ``` 3. **创建PrintDocument或PrinterSettings**: 创建一个`PrintDocument`实例,或者设置`PrinterSettings`对象,指定你想使用的打印机。 ```csharp PrintDocument printDoc = new PrintDocument(); // 设置打印机 printDoc.DefaultPageSettings.PrinterName = "Your Printer Name"; ``` 4. **处理PrintPage事件**: 实现`PrintDocument`的`OnPrintPage`方法,在这里将Excel数据画到页面上。 ```csharp private void printDoc_PrintPage(object sender, PrintPageEventArgs e) { // 将数据渲染到e.Graphics对象上 // 使用EPPlus: foreach (var row in data.Rows) { var x = e.MarginBounds.Left; var y = e.MarginBounds.Top + e.YOffset; // 确保每次开始绘制在新的一行 for (int i = 0; i < row.Count; i++) { e.Graphics.DrawString(row[i].ToString(), font, Brushes.Black, x, y); y += font.Height; } } // 使用NPOI: // ... 类似地遍历sheet并绘制数据 } ``` 5. **打印**: 添加打印事件处理器并开始打印。 ```csharp printDoc.Print(); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值