Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

【WindowsForm】Windowsアプリケーションで帳票印刷

0
Posted at

概要

外部ライブラリを使わず、.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;
}

プレビューの表示
スクリーンショット 2026-01-13 224900.png

株式会社ONE WEDGE

0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?