用紙の寸法(サイズ)を取得する - C#

印刷の用紙の寸法を取得するコードを紹介します。

UI

下図のUIを準備します。ButtonとTextBoxを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)
    {
      int pwidth = e.PageSettings.PaperSize.Width;
      int pheight = e.PageSettings.PaperSize.Height;
      textBox1.Text += string.Format("widht:{0:d}, height:{1:d} 1/100inch \r\n",pwidth,pheight);

      double pwd = (double)pwidth/100f;
      double phd = (double)pheight/100f;
      textBox1.Text += string.Format("widht:{0:f}, height:{1:f} inch \r\n",pwd,phd);
    }
  }
}

解説

button1.click
PrintDocument pd = new PrintDocument();
にて、印刷用のドキュメント"PrintDocument"を作成します。

pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
pd.Print();
印刷の処理はPrintDocumentクラスのPrintPageイベントに実装します。印刷の実装はpd_PrintPage()メソッドに記述をし、PrintPageイベントハンドラを作成します。PrintDocumentクラスのPrintメソッドで印刷を開始します。
pd_PrintPage
int pwidth = e.PageSettings.PaperSize.Width;
int pheight = e.PageSettings.PaperSize.Height;
textBox1.Text += string.Format("widht:{0:d}, height:{1:d} 1/100inch \r\n",pwidth,pheight);
PrintPageEventArgsのPageSettingsオブジェクトのPaperSizeに用紙の寸法が設定されています。単位は1/100インチとなっています。用紙の寸法を取得しテキストボックスに表示します。
double pwd = (double)pwidth/100f;
double phd = (double)pheight/100f;
textBox1.Text += string.Format("widht:{0:f}, height:{1:f} inch \r\n",pwd,phd);
用紙の寸法をインチで取得する場合は値を100で割ります。

実行結果

プロジェクトを実行し、button1を押します。用紙の寸法がテキストボックスに表示されます。また、デフォルトのプリンタで何も印刷されないページが出力されます。


補足

用紙の寸法をmm単位で取得する場合はこちらの記事を参照して下さい。

PrintPageイベント外で取得する場合

PrintPageイベント外で用紙のサイズを取得したい場合もあります。この場合は、PrintDocumentクラスのDefaultPageSettingsプロパティのpaperSizeプロパティを参照します。

コード例

private void button2_Click(object sender, EventArgs e)
{
  PrintDocument pd = new PrintDocument();
  int pwidth = pd.PrinterSettings.DefaultPageSettings.PaperSize.Width;
  int pheight = pd.PrinterSettings.DefaultPageSettings.PaperSize.Height;
  textBox1.Text += string.Format("widht:{0:d}, height:{1:d} 1/100inch \r\n", pwidth, pheight);

  double pwd = (double)pwidth / 100f;
  double phd = (double)pheight / 100f;
  textBox1.Text += string.Format("widht:{0:f}, height:{1:f} inch \r\n", pwd, phd);
}
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
掲載日: 2012-05-29
iPentec all rights reserverd.