LoginSignup
2
0

More than 1 year has passed since last update.

お疲れ様です。たなしょです。
今日は前日作成したテキストエディタに印刷機能を追加しました。

印刷ダイアログを出力する

画像のように印刷ダイアログを出力させました。
image.png

using System.Drawing.Printing;
/* 省略 */
try
{
    printDocument1.DefaultPageSettings = _pageSetting;
    _strPrint = textBox1.Text;
    printDialog1.Document = printDocument1;

    if (printDialog1.ShowDialog() == DialogResult.OK)
    {
        printDocument1.Print();
    }
    else
    {
        return;
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message, "エラー");
}

printDialog1.ShowDialog()で印刷ダイアログを表示させている。
キャンセルや×を押すと処理を抜ける。

印刷処理を実装する

PrintDocument,PrintDialogツールを使用します。
ちょっと作りが複雑なので軽く説明します。
1.文字フォントや文字サイズを設定します

Font font = new("MS UI Gothic", 11);
int numberChars;
int numberLines;
string printString;
StringFormat format = new();

2.ページ上で描画可能な領域を指定

RectangleF rectSquare = new(
      e.MarginBounds.Left,
      e.MarginBounds.Top,
      e.MarginBounds.Width,
      e.MarginBounds.Height
      );

3.印刷する領域のサイズを指定

SizeF SquareSize = new(
      e.MarginBounds.Width,
      e.MarginBounds.Height - font.GetHeight(e.Graphics)
      );

4.印刷可能な1ページ当たりの文字数と行数の計算

e.Graphics.MeasureString(
      _strPrint,
      font,
      SquareSize,
      format,
      out numberChars,
      out numberLines
      );

5.印刷可能な領域に1ページ分の文字列を描画する。

e.Graphics.DrawString(
      printString,
      font,
      Brushes.Black,
      rectSquare,
      format
      );

6.1ページに収まらなかった場合はさらに印刷する

if (numberChars < _strPrint.Length)
{
    _strPrint = _strPrint.Substring(numberChars);
    e.HasMorePages = true;
}
else
{
    e.HasMorePages = false;
    _strPrint = textBox1.Text;
}

印刷プレビュー

image.png

PrintPreviewDialogパーツを使用する。
1.PrintPreviewDialogオブジェクトにPrintDocumentオブジェクトを登録。

printPreviewDialog1.Document = printDocument1;

2.「印刷プレビュー」ダイアログボックスを表示する

printPreviewDialog1.ShowDialog();

ページ設定

image.png
PageSetupDialogパーツを使用する。
1.「ページ設定」ダイアログボックスを表示する

pageSetupDialog1.ShowDialog();

最後に

今日はテキストエディタに印刷機能を追加しました。
「印刷」する挙動を書くのはなかなか難しく一回書いただけでは覚えられませんが、
おそらく印刷機能は書いたものを流用すれば実装できると思うので、
今回書いたソース部分はテンプレートに使おうと思います。

2
0
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
2
0