[C#] 프린트 C# 2009. 2. 3. 21:56

흠.. 일단 간단한 프린트를 하기 위한 코드이다.

각 출력 결과에 따른 포멧 형식은 자신들이 정해야겠지만..

필자는 단지 출력 테스트를 한 것 뿐..

별 다른게 없다^_^

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;

namespace Print
{
    public partial class Form1 : Form
    {
        private PageSettings m_PageSetting = null;
        private Font m_subFont = new Font("굴림체",13);
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                PageSetupDialog Psetup = new PageSetupDialog();
                if (this.m_PageSetting == null)
                    this.m_PageSetting = new PageSettings();
                Psetup.PageSettings = this.m_PageSetting;
                Psetup.ShowDialog();
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                PrintDocument pd = new PrintDocument();
                pd.PrintPage += new PrintPageEventHandler(this.PrintPageEvent);

                if (this.m_PageSetting != null)
                    pd.DefaultPageSettings = this.m_PageSetting;

                PrintPreviewDialog pdlg = new PrintPreviewDialog();
                pdlg.Document = pd;
                pdlg.ShowDialog();
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }

        protected void PrintPageEvent(Object obj,PrintPageEventArgs pea)
        {
            Graphics g = pea.Graphics;
            PrintDocument(g);
            pea.HasMorePages=false;
        }

        private void PrintDocument(Graphics g)
        {
            g.FillRectangle(Brushes.White, 100, 50, 800, 600);
            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Center;
            sf.LineAlignment = StringAlignment.Center;
            Rectangle rect = new Rectangle(110, 130, 400, this.m_subFont.Height * 10);
            g.DrawString(this.txt_Content.Text, this.m_subFont, Brushes.Black, rect);
        }

        private void button3_Click(object sender, System.EventArgs e)
        {
            try
            {
                PrintDocument pd = new PrintDocument();
                pd.PrintPage += new PrintPageEventHandler(this.PrintPageEvent);
                if (this.m_PageSetting != null)
                    pd.DefaultPageSettings = this.m_PageSetting;
                PrintDialog pdlg = new PrintDialog();
                pdlg.Document = pd;
                if (pdlg.ShowDialog() == DialogResult.OK)
                {
                    pd.Print();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}