c# - 如何打印某些标签的文字?

时间:2014-10-25 13:55:53

标签: c# .net winforms printing

我的程序中有一些标签,如:

Name: Paul
Bought: bike

我只想打印这个。我试图用PrintDialog和PrintDocument这样做,但没有成功。我不知道如何获取这些标签的文字和打印。更具体地说,我不知道如何打印任何东西。

我是第一次尝试做这样的事情,如果有人知道如何使用C#进行打印,我将非常感激。

1 个答案:

答案 0 :(得分:2)

在C#中,与绘画几乎没有区别。这很简单:

public void PrintThemAll()
{
    var document = new PrintDocument();
    document.PrintPage += document_PrintPage;
    document.Print();
}

void document_PrintPage(object sender, PrintPageEventArgs e)
{
    var graphics = e.Graphics;
    var normalFont = new Font("Calibri", 14); 

    var pageBounds = e.MarginBounds;
    var drawingPoint = new PointF(pageBounds.Left, (pageBounds.Top + normalFont.Height));

    graphics.DrawString("Name: Paul", normalFont, Brushes.Black, drawingPoint);

    drawingPoint.Y += normalFont.Height;

    graphics.DrawString("Bought: bike", normalFont, Brushes.Black, drawingPoint);

    e.HasMorePages = false; // No pages after this page.
}

您需要创建PrintDocument对象,并为PrintPage事件添加处理程序。每当HasMorePages设置为true时,将调用PrintPage处理程序(如果它设置为false - 当前页面是最后一个)。在处理程序内,您可以在打印文档中绘制任何内容。

相关问题