印刷をするプログラムのコードと実行結果を紹介します。
印刷をするには、PrintDocument クラスを利用します。
PrintDocument.Printメソッドを呼び出すと、PrintPageインベントが発生するので、
PrintPageイベントハンドラの引数 PrintPageEventArgs のGraphicsオブジェクトに対して描画をします。
印刷はプリンタによる印刷が基本ですが、Adobe AcrobatによるPDFの作成もできます。
下図のUIを準備します。フォームにボタンを1つ設置します。
下記コードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;
namespace SimplePrint
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
pd.Print();
}
private void pd_PrintPage(object sender, PrintPageEventArgs e)
{
Font font = new Font("メイリオ", 10.5f);
Brush brush = new SolidBrush(Color.Black);
e.Graphics.DrawString("テスト123456789", font, brush, new PointF(20,20));
Pen p = new Pen(Color.Black);
e.Graphics.DrawRectangle(p, new Rectangle(20,100, 200,100));
}
}
}
PrintDocumentクラスを用いて印刷をします。印刷のロジックは、PrintDocumentクラスのPrintPageイベントに実装します。
PrintDocumentクラスのインスタンスを作成し、PrintPageイベントハンドラを作成します。イベントハンドラのメソッドは、"pd_PrintPage"メソッドを指定します。PeintDocumentクラスのPrintメソッドの呼び出しにより印刷が開始されます。
private void button1_Click(object sender, EventArgs e)
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
pd.Print();
}
印刷のためのフォントとブラシを作成します。
Font font = new Font("メイリオ", 10.5f);
Brush brush = new SolidBrush(Color.Black);
PrintPageEventArgsのGraphicsオブジェクトで描画することにより、印刷ができます。上のコードは座標(20,20)へ文字列"テスト123456789"を印刷します。
印刷座標はデフォルトでは1/100インチ単位となっています。上記コードは、用紙の上から0.2インチ、左から0.2インチの位置に文字列を描画します。
e.Graphics.DrawString("テスト123456789", font, brush, new PointF(20,20));
同様の手順で、矩形も印刷できます。上記コードは左上座標(20,100)、幅200、高さ100の矩形を印刷します。
Pen p = new Pen(Color.Black);
e.Graphics.DrawRectangle(p, new Rectangle(20,100, 200,100));
プロジェクトを実行します。下図のウィンドウが表示されます。
button1をクリックします。コントロールパネルの[プリンタ]で「通常使うプリンタ」に設定されているプリンタで印刷されます。Adobe PDFで印刷した場合の結果を下図に示します。