C#で印刷可能範囲いっぱいに枠線を書く。

目的

プリンタの印刷可能な範囲を知るために、 印刷可能な範囲に枠線を書く。

GUIでプロジェクトを作成し、メニューに 「印刷」と書かれた項目を用意し、 それをクリックすると印刷可能範囲いっぱいに枠線を書く例。

環境

.NET Framework 4.7.2

VisualStudio 2017

Windowsの設定で、規定のプリンタを物理的な使用可能なプリンタに設定している。

ソースコード

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Printing;
using System.Drawing;

namespace _20190608_PrintTest
{
    public partial class Form1 : Form
    {
        private PageSettings pageSetting = new PageSettings();

        public Form1()
        {
            InitializeComponent();
        }

        private void 印刷ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                // マージンをとりあえず設定。
                pageSetting.Margins = new Margins(
                0, 0, 0, 0
                );

                // 原点を設定する。
                printDocument.OriginAtMargins = true;

                printDocument.DefaultPageSettings = pageSetting;
                printDialog.Document = printDocument;

                printDocument.Print();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "エラー");
            }

        }

        private void printDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            // 印刷可能な領域を枠で囲む。
            e.Graphics.DrawRectangle(
                new Pen(Color.Blue, 2),
                e.PageSettings.PrintableArea.X,
                e.PageSettings.PrintableArea.Y,
                e.PageSettings.PrintableArea.Width,
                e.PageSettings.PrintableArea.Height
                );
        }
    }
}

コメント

タイトルとURLをコピーしました