照着书将打印文档的代码敲完,感觉还是有那么一点收获!虽然这是程序员不怎么喜欢的事情(照着别人的代码敲),但是没有办法;谁叫自己还是个菜鸟!下面是我敲的代码,给大家分享下:
using System.Drawing.Printing;///打印空间;
using System.IO;
namespace 打印操作
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string[] textLines;
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
int x = 20;
int y = 20;
foreach(string line in textLines){
e.Graphics.DrawString(line, new Font("Arial", 10),Brushes.Black,x,y);
y += 15;
}
}
/// <summary>
/// 开始
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void printDocument1_BeginPrint(object sender, PrintEventArgs e)
{
char[] param ={ '\n'};
textLines = richTextBox1.Text.Split(param);///对文件进行分割操作;
int i = 0;///去掉每个字符串后面的回车('\r');
foreach(string s in textLines){
textLines[i++] = s.TrimEnd('\r');
}
}
private void printDocument1_EndPrint(object sender, PrintEventArgs e)
{
}
private void 打开OToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if(ofd.ShowDialog()!=DialogResult.OK){
return;
}
richTextBox1.LoadFile(ofd.FileName, RichTextBoxStreamType.PlainText);
}
private void 打印PToolStripMenuItem_Click(object sender, EventArgs e)
{
PrintDialog pd = new PrintDialog();
pd.Document = printDocument1;
if (pd.ShowDialog() == DialogResult.OK)
{
try{
printDocument1.Print();///启用打印;
///
}
catch(Exception ex){
MessageBox.Show(ex.Message,"打印错误");
printDocument1.PrintController.OnEndPrint(printDocument1, new System.Drawing.Printing.PrintEventArgs());
}
}
}
private void 页面设置SToolStripMenuItem_Click(object sender, EventArgs e)
{
PageSetupDialog psd = new PageSetupDialog();
psd.Document = printDocument1;
psd.ShowDialog();
}
private void 打印预览KToolStripMenuItem_Click(object sender, EventArgs e)
{
PrintPreviewDialog printdg = new PrintPreviewDialog();
printdg.Document = printDocument1;
StringReader rd = new StringReader(richTextBox1.Text);
try {
printdg.ShowDialog();
}
catch(Exception ex){
MessageBox.Show(ex.Message,"打印错误!");
}
}
}
}