PrintDocument实例所有的订阅事件如下:

  1. 创建一个PrintDocument的实例.如下: System.Drawing.Printing.PrintDocument docToPrint =     new System.Drawing.Printing.PrintDocument();
  2. 设置打印机开始打印的事件处理函数.函数原形如下: void docToPrint_PrintPage(object sender,     System.Drawing.Printing.PrintPageEventArgs e)
  3. 将事件处理函数添加到PrintDocument的PrintPage事件中。 docToPrint.PrintPage+=new PrintPageEventHandler(docToPrint_PrintPage);
  4. 设置PrintDocument的相关属性,如: PrintDialog1.AllowSomePages = true;PrintDialog1.ShowHelp = true;
  5. 把PrintDialog的Document属性设为上面配置好的PrintDocument的实例: PrintDialog1.Document = docToPrint;
  6. 调用PrintDialog的ShowDialog函数显示打印对话框: DialogResult result = PrintDialog1.ShowDialog();
  7. 根据用户的选择,开始打印: if (result==DialogResult.OK)    {     docToPrint.Print();    }
  8. 打印预览控件PrintPreviewDialog
  9. PrintPreviewControl 在窗体中添加打印预览

例子如下:

使用时先创建PrintService类的实例,然后调用void StartPrint(Stream streamToPrint,string streamType)函数开始打印。其中streamToPrint是要打印的内容(字节流),streamType是流的类型(txt表示普通文本,image表示图像);

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6. using System.Drawing.Printing;
  7. using System.Windows.Forms;
  8. using System.Drawing;
  9. namespace ConsoleApplication1
  10. {
  11. public partial class PrintTxt:Form
  12. {
  13. private   PrintPreviewDialog PrintPreview = new PrintPreviewDialog();
  14. private   string    StreamType;
  15. private   Image image = null;
  16. private   Stream StreamToPrint = null;
  17. Font mainFont = new Font("宋体", 12);//打印的字体
  18. public string Filename =null;
  19. //1、实例化打印文档
  20. PrintDocument pdDocument = new PrintDocument();
  21. private string[] lines;
  22. private PrintPreviewControl printPreviewControl1;
  23. public PrintTxt()
  24. {
  25. InitializeComponent();
  26. }
  27. private int linesPrinted;
  28. public PrintTxt(string filepath,string filetype):this()
  29. {
  30. Filename = Path.GetFileNameWithoutExtension(filepath);
  31. //订阅BeginPrint事件
  32. pdDocument.BeginPrint += new PrintEventHandler(pdDocument_BeginPrint);
  33. //訂閱EndPrint事件,释放资源
  34. pdDocument.PrintPage += new PrintPageEventHandler(OnPrintPage);
  35. //订阅Print打印事件,该方法必须放在订阅打印事件的最后
  36. FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
  37. StartPrint(fs, filetype);
  38. //打印结束
  39. pdDocument.EndPrint += new PrintEventHandler(pdDocument_EndPrint);
  40. }
  41. //2、启动Print打印方法
  42. public   void StartPrint(Stream streamToPrint, string streamType)
  43. {
  44. //声明返回值的PageSettings A4/A5
  45. PageSettings ps = new PageSettings();
  46. //显示设置打印页对话框
  47. PageSetupDialog Psdl = new PageSetupDialog();
  48. //打印多页设置
  49. PrintDialog pt = new PrintDialog();
  50. pt.AllowCurrentPage = true;
  51. pt.AllowSomePages = true;
  52. pt.AllowPrintToFile = true;
  53. printPreviewControl1.Document = pdDocument;//form中的打印预览
  54. printPreviewControl1.Zoom = 1.0;
  55. printPreviewControl1.Dock = DockStyle.Fill;
  56. printPreviewControl1.UseAntiAlias = true;
  57. StreamToPrint = streamToPrint;//打印的字节流
  58. StreamType = streamType; //打印的类型
  59. pdDocument.DocumentName = Filename; //打印的文件名
  60. Psdl.Document = pdDocument;
  61. PrintPreview.Document = pdDocument;
  62. PrintPreview.SetDesktopLocation(300, 800);
  63. Psdl.PageSettings = pdDocument.DefaultPageSettings;
  64. pt.Document = pdDocument;
  65. try
  66. {
  67. //显示对话框
  68. if (Psdl.ShowDialog() == DialogResult.OK)
  69. {
  70. ps = Psdl.PageSettings;
  71. pdDocument.DefaultPageSettings = Psdl.PageSettings;
  72. }
  73. if (pt.ShowDialog() == DialogResult.OK)
  74. {
  75. pdDocument.PrinterSettings.Copies = pt.PrinterSettings.Copies;
  76. }
  77. if (PrintPreview.ShowDialog() == DialogResult.OK)
  78. //调用打印
  79. pdDocument.Print();
  80. // PrintDocument对象的Print()方法在PrintController类中执行PrintPage事件。
  81. //
  82. }
  83. catch (InvalidPrinterException ex)
  84. {
  85. MessageBox.Show(ex.Message, "Simple Editor", MessageBoxButtons.OK, MessageBoxIcon.Error);
  86. throw;
  87. }
  88. }
  89. /// <summary>
  90. /// 3、得到打印內容
  91. /// 每个打印任务只调用OnBeginPrint()一次。
  92. /// </summary>
  93. /// <param name="sender"></param>
  94. /// <param name="e"></param>
  95. void pdDocument_BeginPrint(object sender, PrintEventArgs e)
  96. {
  97. char[] param = { '/n' };
  98. char[] trimParam = { '/r' };//回车
  99. switch (StreamType)
  100. {
  101. case "txt":
  102. StringBuilder text = new StringBuilder();
  103. System.IO.StreamReader streamReader = new StreamReader(StreamToPrint, Encoding.Default);
  104. while (streamReader.Peek() >= 0)
  105. {
  106. lines = streamReader.ReadToEnd().Split(param);
  107. for (int i = 0; i < lines.Length; i++)
  108. {
  109. lines[i] = lines[i].TrimEnd(trimParam);
  110. }
  111. }
  112. break;
  113. case "image":
  114. image = System.Drawing.Image.FromStream(StreamToPrint);
  115. break;
  116. default:
  117. break;
  118. }
  119. }
  120. /// <summary>
  121. /// 4、绘制多个打印界面
  122. /// printDocument的PrintPage事件
  123. /// </summary>
  124. /// <param name="sender"></param>
  125. /// <param name="e"></param>
  126. private void OnPrintPage(object sender, PrintPageEventArgs e)
  127. {
  128. int leftMargin = Convert.ToInt32((e.MarginBounds.Left) * 3 / 4);  //左边距
  129. int topMargin = Convert.ToInt32(e.MarginBounds.Top * 2 / 3);    //顶边距
  130. switch (StreamType)
  131. {
  132. case "txt":
  133. while (linesPrinted < lines.Length)
  134. {
  135. //向画布中填写内容
  136. e.Graphics.DrawString(lines[linesPrinted++], new Font("Arial", 10), Brushes.Black, leftMargin, topMargin, new StringFormat());
  137. topMargin += 55;//行高为55,可调整
  138. //走纸换页
  139. if (topMargin >= e.PageBounds.Height - 60)//页面累加的高度大于页面高度。根据自己需要,可以适当调整
  140. {
  141. //如果大于设定的高
  142. e.HasMorePages = true;
  143. printPreviewControl1.Rows += 1;//窗体的打印预览窗口页面自动加1
  144. /*
  145. * PrintPageEventArgs类的HaeMorePages属性为True时,通知控件器,必须再次調用OnPrintPage()方法,打印一个页面。
  146. * PrintLoopI()有一个用於每个要打印的页面的序例。如果HasMorePages是False,PrintLoop()就会停止。
  147. */
  148. return;
  149. }
  150. }
  151. break;
  152. case "image"://一下涉及剪切图片,
  153. int width = image.Width;
  154. int height = image.Height;
  155. if ((width / e.MarginBounds.Width) > (height / e.MarginBounds.Height))
  156. {
  157. width = e.MarginBounds.Width;
  158. height = image.Height * e.MarginBounds.Width / image.Width;
  159. }
  160. else
  161. {
  162. height = e.MarginBounds.Height;
  163. width = image.Width * e.MarginBounds.Height / image.Height;
  164. }
  165. System.Drawing.Rectangle destRect = new System.Drawing.Rectangle(topMargin, leftMargin, width, height);
  166. //向画布写入图片
  167. for (int i = 0; i < Convert.ToInt32(Math.Floor((double)image.Height/ 820)) + 1; i++)
  168. {
  169. e.Graphics.DrawImage(image, destRect, i*820,i*1170 , image.Width, image.Height, System.Drawing.GraphicsUnit.Pixel);
  170. //走纸换页
  171. if (i * 1170 >= e.PageBounds.Height - 60)//页面累加的高度大于页面高度。根据自己需要,可以适当调整
  172. {
  173. //如果大于设定的高
  174. e.HasMorePages = true;
  175. printPreviewControl1.Rows += 1;//窗体的打印预览窗口页面自动加1
  176. /*
  177. * PrintPageEventArgs类的HaeMorePages属性为True时,通知控件器,必须再次調用OnPrintPage()方法,打印一个页面。
  178. * PrintLoopI()有一个用於每个要打印的页面的序例。如果HasMorePages是False,PrintLoop()就会停止。
  179. */
  180. return;
  181. }
  182. }
  183. break;
  184. }
  185. //打印完毕后,画线条,且注明打印日期
  186. e.Graphics.DrawLine(new Pen(Color.Black), leftMargin, topMargin, e.MarginBounds.Right, topMargin);
  187. string strdatetime = DateTime.Now.ToLongDateString() + DateTime.Now.ToLongTimeString();
  188. e.Graphics.DrawString(string.Format("打印时间:{0}", strdatetime), mainFont, Brushes.Black, e.MarginBounds.Right-240, topMargin+40, new StringFormat());
  189. linesPrinted = 0;
  190. //绘制完成后,关闭多页打印功能
  191. e.HasMorePages = false;
  192. }
  193. /// <summary>
  194. ///5、EndPrint事件,释放资源
  195. /// </summary>
  196. /// <param name="sender"></param>
  197. /// <param name="e"></param>
  198. void pdDocument_EndPrint(object sender, PrintEventArgs e)
  199. {
  200. //变量Lines占用和引用的字符串数组,现在释放
  201. lines = null;
  202. }
  203. private void InitializeComponent()
  204. {
  205. this.printPreviewControl1 = new System.Windows.Forms.PrintPreviewControl();
  206. this.SuspendLayout();
  207. //
  208. // printPreviewControl1
  209. //
  210. this.printPreviewControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
  211. | System.Windows.Forms.AnchorStyles.Left)
  212. | System.Windows.Forms.AnchorStyles.Right)));
  213. this.printPreviewControl1.Location = new System.Drawing.Point(12, 3);
  214. this.printPreviewControl1.Name = "printPreviewControl1";
  215. this.printPreviewControl1.Size = new System.Drawing.Size(685, 511);
  216. this.printPreviewControl1.TabIndex = 0;
  217. //
  218. // PrintTxt
  219. //
  220. this.ClientSize = new System.Drawing.Size(696, 526);
  221. this.Controls.Add(this.printPreviewControl1);
  222. this.Name = "PrintTxt";
  223. this.ResumeLayout(false);
  224. }
  225. }
  226. //PrintTxt simple = new PrintTxt("D://Mainsoft//12.txt", "txt");
  227. }

调用方式 PrintTxt simple = new PrintTxt("D://Mainsoft//12.txt", "txt");

验证通过;

【转】C#使用PrintDocument打印 多页 打印预览的更多相关文章

  1. JAVA打印类(带预览)

    package tool; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; ...

  2. Lodop打印设计矩形重合预览线条变粗

    LODOP中的打印设计是辅助进行开发的,实际打印效果应以预览为准,很多效果都是在设计界面显示不出来,或设计和预览界面有差异.例如add_print_text文本的字间距.行间距,旋转,还有允许标点溢出 ...

  3. C#使用PrintDocument打印 多页 打印预览

    PrintDocument实例所有的订阅事件如下: 创建一个PrintDocument的实例.如下: System.Drawing.Printing.PrintDocument docToPrint ...

  4. .Net(c#)打印--多页打印

    如果要实现多页打印,就要使用PrintPageEventArgs类的HasMorePages属性. 我们对之前的代码作如下变更:      增加PrintDocument的BeginPrint和End ...

  5. ABAP FORM打印转PDF/pdf 预览

    function ZSTXBC_SSFCOMP_PDF_PREVIEW. *"-------------------------------------------------------- ...

  6. dedecms 去掉栏目页的预览功能

    首先找到include/typeunit.class.admin.php 再找到 ListAllType 方法,该方法的功能是“读出所有分类” 找到并将该方法内的所以以下代码注释或者删除”<a ...

  7. .NET网页打印以及使用打印需要注意的事项(可能会引起VS崩溃的现象、打印预览后关闭功能不管用)

    这两天进行给网页添加打印.打印预览.页面设置的功能.遇到了以下几个问题 [1]在网上查找了一些打印方法,一开始还可以用,后来不知道动到了哪里,点击vs中拆分或者切换到另一个设计和源代码显示方式,就会引 ...

  8. JS实现浏览器打印、打印预览

    1.JS实现打印的方式方式一:window.print()window.print();会弹出打印对话框,打印的是window.document.body.innerHTML中的内容,下面是从网上摘到 ...

  9. Chrome打开标签页预览

    类似于Microsoft Edge浏览器上的标签页缩略图预览非常方便,其实现在谷歌浏览器正在测试相关的功能,如果想提前体验,就在地址栏输入"chrome://flags"并按下回车 ...

随机推荐

  1. lr常见问题汇总(持续更新版)

    在使用mms协议的时候,会碰到报错 Action.c(): 错误: C 解释器运行时错误: Action.c (): Error -- Unresolved symbol : mms_play. 解决 ...

  2. 【CSS】规范大纲

    文件规范: 文件分类 : 通用类 :业务类. 文件引入:行内样式(不推荐):外联引入:内联引入.(避免使用Import引入) 文件本身:文件名. 编码:UTF-8. 注释规范: 块状注释:统一缩进,在 ...

  3. unix常用命令记录

    1. ls 命令:列出文件及文件夹 ls -a 列出目录下的所有文件,包括以 . 开头的隐含文件.ls -b 把文件名中不可输出的字符用反斜杠加字符编号(就象在C语言里一样)的形式列出.ls -c 输 ...

  4. CVPR 2013 关于图像/场景分类(classification)的文章paper list

    CVPR 2013 关于图像/场景分类(classification)的文章paper list 八14by 小军   这个搜罗了cvpr2013有关于classification的相关文章,自己得m ...

  5. Git常用的几个命令

    标签(空格分隔): Git 在本地文件系统中新建目录,放置你的工程: mk dir parkk cd parkk //进入该目录 git init //初始化自己的仓库,默认名称为master 在仓库 ...

  6. MT【126】点对个数两题之二【图论】

    在平面上有\(n\) 个点$S={x_1,x_2\cdots,x_n}, $ 证明在这 \(n\) 个点中距离为 \(1\) 的点对数不超过 \(\dfrac{n}{4}+\dfrac{2}{2}n^ ...

  7. 浅谈博弈论之Nim初步(xor正确性的浅显证明)

    引入 在许多地方曾流行过这样一个小游戏:摆出三堆硬币,分别包含3枚,5枚,7枚.两人轮流行动,每次可任选一堆,从中取走任意多枚硬币,可把一堆取光,但不能不取,取走最后一枚硬币者获胜. 概念 \(先手: ...

  8. 【刷题】HDU 6183 Color it

    Problem Description Do you like painting? Little D doesn't like painting, especially messy color pai ...

  9. Vue 中使用UEditor富文本编辑器-亲测可用-vue-ueditor-wrap

    其中UEditor中也存在不少错误,再引用过程中. 但是UEditor相对还是比较好用的一个富文本编辑器. vue-ueditor-wrap说明 Vue + UEditor + v-model 双向绑 ...

  10. 最新wireshark抓包教程

    http://jingyan.baidu.com/article/d71306350f213b13fdf475b9.html 大家都知道,sniffer是一款收费产品, 要真正的学会使用,因为有许多的 ...