FormPrint.cs /* Created by SharpDevelop. * Developed by: Juergen Thomas, Berlin (Germany) * email adress: post(at)vs-polis.de * * Provided for NET 1.1 and 2.0 * ---------------------------- * To adapt the code for the used version, change the #define instructions. * * Project: general tool to print or save a form or any other control * * License: you can use this code 'as is' without any warrenty. * * Description * ----------- * http://www.codeproject.com/csharp/FormPrintPackage.asp (English) * http://www.mycsharp.de/wbb2/thread.php?threadid=29704 (deutsch) * * History * ------- * 12/17/2006 * First version * * 12/19/2006 * 1. added: clearing resources (Bitmap, Graphics) * 2. added: printing as portrait or landscape * 3. added: another method Execute() to decide printing either portrait or landscape * * 12/23/2006 * 1. changed: a shorter way to copy the control's graphics to the bitmap * 2. comment changed: at present, no adaptation to NET 1.1 * * 12/25/2006 * 1. added: copy the control's graphics to the bitmap with NET 1.1 * 2. changed: variables and methods are grouped newly, * but with no other features * 3. comment changed: adaptation to NET 1.1 * 4. commend added: known problems * * 01/13/2007 * 1. NET 1.1 changed: form can be printed including title and menu bar * 2. changed: public method Execute() splitted to Print() resp. Save() * 3. changed: Print() allows several parameters: PrinterName, Margins, Orientation * 4. changed: printing can compress to papersize with margins if necessary * 5. changed: most of the parameters can be omitted * 6. changed: printer memory problem managed by converting * to PixelFormat.Format8bppIndexed and GrayScaled bitmap * instead of colored PixelFormat.Canonical * 7. changed: Execute() uses progress label while printing a large control * (more than 40000 pixels, e.g. 200x200) * 8. changed: private method Execute() splitted to StartPrinting() resp. StartSaving() * * 01/22/2007 * 1. changed: use #define to change NET version * 2. changed: converting to PixelFormat.Format8bppIndexed now managed * by enum ColorDepthReduction * * 03/22/2007 * RichTextBox and WebBrowser cannot be copied by Control.DrawToBitmap(); therefore * we need DllImport("gdi32.dll") both, for NET 1.1 and NET 2.0 * this leeds to the following changes: * 1. changed using System.Runtime.InteropServices; for NET 2.0, too * 2. renamed GetBitmap() for NET 1.1 to GetBitmapGdi() * FormPrint calls GetBitmap() and leeds to GetBitmapGdi() * 3. changed GetBitmap() for NET 2.0 isn't used in all situations: * does Control contain any RichTextBox or WebBrowser Control? * true => FormPrint calls GetBitmapGdi() * false => FormPrint calls GetBitmap() using DrawToBitmap() * * */
最简单的方法 ,如果是没有滚动条的, 用 Graphics.CopyFRomScreen( new Point (10,10),new Point(0,0),Size) try { setButtonStatus(false); //把按钮等不显示的东东HIDE image = new Bitmap(this.Width-10, this.Height-90);//从窗体的哪里开始 using (Graphics g = Graphics.FromImage(image)) { Point pt1 = new Point(this.Location.X + 5, this.Location.Y + 70); g.CopyFromScreen(pt1, new Point(0, 0), new Size (this .Width -10,this .Height -90)); // image.Save(@"c:\form.bmp"); setButtonStatus(true); } } catch (Exception ex) { setButtonStatus(true); MessageBox.Show(ex.Message); } PrintDocument pdoc = new PrintDocument(); pdoc.PrintPage += new PrintPageEventHandler(pdoc_PrintPage); //PrintDialog pd = new PrintDialog(); PrintPreviewDialog pd = new PrintPreviewDialog(); pd.Document = pdoc; if (pd.ShowDialog() == DialogResult.OK) { pdoc.Print(); } } Image image; void pdoc_PrintPage(object sender, PrintPageEventArgs e) { e.Graphics.DrawImage(image, 50,40,e.MarginBounds.Right , e.MarginBounds.Height/2); }
给你一段代码,老外的,如果要自己绘制控件的话: 不过不是很好看 foreach (Control c in Controls) { // Get the time of the next control so we can unbox it string strType = c.GetType().ToString().Substring(c.GetType().ToString().LastIndexOf(".") + 1); switch (strType) { case "Button": Button b = (Button)c; // Use the ControlPaint method DrawButton in order to draw the button of the form ControlPaint.DrawButton(g, ((Button)c).Left, ((Button)c).Top, ((Button)c).Width, ((Button)c).Height, ButtonState.Normal); // We also need to draw the text g.DrawString(b.Text, b.Font, new SolidBrush(b.ForeColor), b.Left + b.Width / 2 - g.MeasureString(b.Text, b.Font).Width / 2, b.Top + b.Height / 2 - g.MeasureString("a", b.Font).Height / 2, new StringFormat()); break; case "TextBox": TextBox t = (TextBox)c; // Draw a text box by drawing a pushed in button and filling the rectangle with the background color and the text // of the TextBox control // First the sunken border ControlPaint.DrawButton(g, t.Left, t.Top, t.Width, t.Height, ButtonState.Pushed); // Then fill it with the background of the textbox g.FillRectangle(new SolidBrush(t.BackColor), t.Left + 1, t.Top + 1, t.Width + 2, t.Height - 2); // Finally draw the string inside g.DrawString(t.Text, t.Font, new SolidBrush(t.ForeColor), t.Left + 2, t.Top + t.Height / 2 - g.MeasureString("a", t.Font).Height / 2, new StringFormat()); break; case "CheckBox":// We have a checkbox to paint, unbox it CheckBox cb = (CheckBox)c; // Use the DrawCheckBox command to draw a checkbox and pass the button state to paint it checked or unchecked if (cb.Checked) ControlPaint.DrawCheckBox(g, cb.Left, cb.Top, cb.Height / 2, cb.Height / 2, ButtonState.Checked); else ControlPaint.DrawCheckBox(g, cb.Left, cb.Top, cb.Height / 2, cb.Height / 2, ButtonState.Normal); // Don't forget the checkbox text g.DrawString(cb.Text, cb.Font, new SolidBrush(cb.ForeColor), cb.Right - cb.Height - g.MeasureString(cb.Text, cb.Font).Width, cb.Top, new StringFormat()); break; case "RadioButton": //自已加的,不是很对 RadioButton rb = (RadioButton)c; ControlPaint.DrawRadioButton(g, rb.Left, rb.Top, rb.Width, rb.Height, ButtonState.Normal); g.DrawString(rb.Text, rb.Font, new SolidBrush(rb.ForeColor), rb.Right - rb.Height - g.MeasureString(rb.Text, rb.Font).Width, rb.Top, new StringFormat()); break; } }
2.自己绘制表格
要自己用 Graphics 画
public void Document_PrintPage(object sender, PrintPageEventArgs e)
{
Graphics g = e.Graphics;
g.PageUnit = GraphicsUnit.Millimeter;
//打字
g.DrawString("你要打的文字", new Font("宋体", 14, FontStyle.Bold), Brushes.Black, intEnglishX, intEnglishY);
//画线
Pen p = new Pen(Brushes.Black);
p.Width = 0.1f;
g.DrawLine(p, new Point(x1, y1), new Point(x2, y2));
...
}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>无标题页</title>
</head><script>
function href()
{
window.open("Default2.aspx");
}
</script>
<body>
<form id="form1" runat="server">
<div>
<!--startprint-->
<div id="myPage">
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:BoundField DataField="job_id" HeaderText="不知道" />
</Columns>
</asp:GridView>
</div>
<input id="Button1" type="button" value="button" onclick="href();"/></div>
</form>
</body>
</html>Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Reflection;
using System.IO;
using System.Text;public partial class _Default : System.Web.UI.Page
{
string tbName = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
tbName = "jobs";
SqlConnection sqlcon = new SqlConnection("server=.;database=pubs;uid=sa;pwd=sa");
sqlcon.Open();
string sql = "select * from " + tbName + "";
SqlDataAdapter sqlDa = new SqlDataAdapter(sql, sqlcon);
System.Data.DataTable dt = new System.Data.DataTable();
sqlDa.Fill(dt);
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
sqlcon.Close();
}
} protected void Button4_Click(object sender, EventArgs e)
{
tbName = "jobs";
SqlConnection sqlcon = new SqlConnection("server=.;database=pubs;uid=sa;pwd=sa");
sqlcon.Open();
string sql = "select * from " + tbName + "";
SqlDataAdapter sqlDa = new SqlDataAdapter(sql, sqlcon);
System.Data.DataTable dt = new System.Data.DataTable();
sqlDa.Fill(dt);
DGPrint(dt);
sqlcon.Close();
} //自定义类PrintClass
public string DGPrint(DataTable dt)
{
//DGPrint执行的功能:根据DataTable转换成对应的HTML对应的字符串
DataTable myDataTable = new DataTable();
myDataTable = dt; int myRow = myDataTable.Rows.Count;
int myCol = myDataTable.Columns.Count; StringBuilder sb = new StringBuilder(); string colHeaders = "<html><body>" + "<object ID='WebBrowser' WIDTH=0 HEIGHT=0 CLASSID='CLSID:8856F961-340A-11D0-A96B-00C04FD705A2'VIEWASTEXT></object>" + "<table><tr>"; for (int i = 0; i < myCol; i++)
{
colHeaders += "<td>" + myDataTable.Columns[i].ColumnName.ToString() + "</td>";
}
colHeaders += "</tr>";
sb.Append(colHeaders); for (int i = 0; i < myRow; i++)
{
sb.Append("<tr>");
for (int j = 0; j < myCol; j++)
{
sb.Append("<td>");
sb.Append(myDataTable.Rows[i][j].ToString().Trim());
sb.Append("</td>");
}
sb.Append("</tr>");
} sb.Append("</table></body></html>");
colHeaders = sb.ToString();
colHeaders += "<script languge='Javascript'>WebBrowser.ExecWB(7,1); window.opener=null;window.close();</script>";
return (colHeaders);
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
<style media="print">
.noprint { display: none }
</style>
</head>
<script>
function swichbar()
{
var myPage= window.opener.document.getElementById('myPage').innerHTML;
window.document.getElementById('pg').innerHTML=myPage;
}</script>
<body onload="swichbar()">
<OBJECT classid="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2" height="0" id=WebBrowser width="0"></OBJECT>
<form id="form1" runat="server">
<div id="pg">
</div>
<div id="page" class="noprint">
<input id="Button1" type="button" value="直接打印" onclick="document.all.WebBrowser.ExecWB(6,6)" />
<input id="Button2" type="button" value="页面设置" onclick="document.all.WebBrowser.ExecWB(8,1)" />
<input id="Button3" type="button" value="打印预览" onclick="javascript:document.all.WebBrowser.ExecWB(7,1)" />
</div>
</form>
</body>
</html>Default2.aspx.cs
或者参考一下文档:
http://blog.csdn.net/zhangzeshuai/archive/2008/09/02/2865766.aspx
FormPrint.cs
/* Created by SharpDevelop.
* Developed by: Juergen Thomas, Berlin (Germany)
* email adress: post(at)vs-polis.de
*
* Provided for NET 1.1 and 2.0
* ----------------------------
* To adapt the code for the used version, change the #define instructions.
*
* Project: general tool to print or save a form or any other control
*
* License: you can use this code 'as is' without any warrenty.
*
* Description
* -----------
* http://www.codeproject.com/csharp/FormPrintPackage.asp (English)
* http://www.mycsharp.de/wbb2/thread.php?threadid=29704 (deutsch)
*
* History
* -------
* 12/17/2006
* First version
*
* 12/19/2006
* 1. added: clearing resources (Bitmap, Graphics)
* 2. added: printing as portrait or landscape
* 3. added: another method Execute() to decide printing either portrait or landscape
*
* 12/23/2006
* 1. changed: a shorter way to copy the control's graphics to the bitmap
* 2. comment changed: at present, no adaptation to NET 1.1
*
* 12/25/2006
* 1. added: copy the control's graphics to the bitmap with NET 1.1
* 2. changed: variables and methods are grouped newly,
* but with no other features
* 3. comment changed: adaptation to NET 1.1
* 4. commend added: known problems
*
* 01/13/2007
* 1. NET 1.1 changed: form can be printed including title and menu bar
* 2. changed: public method Execute() splitted to Print() resp. Save()
* 3. changed: Print() allows several parameters: PrinterName, Margins, Orientation
* 4. changed: printing can compress to papersize with margins if necessary
* 5. changed: most of the parameters can be omitted
* 6. changed: printer memory problem managed by converting
* to PixelFormat.Format8bppIndexed and GrayScaled bitmap
* instead of colored PixelFormat.Canonical
* 7. changed: Execute() uses progress label while printing a large control
* (more than 40000 pixels, e.g. 200x200)
* 8. changed: private method Execute() splitted to StartPrinting() resp. StartSaving()
*
* 01/22/2007
* 1. changed: use #define to change NET version
* 2. changed: converting to PixelFormat.Format8bppIndexed now managed
* by enum ColorDepthReduction
*
* 03/22/2007
* RichTextBox and WebBrowser cannot be copied by Control.DrawToBitmap(); therefore
* we need DllImport("gdi32.dll") both, for NET 1.1 and NET 2.0
* this leeds to the following changes:
* 1. changed using System.Runtime.InteropServices; for NET 2.0, too
* 2. renamed GetBitmap() for NET 1.1 to GetBitmapGdi()
* FormPrint calls GetBitmap() and leeds to GetBitmapGdi()
* 3. changed GetBitmap() for NET 2.0 isn't used in all situations:
* does Control contain any RichTextBox or WebBrowser Control?
* true => FormPrint calls GetBitmapGdi()
* false => FormPrint calls GetBitmap() using DrawToBitmap()
*
* */
调用也简单如下:
这是保存代码:FormPrint.Save(this, ImageFormat.Gif, "c:\\t.gif");
这是打印代码:FormPrint.Print(this);
this指窗体本身。
细心点就不会出错。事先分析好表头和内容的格式,在纸上画出来,算好位置和距离就行了主要使用函数是 DrawLine() 和 DrawString() ,另外 MesureString() 也要大量使用。
1. 使用水晶报表
2. 使用第三方控件
3. 自己重画表格
4. 写到excel中,然后打印excel
...
用 Graphics.CopyFRomScreen( new Point (10,10),new Point(0,0),Size)
try
{
setButtonStatus(false); //把按钮等不显示的东东HIDE
image = new Bitmap(this.Width-10, this.Height-90);//从窗体的哪里开始
using (Graphics g = Graphics.FromImage(image))
{
Point pt1 = new Point(this.Location.X + 5, this.Location.Y + 70);
g.CopyFromScreen(pt1, new Point(0, 0), new Size (this .Width -10,this .Height -90));
// image.Save(@"c:\form.bmp");
setButtonStatus(true);
}
}
catch (Exception ex)
{
setButtonStatus(true);
MessageBox.Show(ex.Message);
}
PrintDocument pdoc = new PrintDocument();
pdoc.PrintPage += new PrintPageEventHandler(pdoc_PrintPage);
//PrintDialog pd = new PrintDialog();
PrintPreviewDialog pd = new PrintPreviewDialog();
pd.Document = pdoc;
if (pd.ShowDialog() == DialogResult.OK)
{
pdoc.Print();
}
} Image image;
void pdoc_PrintPage(object sender, PrintPageEventArgs e)
{
e.Graphics.DrawImage(image, 50,40,e.MarginBounds.Right , e.MarginBounds.Height/2);
}
不过不是很好看
foreach (Control c in Controls)
{
// Get the time of the next control so we can unbox it
string strType = c.GetType().ToString().Substring(c.GetType().ToString().LastIndexOf(".") + 1);
switch (strType)
{
case "Button": Button b = (Button)c;
// Use the ControlPaint method DrawButton in order to draw the button of the form
ControlPaint.DrawButton(g, ((Button)c).Left, ((Button)c).Top, ((Button)c).Width, ((Button)c).Height, ButtonState.Normal);
// We also need to draw the text
g.DrawString(b.Text, b.Font, new SolidBrush(b.ForeColor), b.Left + b.Width / 2 - g.MeasureString(b.Text,
b.Font).Width / 2, b.Top + b.Height / 2 - g.MeasureString("a", b.Font).Height / 2, new StringFormat());
break;
case "TextBox": TextBox t = (TextBox)c;
// Draw a text box by drawing a pushed in button and filling the rectangle with the background color and the text
// of the TextBox control
// First the sunken border
ControlPaint.DrawButton(g, t.Left, t.Top, t.Width, t.Height, ButtonState.Pushed);
// Then fill it with the background of the textbox
g.FillRectangle(new SolidBrush(t.BackColor), t.Left + 1, t.Top + 1, t.Width + 2, t.Height - 2);
// Finally draw the string inside
g.DrawString(t.Text, t.Font, new SolidBrush(t.ForeColor), t.Left + 2, t.Top + t.Height / 2 - g.MeasureString("a", t.Font).Height / 2, new StringFormat());
break;
case "CheckBox":// We have a checkbox to paint, unbox it
CheckBox cb = (CheckBox)c;
// Use the DrawCheckBox command to draw a checkbox and pass the button state to paint it checked or unchecked
if (cb.Checked)
ControlPaint.DrawCheckBox(g, cb.Left, cb.Top, cb.Height / 2, cb.Height / 2, ButtonState.Checked);
else
ControlPaint.DrawCheckBox(g, cb.Left, cb.Top, cb.Height / 2, cb.Height / 2, ButtonState.Normal);
// Don't forget the checkbox text
g.DrawString(cb.Text, cb.Font, new SolidBrush(cb.ForeColor), cb.Right - cb.Height - g.MeasureString(cb.Text, cb.Font).Width, cb.Top, new StringFormat());
break;
case "RadioButton": //自已加的,不是很对
RadioButton rb = (RadioButton)c;
ControlPaint.DrawRadioButton(g, rb.Left, rb.Top, rb.Width, rb.Height, ButtonState.Normal);
g.DrawString(rb.Text, rb.Font, new SolidBrush(rb.ForeColor), rb.Right - rb.Height - g.MeasureString(rb.Text, rb.Font).Width, rb.Top, new StringFormat());
break;
}
}