WPF 打印操作之PrintDocument,WPF獲取打印機列表,WPF指定打印機


一、WPF 打印操作之PrintDocument,WPF獲取打印機列表,WPF指定打印機

PrintDocument

定義一個可重用的對象,當從Windows Forms應用程序進行打印時,該對象將輸出發送到打印機

 

通常,您將創建PrintDocument的實例,設置諸如DocumentNamePrinterSettings之類的屬性,然后調用Print方法來啟動打印過程。通過使用PrintPageEventArgsGraphics Graphics屬性,在您指定要打印輸出的地方處理PrintPage事件

 

注意:使用此類需要提前安裝 System.Drawing.Common

 

更多參考:

https://docs.microsoft.com/en-us/dotnet/api/system.drawing.printing.printdocument?view=dotnet-plat-ext-3.1

 

二、wpf獲取系統可用打印機列表

 

//獲取打印機列表
StringCollection strList = PrinterSettings.InstalledPrinters;

 

 

使用打印機名稱,指定特定的打印機進行打印。

 PrintDocument pd = new PrintDocument();
pd.PrinterSettings.PrinterName = "Canon TS3100 series (副本 1)";

 

三、打印示例

Font printFont = null;
StreamReader streamToPrint = null;
private void Button_Click_1(object sender, RoutedEventArgs e)
{
    try
    {
        streamToPrint = new StreamReader
            ("G:\\桌面\\新建文本文檔.txt");
        try
        {
            printFont = new Font("Arial", 10);
            PrintDocument pd = new PrintDocument();
            pd.PrinterSettings.PrinterName = "Canon TS3100 series (副本 1)";
            pd.PrintPage += new PrintPageEventHandler
                (this.pd_PrintPage);
            pd.Print();
        }
        finally
        {
            streamToPrint.Close();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
// The PrintPage event is raised for each page to be printed.
private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
    float linesPerPage = 0;
    float yPos = 0;
    int count = 0;
    float leftMargin = ev.MarginBounds.Left;
    float topMargin = ev.MarginBounds.Top;
    string line = null;

    // Calculate the number of lines per page.
    linesPerPage = ev.MarginBounds.Height /
        printFont.GetHeight(ev.Graphics);

    // Print each line of the file.
    while (count < linesPerPage &&
        ((line = streamToPrint.ReadLine()) != null))
    {
        yPos = topMargin + (count *
            printFont.GetHeight(ev.Graphics));
        ev.Graphics.DrawString(line, printFont, System.Drawing.Brushes.Black,
            leftMargin, yPos, new StringFormat());
        count++;
    }

    // If more lines exist, print another page.
    if (line != null)
        ev.HasMorePages = true;
    else
        ev.HasMorePages = false;
}

 

 

更多:

WPF 打印操作之PrintDialog

WPF 皮膚之MathApps.Metro UI庫

WPF RichTextBox滾動條自動滾動實例、文本自動滾動實例


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM