C#使用PrintDocument打印 多页 打印预览
PrintDocument实例所有的订阅事件如下:
- 创建一个PrintDocument的实例.如下: System.Drawing.Printing.PrintDocument docToPrint =
new System.Drawing.Printing.PrintDocument(); - 设置打印机开始打印的事件处理函数.函数原形如下: void docToPrint_PrintPage(object sender,
System.Drawing.Printing.PrintPageEventArgs e) - 将事件处理函数添加到PrintDocument的PrintPage事件中。 docToPrint.PrintPage+=new PrintPageEventHandler(docToPrint_PrintPage);
- 设置PrintDocument的相关属性,如: PrintDialog1.AllowSomePages = true;PrintDialog1.ShowHelp = true;
- 把PrintDialog的Document属性设为上面配置好的PrintDocument的实例: PrintDialog1.Document = docToPrint;
- 调用PrintDialog的ShowDialog函数显示打印对话框: DialogResult result = PrintDialog1.ShowDialog();
- 根据用户的选择,开始打印: if (result==DialogResult.OK) { docToPrint.Print(); }
- 打印预览控件PrintPreviewDialog
- PrintPreviewControl 在窗体中添加打印预览
例子如下:
使用时先创建PrintService类的实例,然后调用void StartPrint(Stream streamToPrint,string streamType)函数开始打印。其中streamToPrint是要打印的内容(字节流),streamType是流的类型(txt表示普通文本,image表示图像);
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.IO;
- using System.Drawing.Printing;
- using System.Windows.Forms;
- using System.Drawing;
- namespace ConsoleApplication1
- {
- public partial class PrintTxt:Form
- {
- private PrintPreviewDialog PrintPreview = new PrintPreviewDialog();
- private string StreamType;
- private Image image = null;
- private Stream StreamToPrint = null;
- Font mainFont = new Font("宋体", 12);//打印的字体
- public string Filename =null;
- //1、实例化打印文档
- PrintDocument pdDocument = new PrintDocument();
- private string[] lines;
- private PrintPreviewControl printPreviewControl1;
- public PrintTxt()
- {
- InitializeComponent();
- }
- private int linesPrinted;
- public PrintTxt(string filepath,string filetype):this()
- {
- Filename = Path.GetFileNameWithoutExtension(filepath);
- //订阅BeginPrint事件
- pdDocument.BeginPrint += new PrintEventHandler(pdDocument_BeginPrint);
- //訂閱EndPrint事件,释放资源
- pdDocument.PrintPage += new PrintPageEventHandler(OnPrintPage);
- //订阅Print打印事件,该方法必须放在订阅打印事件的最后
- FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
- StartPrint(fs, filetype);
- //打印结束
- pdDocument.EndPrint += new PrintEventHandler(pdDocument_EndPrint);
- }
- //2、启动Print打印方法
- public void StartPrint(Stream streamToPrint, string streamType)
- {
- //声明返回值的PageSettings A4/A5
- PageSettings ps = new PageSettings();
- //显示设置打印页对话框
- PageSetupDialog Psdl = new PageSetupDialog();
- //打印多页设置
- PrintDialog pt = new PrintDialog();
- pt.AllowCurrentPage = true;
- pt.AllowSomePages = true;
- pt.AllowPrintToFile = true;
- printPreviewControl1.Document = pdDocument;//form中的打印预览
- printPreviewControl1.Zoom = 1.0;
- printPreviewControl1.Dock = DockStyle.Fill;
- printPreviewControl1.UseAntiAlias = true;
- StreamToPrint = streamToPrint;//打印的字节流
- StreamType = streamType; //打印的类型
- pdDocument.DocumentName = Filename; //打印的文件名
- Psdl.Document = pdDocument;
- PrintPreview.Document = pdDocument;
- PrintPreview.SetDesktopLocation(300, 800);
- Psdl.PageSettings = pdDocument.DefaultPageSettings;
- pt.Document = pdDocument;
- try
- {
- //显示对话框
- if (Psdl.ShowDialog() == DialogResult.OK)
- {
- ps = Psdl.PageSettings;
- pdDocument.DefaultPageSettings = Psdl.PageSettings;
- }
- if (pt.ShowDialog() == DialogResult.OK)
- {
- pdDocument.PrinterSettings.Copies = pt.PrinterSettings.Copies;
- }
- if (PrintPreview.ShowDialog() == DialogResult.OK)
- //调用打印
- pdDocument.Print();
- // PrintDocument对象的Print()方法在PrintController类中执行PrintPage事件。
- //
- }
- catch (InvalidPrinterException ex)
- {
- MessageBox.Show(ex.Message, "Simple Editor", MessageBoxButtons.OK, MessageBoxIcon.Error);
- throw;
- }
- }
- /// <summary>
- /// 3、得到打印內容
- /// 每个打印任务只调用OnBeginPrint()一次。
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- void pdDocument_BeginPrint(object sender, PrintEventArgs e)
- {
- char[] param = { '/n' };
- char[] trimParam = { '/r' };//回车
- switch (StreamType)
- {
- case "txt":
- StringBuilder text = new StringBuilder();
- System.IO.StreamReader streamReader = new StreamReader(StreamToPrint, Encoding.Default);
- while (streamReader.Peek() >= 0)
- {
- lines = streamReader.ReadToEnd().Split(param);
- for (int i = 0; i < lines.Length; i++)
- {
- lines[i] = lines[i].TrimEnd(trimParam);
- }
- }
- break;
- case "image":
- image = System.Drawing.Image.FromStream(StreamToPrint);
- break;
- default:
- break;
- }
- }
- /// <summary>
- /// 4、绘制多个打印界面
- /// 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); //顶边距
- switch (StreamType)
- {
- case "txt":
- while (linesPrinted < lines.Length)
- {
- //向画布中填写内容
- e.Graphics.DrawString(lines[linesPrinted++], new Font("Arial", 10), Brushes.Black, leftMargin, topMargin, new StringFormat());
- topMargin += 55;//行高为55,可调整
- //走纸换页
- if (topMargin >= e.PageBounds.Height - 60)//页面累加的高度大于页面高度。根据自己需要,可以适当调整
- {
- //如果大于设定的高
- e.HasMorePages = true;
- printPreviewControl1.Rows += 1;//窗体的打印预览窗口页面自动加1
- /*
- * PrintPageEventArgs类的HaeMorePages属性为True时,通知控件器,必须再次調用OnPrintPage()方法,打印一个页面。
- * PrintLoopI()有一个用於每个要打印的页面的序例。如果HasMorePages是False,PrintLoop()就会停止。
- */
- return;
- }
- }
- break;
- case "image"://一下涉及剪切图片,
- int width = image.Width;
- int height = image.Height;
- if ((width / e.MarginBounds.Width) > (height / e.MarginBounds.Height))
- {
- width = e.MarginBounds.Width;
- height = image.Height * e.MarginBounds.Width / image.Width;
- }
- else
- {
- height = e.MarginBounds.Height;
- width = image.Width * e.MarginBounds.Height / image.Height;
- }
- System.Drawing.Rectangle destRect = new System.Drawing.Rectangle(topMargin, leftMargin, width, height);
- //向画布写入图片
- for (int i = 0; i < Convert.ToInt32(Math.Floor((double)image.Height/ 820)) + 1; i++)
- {
- e.Graphics.DrawImage(image, destRect, i*820,i*1170 , image.Width, image.Height, System.Drawing.GraphicsUnit.Pixel);
- //走纸换页
- if (i * 1170 >= e.PageBounds.Height - 60)//页面累加的高度大于页面高度。根据自己需要,可以适当调整
- {
- //如果大于设定的高
- e.HasMorePages = true;
- printPreviewControl1.Rows += 1;//窗体的打印预览窗口页面自动加1
- /*
- * PrintPageEventArgs类的HaeMorePages属性为True时,通知控件器,必须再次調用OnPrintPage()方法,打印一个页面。
- * PrintLoopI()有一个用於每个要打印的页面的序例。如果HasMorePages是False,PrintLoop()就会停止。
- */
- return;
- }
- }
- break;
- }
- //打印完毕后,画线条,且注明打印日期
- e.Graphics.DrawLine(new Pen(Color.Black), leftMargin, topMargin, e.MarginBounds.Right, topMargin);
- string strdatetime = DateTime.Now.ToLongDateString() + DateTime.Now.ToLongTimeString();
- e.Graphics.DrawString(string.Format("打印时间:{0}", strdatetime), mainFont, Brushes.Black, e.MarginBounds.Right-240, topMargin+40, new StringFormat());
- linesPrinted = 0;
- //绘制完成后,关闭多页打印功能
- e.HasMorePages = false;
- }
- /// <summary>
- ///5、EndPrint事件,释放资源
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- void pdDocument_EndPrint(object sender, PrintEventArgs e)
- {
- //变量Lines占用和引用的字符串数组,现在释放
- lines = null;
- }
- private void InitializeComponent()
- {
- this.printPreviewControl1 = new System.Windows.Forms.PrintPreviewControl();
- this.SuspendLayout();
- //
- // printPreviewControl1
- //
- this.printPreviewControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
- | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
- this.printPreviewControl1.Location = new System.Drawing.Point(12, 3);
- this.printPreviewControl1.Name = "printPreviewControl1";
- this.printPreviewControl1.Size = new System.Drawing.Size(685, 511);
- this.printPreviewControl1.TabIndex = 0;
- //
- // PrintTxt
- //
- this.ClientSize = new System.Drawing.Size(696, 526);
- this.Controls.Add(this.printPreviewControl1);
- this.Name = "PrintTxt";
- this.ResumeLayout(false);
- }
- }
- //PrintTxt simple = new PrintTxt("D://Mainsoft//12.txt", "txt");
- }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing.Printing;
using System.Windows.Forms;
using System.Drawing;
namespace ConsoleApplication1
{
public partial class PrintTxt:Form
{
private PrintPreviewDialog PrintPreview = new PrintPreviewDialog();
private string StreamType;
private Image image = null;
private Stream StreamToPrint = null;
Font mainFont = new Font("宋体", 12);//打印的字体
public string Filename =null;
//1、实例化打印文档
PrintDocument pdDocument = new PrintDocument();
private string[] lines;
private PrintPreviewControl printPreviewControl1;
public PrintTxt()
{
InitializeComponent();
}
private int linesPrinted;
public PrintTxt(string filepath,string filetype):this()
{
Filename = Path.GetFileNameWithoutExtension(filepath);
//订阅BeginPrint事件
pdDocument.BeginPrint += new PrintEventHandler(pdDocument_BeginPrint);
//訂閱EndPrint事件,释放资源
pdDocument.PrintPage += new PrintPageEventHandler(OnPrintPage);
//订阅Print打印事件,该方法必须放在订阅打印事件的最后
FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
StartPrint(fs, filetype);
//打印结束
pdDocument.EndPrint += new PrintEventHandler(pdDocument_EndPrint);
}
//2、启动Print打印方法
public void StartPrint(Stream streamToPrint, string streamType)
{
//声明返回值的PageSettings A4/A5
PageSettings ps = new PageSettings();
//显示设置打印页对话框
PageSetupDialog Psdl = new PageSetupDialog();
//打印多页设置
PrintDialog pt = new PrintDialog();
pt.AllowCurrentPage = true;
pt.AllowSomePages = true;
pt.AllowPrintToFile = true;
printPreviewControl1.Document = pdDocument;//form中的打印预览
printPreviewControl1.Zoom = 1.0;
printPreviewControl1.Dock = DockStyle.Fill;
printPreviewControl1.UseAntiAlias = true;
StreamToPrint = streamToPrint;//打印的字节流
StreamType = streamType; //打印的类型
pdDocument.DocumentName = Filename; //打印的文件名
Psdl.Document = pdDocument;
PrintPreview.Document = pdDocument;
PrintPreview.SetDesktopLocation(300, 800);
Psdl.PageSettings = pdDocument.DefaultPageSettings;
pt.Document = pdDocument;
try
{
//显示对话框
if (Psdl.ShowDialog() == DialogResult.OK)
{
ps = Psdl.PageSettings;
pdDocument.DefaultPageSettings = Psdl.PageSettings;
}
if (pt.ShowDialog() == DialogResult.OK)
{
pdDocument.PrinterSettings.Copies = pt.PrinterSettings.Copies;
}
if (PrintPreview.ShowDialog() == DialogResult.OK)
//调用打印
pdDocument.Print();
// PrintDocument对象的Print()方法在PrintController类中执行PrintPage事件。
//
}
catch (InvalidPrinterException ex)
{
MessageBox.Show(ex.Message, "Simple Editor", MessageBoxButtons.OK, MessageBoxIcon.Error);
throw;
}
}
/// <summary>
/// 3、得到打印內容
/// 每个打印任务只调用OnBeginPrint()一次。
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void pdDocument_BeginPrint(object sender, PrintEventArgs e)
{
char[] param = { '/n' };
char[] trimParam = { '/r' };//回车
switch (StreamType)
{
case "txt":
StringBuilder text = new StringBuilder();
System.IO.StreamReader streamReader = new StreamReader(StreamToPrint, Encoding.Default);
while (streamReader.Peek() >= 0)
{
lines = streamReader.ReadToEnd().Split(param);
for (int i = 0; i < lines.Length; i++)
{
lines[i] = lines[i].TrimEnd(trimParam);
}
}
break;
case "image":
image = System.Drawing.Image.FromStream(StreamToPrint);
break;
default:
break;
}
}
/// <summary>
/// 4、绘制多个打印界面
/// 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); //顶边距
switch (StreamType)
{
case "txt":
while (linesPrinted < lines.Length)
{
//向画布中填写内容
e.Graphics.DrawString(lines[linesPrinted++], new Font("Arial", 10), Brushes.Black, leftMargin, topMargin, new StringFormat());
topMargin += 55;//行高为55,可调整
//走纸换页
if (topMargin >= e.PageBounds.Height - 60)//页面累加的高度大于页面高度。根据自己需要,可以适当调整
{
//如果大于设定的高
e.HasMorePages = true;
printPreviewControl1.Rows += 1;//窗体的打印预览窗口页面自动加1
/*
* PrintPageEventArgs类的HaeMorePages属性为True时,通知控件器,必须再次調用OnPrintPage()方法,打印一个页面。
* PrintLoopI()有一个用於每个要打印的页面的序例。如果HasMorePages是False,PrintLoop()就会停止。
*/
return;
}
}
break;
case "image"://一下涉及剪切图片,
int width = image.Width;
int height = image.Height;
if ((width / e.MarginBounds.Width) > (height / e.MarginBounds.Height))
{
width = e.MarginBounds.Width;
height = image.Height * e.MarginBounds.Width / image.Width;
}
else
{
height = e.MarginBounds.Height;
width = image.Width * e.MarginBounds.Height / image.Height;
}
System.Drawing.Rectangle destRect = new System.Drawing.Rectangle(topMargin, leftMargin, width, height);
//向画布写入图片
for (int i = 0; i < Convert.ToInt32(Math.Floor((double)image.Height/ 820)) + 1; i++)
{
e.Graphics.DrawImage(image, destRect, i*820,i*1170 , image.Width, image.Height, System.Drawing.GraphicsUnit.Pixel);
//走纸换页
if (i * 1170 >= e.PageBounds.Height - 60)//页面累加的高度大于页面高度。根据自己需要,可以适当调整
{
//如果大于设定的高
e.HasMorePages = true;
printPreviewControl1.Rows += 1;//窗体的打印预览窗口页面自动加1
/*
* PrintPageEventArgs类的HaeMorePages属性为True时,通知控件器,必须再次調用OnPrintPage()方法,打印一个页面。
* PrintLoopI()有一个用於每个要打印的页面的序例。如果HasMorePages是False,PrintLoop()就会停止。
*/
return;
}
}
break;
}
//打印完毕后,画线条,且注明打印日期
e.Graphics.DrawLine(new Pen(Color.Black), leftMargin, topMargin, e.MarginBounds.Right, topMargin);
string strdatetime = DateTime.Now.ToLongDateString() + DateTime.Now.ToLongTimeString();
e.Graphics.DrawString(string.Format("打印时间:{0}", strdatetime), mainFont, Brushes.Black, e.MarginBounds.Right-240, topMargin+40, new StringFormat());
linesPrinted = 0;
//绘制完成后,关闭多页打印功能
e.HasMorePages = false;
}
/// <summary>
///5、EndPrint事件,释放资源
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void pdDocument_EndPrint(object sender, PrintEventArgs e)
{
//变量Lines占用和引用的字符串数组,现在释放
lines = null;
}
private void InitializeComponent()
{
this.printPreviewControl1 = new System.Windows.Forms.PrintPreviewControl();
this.SuspendLayout();
//
// printPreviewControl1
//
this.printPreviewControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.printPreviewControl1.Location = new System.Drawing.Point(12, 3);
this.printPreviewControl1.Name = "printPreviewControl1";
this.printPreviewControl1.Size = new System.Drawing.Size(685, 511);
this.printPreviewControl1.TabIndex = 0;
//
// PrintTxt
//
this.ClientSize = new System.Drawing.Size(696, 526);
this.Controls.Add(this.printPreviewControl1);
this.Name = "PrintTxt";
this.ResumeLayout(false);
}
}
//PrintTxt simple = new PrintTxt("D://Mainsoft//12.txt", "txt");
}
调用方式 PrintTxt simple = new PrintTxt("D://Mainsoft//12.txt", "txt");
验证通过;
来自:http://blog.csdn.net/tsapi/article/details/6237695
C#使用PrintDocument打印 多页 打印预览的更多相关文章
- JAVA打印类(带预览)
package tool; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; ...
- Lodop打印设计矩形重合预览线条变粗
LODOP中的打印设计是辅助进行开发的,实际打印效果应以预览为准,很多效果都是在设计界面显示不出来,或设计和预览界面有差异.例如add_print_text文本的字间距.行间距,旋转,还有允许标点溢出 ...
- 【转】C#使用PrintDocument打印 多页 打印预览
PrintDocument实例所有的订阅事件如下: 创建一个PrintDocument的实例.如下: System.Drawing.Printing.PrintDocument docToPrint ...
- .Net(c#)打印--多页打印
如果要实现多页打印,就要使用PrintPageEventArgs类的HasMorePages属性. 我们对之前的代码作如下变更: 增加PrintDocument的BeginPrint和End ...
- ABAP FORM打印转PDF/pdf 预览
function ZSTXBC_SSFCOMP_PDF_PREVIEW. *"-------------------------------------------------------- ...
- dedecms 去掉栏目页的预览功能
首先找到include/typeunit.class.admin.php 再找到 ListAllType 方法,该方法的功能是“读出所有分类” 找到并将该方法内的所以以下代码注释或者删除”<a ...
- .NET网页打印以及使用打印需要注意的事项(可能会引起VS崩溃的现象、打印预览后关闭功能不管用)
这两天进行给网页添加打印.打印预览.页面设置的功能.遇到了以下几个问题 [1]在网上查找了一些打印方法,一开始还可以用,后来不知道动到了哪里,点击vs中拆分或者切换到另一个设计和源代码显示方式,就会引 ...
- JS实现浏览器打印、打印预览
1.JS实现打印的方式方式一:window.print()window.print();会弹出打印对话框,打印的是window.document.body.innerHTML中的内容,下面是从网上摘到 ...
- Chrome打开标签页预览
类似于Microsoft Edge浏览器上的标签页缩略图预览非常方便,其实现在谷歌浏览器正在测试相关的功能,如果想提前体验,就在地址栏输入"chrome://flags"并按下回车 ...
随机推荐
- LuoguP1351 联合权值 (枚举)
题目链接 枚举每个点,遍历和他相邻的点,然后答案一边更新就可以了. 最大值的时候一定是两个最大值相乘,一边遍历一边记录就好了. 时间复杂度.\(O(n)\) #include <iostream ...
- 【树状数组 离散化】bzoj1573: [Usaco2009 Open]牛绣花cowemb
解方程题! Description Bessie学会了刺绣这种精细的工作.牛们在一片半径为d(1 <= d <= 50000)的圆形布上绣花. 它们一共绣了N (2 <= N < ...
- windows 下phpstudy 升级mysql版本5.7
今天在导入sql文件的时候遇到了sql执行错误.最后找到原因是因为mysql版本过低,导致出错 原因:在执行sql的时候出现了两次CURRENT_TIMESTAMP ,最后得知在5.7版本之前都是不支 ...
- Vue的响应式规则
对象属性的响应规则 <body> <div id="root"> {{msg}} </div> </body> <script ...
- Python3与SQLServer、Oracle、MySql的连接方法
环境: python3.4 64bit pycharm2018社区版 64bit Oracle 11 64bit SQLServer· Mysql 其中三种不同的数据库安装在不同的服务器上,通过局域网 ...
- PAT Basic 1038
1038 统计同成绩学生 本题要求读入N名学生的成绩,将获得某一给定分数的学生人数输出. 输入格式: 输入在第1行给出不超过10^5^的正整数N,即学生总人数.随后1行给出N名学生的百分制整数成绩,中 ...
- Web Best Practices
Web Best Practices General Google WebFundamentals - Github JavaScript Style Guide - Github Google In ...
- Disqus 升级到3.0以上版本的评论同步问题
Disqus从2.*升级3.*时,Knowlege Base的文章不显示Disqus评论, 解决方法:在Disqus的Advanced Settings中勾选Render Comments JavaS ...
- POJ-3352 Road Construction,tarjan缩点求边双连通!
Road Construction 本来不想做这个题,下午总结的时候发现自己花了一周的时间学连通图却连什么是边双连通不清楚,于是百度了一下相关内容,原来就是一个点到另一个至少有两条不同的路. 题意:给 ...
- POJ 1056 IMMEDIATE DECODABILITY
IMMEDIATE DECODABILITY Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 9630 Accepted: ...