目次

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

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

UI

以下のUIを準備します。


コード

以下のコードを記述します。
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;

      double pwm = (double)pwidth * 0.254f;
      double phm = (double)pheight* 0.254f;
      textBox1.Text += string.Format("widht:{0:f}, height:{1:f} mm \r\n", pwm, phm);
    }
  }
}

解説

印刷、用紙の寸法に関する解説はこちらの記事を参照してください。
1 inch = 25.40 mm から、1/100インチで取得したPageSettings.PaperSizeの値に0.254を乗じて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;

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