在開始編碼之前先了解PrintDocument的幾個方法,如下:
打印文本的基本邏輯如下
PrintDocument pdDocument = new PrintDocument(); pdDocument.PrintPage += new PrintPageEventHandler(OnPrintPage); private void OnPrintPage(object sender, PrintPageEventArgs e) { int leftMargin = Convert.ToInt32((e.MarginBounds.Left) * 3 / 4); //左邊距 int topMargin = Convert.ToInt32(e.MarginBounds.Top * 2 / 3); //頂邊距 while (linesPrinted < lines.Length) { e.Graphics.DrawString("你好", new Font("黑體", 10), Brushes.Black, leftMargin, topMargin); } }
如果需要打印的文本比較長,使用上述打印方式就會出現文字內容不全的問題,此時需要能夠打印多頁的功能
大致思路是將文本按照一個分隔符將文本分割成數組在OnPrintPage方法中給每一行計算一個高度,判斷高度是否超出文檔頁高度,如果超出則設置新一頁
PrintDocument pdDocument = new PrintDocument();//聲明一個文檔 private string[] lines;//存儲文本數組
private int linesPrinted;//記錄行數 pdDocument.BeginPrint += new PrintEventHandler(pdDocument_BeginPrint); pdDocument.PrintPage += new PrintPageEventHandler(OnPrintPage); /// <summary> /// 得到打印內容 /// 每個打印任務只調用OnBeginPrint()一次。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void pdDocument_BeginPrint(object sender, PrintEventArgs e) { lines = this.richTextBox1.Text.Split(new string[1] { "\n" }, StringSplitOptions.None); } /// <summary> /// 繪制多個打印界面 /// printDocument的PrintPage事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnPrintPage(object sender, PrintPageEventArgs e) { int leftMargin = Convert.ToInt32((e.MarginBounds.Left) * 3 / 4); //左邊距 int topMargin = Convert.ToInt32(e.MarginBounds.Top * 2 / 3); //頂邊距 while (linesPrinted < lines.Length) { e.Graphics.DrawString(lines[linesPrinted++], new Font("黑體", 10), Brushes.Black, leftMargin, topMargin); topMargin += 25;//行高為55,可調整 //頁面累加的高度大於頁面高度。根據自己需要,可以適當調整 if (topMargin >= e.PageBounds.Height - 60) { //如果大於設定的高 e.HasMorePages = true; /* * PrintPageEventArgs類的HaeMorePages屬性為True時,通知控件器,必須再次調用OnPrintPage()方法,打印一個頁面。 * PrintLoopI()有一個用於每個要打印的頁面的序例。如果HasMorePages是False,PrintLoop()就會停止。 */ return; } } linesPrinted = 0; //繪制完成后,關閉多頁打印功能 e.HasMorePages = false; }
e.Graphics.DrawString(lines[linesPrinted++], new Font("黑體", 10), Brushes.Black, leftMargin, topMargin);
方法有多個重載,如果需要指定保留文本格式,則使用
public void DrawString(string s, Font font, Brush brush, float x, float y, StringFormat format)
默認文本格式(文本的原有格式)
public void DrawString(string s, Font font, Brush brush, float x, float y)
打印效果,下圖為縮略圖有4頁文檔被輸出成PDF
//聲明一個文檔