首页 > 解决方案 > 在 C#.net 中,如何在打印时获取行中的文本?

问题描述

我在 C# windows 窗体应用程序中创建了一个项目。我正在使用 Visual Studio 2010 和 .net 框架 4.0 版。我的项目有打印按钮。我为打印按钮编写了代码:

 private void btn_Print_Click(object sender, EventArgs e)
    {
        PrintDialog pd = new PrintDialog();
        PrintDocument pdoc = new PrintDocument();
        PrinterSettings ps = new PrinterSettings();

        PaperSize psize = new PaperSize("Custom", 100, 200);

        pd.Document = pdoc;
        pd.Document.DefaultPageSettings.PaperSize = psize;

        pdoc.DefaultPageSettings.PaperSize.Height = 820;

        pdoc.DefaultPageSettings.PaperSize.Width = 520;

        pdoc.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
        DialogResult result = pd.ShowDialog();
        if (result == DialogResult.OK)
        {
            PrintPreviewDialog pp = new PrintPreviewDialog();
            pp.Document = pdoc;
            result = pp.ShowDialog();
            if (result == DialogResult.OK)
            {
                pdoc.Print();
            }
        }
    }

和 printDocument1 控件的事件处理程序代码

 private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
    {

        string s1 = "1st line text";
        string s2 = "2nd line text";
        string s3 = "3rd line text";
        Font f1 = new Font("Arial", 10, FontStyle.Bold, GraphicsUnit.Pixel);
        Font f2 = new Font("Arial", 10, FontStyle.Regular, GraphicsUnit.Pixel);
        Font f3 = new Font("Arial", 10, FontStyle.Regular, GraphicsUnit.Pixel);
        e.Graphics.DrawString(s1, f1, Brushes.Black, new Point(260, 10));
        e.Graphics.DrawString(s2, f2, Brushes.Black, new Point(260, 20));
        e.Graphics.DrawString(s3, f3, Brushes.Black, new Point(260, 30));

   }

我需要在行中间的字符串 s1,s2,s3。从上面的代码中,我得到了从行的中点开始的字符串的第一个字符。但我需要在中间的整个字符串。我尝试了网上给出的所有解决方案。但还没有得到结果。请帮我找出,我错过了什么。谢谢你的时间。

标签: c#.netwinformsprintingprintdocument

解决方案


e.Graphics.DrawString(s1, f1, Brushes.Black, new RectangleF(0, 10, e.PageBounds.Width, 30), new StringFormat() { Alignment = StringAlignment.Center });

而不是点,设置您需要打印的区域的实际矩形并设置对齐方式

在您的声明中,代码必须是

        string s1 = "1st line text";
        string s2 = "2nd line text";
        string s3 = "3rd line text";
        Font f1 = new Font("Arial", 10, FontStyle.Bold, GraphicsUnit.Pixel);
        Font f2 = new Font("Arial", 10, FontStyle.Regular, GraphicsUnit.Pixel);
        Font f3 = new Font("Arial", 10, FontStyle.Regular, GraphicsUnit.Pixel);
        e.Graphics.DrawString(s1, f1, Brushes.Black, new RectangleF(0, 10, e.PageBounds.Width, 10), new StringFormat() { Alignment = StringAlignment.Center });
        e.Graphics.DrawString(s2, f2, Brushes.Black, new RectangleF(0, 20, e.PageBounds.Width, 10), new StringFormat() { Alignment = StringAlignment.Center });
        e.Graphics.DrawString(s3, f3, Brushes.Black, new RectangleF(0, 30, e.PageBounds.Width, 10), new StringFormat() { Alignment = StringAlignment.Center });

推荐阅读