概要
外部ライブラリを使わず、.NET標準機能だけで帳票印刷する方法を記載。
PrintDocument コンポーネントの概要 (Windows フォーム)
PrintDocumentを使用して印刷する内容の設定を行う。
内容の確認のために、PrintPreviewDialogも使用。
ソースコード
public void PrintPreview()
{
PrintDocument printDocument = new PrintDocument();
// A4縦
printDocument.DefaultPageSettings.PaperSize = new PaperSize("A4", 827, 1169);
printDocument.PrintPage += PrintPage;
printDocument.DefaultPageSettings.Landscape = false;
PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();
printPreviewDialog.Document = printDocument;
printPreviewDialog.WindowState = FormWindowState.Maximized;
if (printPreviewDialog.ShowDialog() == DialogResult.OK)
{
printDocument.Print();
}
}
private void PrintPage(object sender, PrintPageEventArgs e)
{
Graphics g = e.Graphics;
// フォント
Font titleFont = new Font("MS Gothic", 16, FontStyle.Bold);
Font bodyFont = new Font("MS Gothic", 10);
int x = 50;
int y = 50;
// タイトル
g.DrawString("タイトル", titleFont, Brushes.Black, x, y);
y += 40;
// 罫線
g.DrawLine(Pens.Black, x, y, x + 700, y);
y += 10;
// 見出し
g.DrawString("日付", bodyFont, Brushes.Black, x, y);
g.DrawString("氏名", bodyFont, Brushes.Black, x + 150, y);
g.DrawString("出勤", bodyFont, Brushes.Black, x + 300, y);
g.DrawString("退勤", bodyFont, Brushes.Black, x + 450, y);
y += 20;
// データ行(仮)
for (int i = 0; i < 10; i++)
{
g.DrawLine(Pens.Black, x, y, x + 700, y);
y += 10;
g.DrawString("2026/01/12", bodyFont, Brushes.Black, x, y);
g.DrawString("山田 太郎", bodyFont, Brushes.Black, x + 150, y);
g.DrawString("09:00", bodyFont, Brushes.Black, x + 300, y);
g.DrawString("18:00", bodyFont, Brushes.Black, x + 450, y);
y += 20;
}
}
複数ページ必要な場合は、PrintPage関数の中でHasMorePagesプロパティにTrueを設定。
HasMorePagesプロパティにTrueを設定すると、PrintPageイベント・ハンドラの印刷処理が完了した後、再びPrintPageイベントが呼び出される。
印刷したいページ分、HasMorePagesプロパティをTrueにする。
private void PrintPage(object sender, PrintPageEventArgs e)
{
// 印刷内容設定処理
...
//
e.HasMorePages = true;
}
