C#打印(PrintDocument、PrintDialog、PageSetupDialog、PrintPreviewDialog)


 這幾天一直在弄C#打印,下面整理過后的打印范例,主要介紹了PrintDocument的主要屬性、方法的應用。及打印過程中可能用的到得PrintDialog、PageSetupDialog、PrintPreviewDialog對話框。
代碼:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;

namespace demo
{
public partial class PrintOther : Form
{

public PrintOther()
{
InitializeComponent();
}

// PrintDocument類是實現打印功能的核心,它封裝了打印有關的屬性、事件、和方法
PrintDocument printDocument = new PrintDocument();

private void btnPrint_Click( object sender, EventArgs e)
{
// printDocument.PrinterSettings可以獲取或設置計算機默認打印相關屬性或參數,如:printDocument.PrinterSettings.PrinterName獲得默認打印機打印機名稱
// printDocument.DefaultPageSettings // 可以獲取或設置打印頁面參數信息、如是紙張大小,是否橫向打印等

// 設置文檔名
printDocument.DocumentName = " 處方箋 " ; // 設置完后可在打印對話框及隊列中顯示(默認顯示document)

// 設置紙張大小(可以不設置取,取默認設置)
PaperSize ps = new PaperSize( " Your Paper Name " , 100 , 70 );
ps.RawKind
= 150 ; // 如果是自定義紙張,就要大於118,(A4值為9,詳細紙張類型與值的對照請看http: // msdn.microsoft.com/zh-tw/library/system.drawing.printing.papersize.rawkind(v=vs.85).aspx)
printDocument.DefaultPageSettings.PaperSize = ps;

// 打印開始前
printDocument.BeginPrint += new PrintEventHandler(printDocument_BeginPrint);
// 打印輸出(過程)
printDocument.PrintPage += new PrintPageEventHandler(printDocument_PrintPage);
// 打印結束
printDocument.EndPrint += new PrintEventHandler(printDocument_EndPrint);

// 跳出打印對話框,提供打印參數可視化設置,如選擇哪個打印機打印此文檔等
PrintDialog pd = new PrintDialog();
pd.Document
= printDocument;
if (DialogResult.OK == pd.ShowDialog()) // 如果確認,將會覆蓋所有的打印參數設置
{
// 頁面設置對話框(可以不使用,其實PrintDialog對話框已提供頁面設置)
PageSetupDialog psd = new PageSetupDialog();
psd.Document
= printDocument;
if (DialogResult.OK == psd.ShowDialog())
{
// 打印預覽
PrintPreviewDialog ppd = new PrintPreviewDialog();
ppd.Document
= printDocument;
if (DialogResult.OK == ppd.ShowDialog())
printDocument.Print();
// 打印
}
}
}

void printDocument_BeginPrint( object sender, PrintEventArgs e)
{
// 也可以把一些打印的參數放在此處設置
}

void printDocument_PrintPage( object sender, PrintPageEventArgs e)
{
// 打印啥東東就在這寫了
Graphics g = e.Graphics;
Brush b
= new SolidBrush(Color.Black);
Font titleFont
= new Font( " 宋體 " , 16 );
string title = " 社區衛生服務站 處方箋 " ;
g.DrawString(title, titleFont, b,
new PointF((e.PageBounds.Width - g.MeasureString(title, titleFont).Width) / 2 , 20 ));

// e.Cancel // 獲取或設置是否取消打印
// e.HasMorePages // 為true時,該函數執行完畢后還會重新執行一遍(可用於動態分頁)
}

void printDocument_EndPrint( object sender, PrintEventArgs e)
{
// 打印結束后相關操作
}
}
}


免責聲明!

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



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