c# 打印字符串

using System;
using System.Drawing;
using System.Drawing.Printing;
 
public class PrinterExample
{
    public static void Main()
    {
        // 创建PrintDocument对象
        PrintDocument printDocument = new PrintDocument();
 
        // 设置打印任务的事件处理程序
        printDocument.PrintPage += new PrintPageEventHandler(PrintPage);
 
        // 打印文档
        try
        {
            printDocument.Print();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
 
    // 打印页面的事件处理程序
    private static void PrintPage(object sender, PrintPageEventArgs e)
    {
        string textToPrint = "Hello, World!"; // 要打印的字符串
        Font printFont = new Font("Arial", 12); // 字体和大小
        Brush brush = new SolidBrush(Color.Black); // 画笔颜色
 
        // 测量字符串的大小
        SizeF textSize = e.Graphics.MeasureString(textToPrint, printFont);
 
        // 在页面上打印字符串(水平居中,垂直居中)
        PointF textLocation = new PointF(
            (e.PageBounds.Width / 2) - (textSize.Width / 2),
            (e.PageBounds.Height / 2) - (textSize.Height / 2));
 
        e.Graphics.DrawString(textToPrint, printFont, brush, textLocation);
    }
}

你可能感兴趣的:(c#,开发语言)