int sub = 0;html
private void printText(string text, System.Drawing.Printing.PrintPageEventArgs e)ide
{字體
//取得Graphics實例this
Graphics g = e.Graphics;url
//得到相關點座標、長度、寬度spa
int x = e.PageSettings.Margins.Left;orm
int y = e.PageSettings.Margins.Right;htm
int width = e.PageSettings.PaperSize.Width - e.PageSettings.Margins.Left - e.PageSettings.Margins.Right;對象
int height = e.PageSettings.PaperSize.Height - e.PageSettings.Margins.Top - e.PageSettings.Margins.Bottom;blog
int charnum;
int line;
//設置字體
Font font = new Font("宋體",15);
//打印string
g.MeasureString(text.Substring(sub), font, new SizeF(width, height - 10), new StringFormat(), out charnum, out line);
//設置截取位置
g.DrawString(text.Substring(sub), font, Brushes.Black, new RectangleF(x, y, width, height), new StringFormat());
sub += charnum;
if (sub < this.textBox1.Text.Length)
{
e.HasMorePages = true;
}
else
{
e.HasMorePages = false;
sub = 0;
}
}
//打印預覽
private void button1_Click(object sender, EventArgs e)
{
//注意指定其Document(獲取或設置要預覽的文檔)屬性
this.printPreviewDialog1.Document = this.printDocument1;
//ShowDialog方法:將窗體顯示爲模式對話框,並將當前活動窗口設置爲它的全部者
this.printPreviewDialog1.ShowDialog();
}
//打印
private void button2_Click(object sender, EventArgs e)
{
//注意指定Document(獲取或設置一個值)屬性
this.printDialog1.Document = this.printDocument1;
//ShowDialog方法:用默認的全部者運行通用對話框
if (this.printDialog1.ShowDialog() == DialogResult.OK)
{ //DialogResult指定標識符以指定對話框的返回值
//觸發PrintDocument的PrintPage事件
this.printDocument1.Print(); //Print方法:開始文檔的打印進程
}
}
//printDocument1控件的PrintPage事件(雙擊printDocument1控件生成)
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
printText(textBox1.Text, e); //打印文本
e.Graphics.DrawImage(pictureBox1.Image, 20, 20); //打印圖片
}
// printDocument1控件:定義一個向打印機發送輸出的對象;
// printDialog1控件:顯示一個對話框,容許用戶選擇打印機並選擇其餘打印選項;
// printPreviewDialog1控件:顯示一個對話框,向用戶顯示關聯文檔打印時的樣子;