c#打印边距1

来源:互联网 发布:万捷网络验证 编辑:程序博客网 时间:2024/06/06 03:31
 
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. using System.Drawing.Printing;
  9. using System.Drawing.Drawing2D;
  10. namespace WindowsApplication3
  11. {
  12.     public partial class Form6 : Form
  13.     {
  14.         string filename = "myfile.txt";
  15.         Font printerfont = null;
  16.         public Form6()
  17.         {
  18.             InitializeComponent();
  19.         }
  20.         static Rectangle GetRealPageBounds(PrintPageEventArgs e, bool preview)
  21.         {
  22.             if (preview) return e.PageBounds;
  23.             RectangleF vpb = e.Graphics.VisibleClipBounds;
  24.             PointF[]bottomRight={new PointF(vpb.Size.Width,vpb.Size.Height)};
  25.             e.Graphics.TransformPoints(CoordinateSpace.Device, CoordinateSpace.Page, bottomRight);
  26.             float dpix = e.Graphics.DpiX;
  27.             float dpiy = e.Graphics.DpiY;
  28.             return new Rectangle(0, 0, (int)(bottomRight[0].X * 100 / dpix), (int)(bottomRight[0].Y * 100 / dpiy));
  29.         }
  30.         private void button1_Click(object sender, EventArgs e)
  31.         {
  32.             this.printDocument1.DocumentName = this.filename;
  33.             this.printDocument1.Print();
  34.         }
  35.         private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
  36.         {
  37.             Graphics g = e.Graphics;
  38.             bool preview=false;
  39.             Rectangle realPageBounds = GetRealPageBounds(e, preview);
  40.             g.DrawString("header", printerfont, Brushes.Red, realPageBounds);
  41.             StringFormat farFormat = new StringFormat();
  42.             farFormat.Alignment = StringAlignment.Far;
  43.             farFormat.LineAlignment = StringAlignment.Far;
  44.             g.DrawString("footer", printerfont, Brushes.Black, realPageBounds, farFormat);
  45.         }
  46.         private void printDocument1_BeginPrint(object sender, PrintEventArgs e)
  47.         {
  48.             printerfont = new Font("Lucida Console", 72);
  49.         }
  50.         private void printDocument1_EndPrint(object sender, PrintEventArgs e)
  51.         {
  52.             printerfont.Dispose();
  53.             printerfont = null;
  54.         }
  55.     }
  56. }
原创粉丝点击