如何将 C# 与远程打印机连接

本文关键字:打印机 连接 | 更新日期: 2023-09-27 18:33:22

>我正在尝试使用命名空间连接 C# 和远程服务器System.printing这是我的代码,它执行得很好,但它不打印任何东西,我不知道为什么。

[DllImport("winspool.drv")]
public static extern bool AddPrinterConnection(string PrinterName);
[DllImport("winspool.drv")]
public static extern bool SetDefaultPrinter(string printerName);
private void ConnectToNetworkPrinter()
{
    bool result = AddPrinterConnection(@"''CHSADMIN-PC'Canon LBP2900");
    bool resultdef = SetDefaultPrinter(@"''CHSADMIN-PC'Canon LBP2900");
}
public void Button1_Click(object sender, EventArgs e)
{
    PrintServer myPrintServer = new PrintServer(
        @"''CHSADMIN-PC", 
        System.Printing.PrintSystemDesiredAccess.EnumerateServer);
    PrintQueueCollection myPrintQueues = myPrintServer.GetPrintQueues();
    String printQueueNames = "My Print Queues:'n'n";
    foreach (PrintQueue pq in myPrintQueues)
    {
        printQueueNames += "'t" + pq.Name + "'n";
    }
    Console.WriteLine(printQueueNames);
    Console.WriteLine("'nPress Return to continue.");
    Console.ReadLine();
}

如何将 C# 与远程打印机连接

protected void Button1_Click(object sender, EventArgs e)
     {
        //String strDefaultPrinter;
        //SetDefaultPrinter("doPDF v7");
        PrintDialog printDialog = new PrintDialog();
        PrintDocument documentToPrint = new PrintDocument();
        printDialog.Document = documentToPrint;
        documentToPrint.PrinterSettings.PrinterName = "canon LBP2900 on CHSADMIN-PC";
        StringReader reader = new StringReader(TextBox1.Text);
        documentToPrint.PrintPage += new PrintPageEventHandler(DocumentToPrint_PrintPage);
        documentToPrint.Print();

    }

    private void DocumentToPrint_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
    {
        StringReader reader = new StringReader(TextBox1.Text);
        float LinesPerPage = 0;
        float YPosition = 0;
        int Count = 0;
        float LeftMargin = e.MarginBounds.Left;
        float TopMargin = e.MarginBounds.Top;
        string Line = null;
        Font PrintFont = SystemFonts.DefaultFont;
        System.Drawing.SolidBrush PrintBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);
        PrintServer ps = new PrintServer();
        //pd.PrinterSettings.PrinterName = printer;
        LinesPerPage = e.MarginBounds.Height / PrintFont.GetHeight(e.Graphics);
        //DefaultHttpHandler ip = new DefaultHttpHandler();
        while (Count < LinesPerPage && ((Line = reader.ReadLine()) != null))
        {
            YPosition = TopMargin + (Count * PrintFont.GetHeight(e.Graphics));
            e.Graphics.DrawString(Line, PrintFont, PrintBrush, LeftMargin, YPosition, new StringFormat());
            Count++;
        }
        if (Line != null)
        {
            e.HasMorePages = true;
        }
        else
        {
            e.HasMorePages = false;
        }
        PrintBrush.Dispose();
    }