Share via


方法 : Windows フォームで印刷プレビューを使用して印刷する

更新 : 2007 年 11 月

Windows フォームのプログラミングでは、印刷サービスのほかに印刷プレビューを実装することは一般的です。アプリケーションに印刷プレビュー サービスを追加する簡単な方法は、ファイルの印刷に、PrintPreviewDialog コントロールと PrintPage イベント処理ロジックを組み合わせて使用することです。

PrintPreviewDialog コントロールを使用してテキスト文書をプレビューするには

  1. フォームに PrintPreviewDialogPrintDocument、および 2 つの文字列を追加します。

    Private printPreviewDialog1 As New PrintPreviewDialog()
    Private WithEvents printDocument1 As New PrintDocument()
    
    ' Declare a string to hold the entire document contents.
    Private documentContents As String
    
    ' Declare a variable to hold the portion of the document that
    ' is not printed.
    Private stringToPrint As String
    
    private PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog();
    private PrintDocument printDocument1 = new PrintDocument();
    
    // Declare a string to hold the entire document contents.
    private string documentContents;
    
    // Declare a variable to hold the portion of the document that
    // is not printed.
    private string stringToPrint;
    
  2. DocumentName プロパティを印刷する文書に設定し、前もって追加してあった文字列に文書の内容を読み込みます。

    Private Sub ReadDocument() 
        Dim docName As String = "testPage.txt"
        Dim docPath As String = "c:\"
        printDocument1.DocumentName = docName
        Dim stream As New FileStream(docPath + docName, FileMode.Open)
        Try
            Dim reader As New StreamReader(stream)
            Try
                documentContents = reader.ReadToEnd()
            Finally
                reader.Dispose()
            End Try
        Finally
            stream.Dispose()
        End Try
        stringToPrint = documentContents
    
    End Sub
    
    private void ReadDocument()
    {
        string docName = "testPage.txt";
        string docPath = @"c:\";
        printDocument1.DocumentName = docName;
        using (FileStream stream = new FileStream(docPath + docName, FileMode.Open))
        using (StreamReader reader = new StreamReader(stream))
        {
            documentContents = reader.ReadToEnd();
        }
        stringToPrint = documentContents;
    }
    
  3. 文書を印刷する場合と同様に、PrintPage イベント ハンドラでは、PrintPageEventArgs クラスの Graphics プロパティとファイルの内容を使用し、1 ページあたりの行数を計算し、文書の内容を描画します。各ページの描画後に、そのページが最終ページかどうかを確認し、結果に応じて PrintPageEventArgsHasMorePages プロパティを設定します。HasMorePages が false になるまで、PrintPage イベントが発生します。文書の描画が完了したら、描画対象の文字列をリセットします。また、PrintPage イベントがイベント処理メソッドに関連付けられていることを確認します。

    ms404294.alert_note(ja-jp,VS.90).gifメモ :

    アプリケーションに印刷機能を実装済みの場合、手順 2 と 3 は完了していることもあります。

    イベント ハンドラを使用して、フォームに使用したのと同じフォントで "testPage.txt" ファイルを印刷するコード例を次に示します。

    Sub printDocument1_PrintPage(ByVal sender As Object, _
        ByVal e As PrintPageEventArgs) Handles printDocument1.PrintPage
    
        Dim charactersOnPage As Integer = 0
        Dim linesPerPage As Integer = 0
    
        ' Sets the value of charactersOnPage to the number of characters 
        ' of stringToPrint that will fit within the bounds of the page.
        e.Graphics.MeasureString(stringToPrint, Me.Font, e.MarginBounds.Size, _
            StringFormat.GenericTypographic, charactersOnPage, linesPerPage)
    
        ' Draws the string within the bounds of the page.
        e.Graphics.DrawString(stringToPrint, Me.Font, Brushes.Black, _
            e.MarginBounds, StringFormat.GenericTypographic)
    
        ' Remove the portion of the string that has been printed.
        stringToPrint = stringToPrint.Substring(charactersOnPage)
    
        ' Check to see if more pages are to be printed.
        e.HasMorePages = stringToPrint.Length > 0
    
        ' If there are no more pages, reset the string to be printed.
        If Not e.HasMorePages Then
            stringToPrint = documentContents
        End If
    
    End Sub
    
    void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
    {
        int charactersOnPage = 0;
        int linesPerPage = 0;
    
        // Sets the value of charactersOnPage to the number of characters 
        // of stringToPrint that will fit within the bounds of the page.
        e.Graphics.MeasureString(stringToPrint, this.Font,
            e.MarginBounds.Size, StringFormat.GenericTypographic,
            out charactersOnPage, out linesPerPage);
    
        // Draws the string within the bounds of the page.
        e.Graphics.DrawString(stringToPrint, this.Font, Brushes.Black,
        e.MarginBounds, StringFormat.GenericTypographic);
    
        // Remove the portion of the string that has been printed.
        stringToPrint = stringToPrint.Substring(charactersOnPage);
    
        // Check to see if more pages are to be printed.
        e.HasMorePages = (stringToPrint.Length > 0);
    
        // If there are no more pages, reset the string to be printed.
        if (!e.HasMorePages)
            stringToPrint = documentContents;
    }
    
  4. PrintPreviewDialog コントロールの Document プロパティをフォームの PrintDocument コンポーネントに設定します。

    printPreviewDialog1.Document = printDocument1
    
    printPreviewDialog1.Document = printDocument1;
    
  5. PrintPreviewDialog コントロールの ShowDialog メソッドを呼び出します。通常、ボタンの Click イベント処理メソッドから ShowDialog を呼び出します。ShowDialog を呼び出すと、PrintPage イベントが発生し、出力を PrintPreviewDialog コントロールに描画します。ユーザーがダイアログ ボックスの印刷アイコンをクリックすると PrintPage イベントが再発生し、出力はプレビュー ダイアログ ボックスではなくプリンタに送信されます。これが、手順 3 で描画プロセスの最後に文字列をリセットする理由です。

    フォーム上にあるボタンの Click イベント処理メソッドのコード例を次に示します。このイベント処理メソッドは、文書を読み込んで印刷プレビュー ダイアログ ボックスを表示するメソッドを呼び出します。

    Private Sub printPreviewButton_Click(ByVal sender As Object, _
        ByVal e As EventArgs) Handles printPreviewButton.Click
    
        ReadDocument()
        printPreviewDialog1.Document = printDocument1
        printPreviewDialog1.ShowDialog()
    End Sub
    
            private void printPreviewButton_Click(object sender, EventArgs e)
            {
                ReadDocument();
                printPreviewDialog1.Document = printDocument1;
            printPreviewDialog1.ShowDialog();
    
            }
    

使用例

Imports System
Imports System.Drawing
Imports System.IO
Imports System.Drawing.Printing
Imports System.Windows.Forms



Class Form1
    Inherits Form

    Private WithEvents printPreviewButton As Button

    Private printPreviewDialog1 As New PrintPreviewDialog()
    Private WithEvents printDocument1 As New PrintDocument()

    ' Declare a string to hold the entire document contents.
    Private documentContents As String

    ' Declare a variable to hold the portion of the document that
    ' is not printed.
    Private stringToPrint As String

    Public Sub New() 
        Me.printPreviewButton = New System.Windows.Forms.Button()
        Me.printPreviewButton.Location = New System.Drawing.Point(12, 12)
        Me.printPreviewButton.Size = New System.Drawing.Size(125, 23)
        Me.printPreviewButton.Text = "Print Preview"
        Me.ClientSize = New System.Drawing.Size(292, 266)
        Me.Controls.Add(Me.printPreviewButton)

    End Sub

    Private Sub ReadDocument() 
        Dim docName As String = "testPage.txt"
        Dim docPath As String = "c:\"
        printDocument1.DocumentName = docName
        Dim stream As New FileStream(docPath + docName, FileMode.Open)
        Try
            Dim reader As New StreamReader(stream)
            Try
                documentContents = reader.ReadToEnd()
            Finally
                reader.Dispose()
            End Try
        Finally
            stream.Dispose()
        End Try
        stringToPrint = documentContents

    End Sub

    Sub printDocument1_PrintPage(ByVal sender As Object, _
        ByVal e As PrintPageEventArgs) Handles printDocument1.PrintPage

        Dim charactersOnPage As Integer = 0
        Dim linesPerPage As Integer = 0

        ' Sets the value of charactersOnPage to the number of characters 
        ' of stringToPrint that will fit within the bounds of the page.
        e.Graphics.MeasureString(stringToPrint, Me.Font, e.MarginBounds.Size, _
            StringFormat.GenericTypographic, charactersOnPage, linesPerPage)

        ' Draws the string within the bounds of the page.
        e.Graphics.DrawString(stringToPrint, Me.Font, Brushes.Black, _
            e.MarginBounds, StringFormat.GenericTypographic)

        ' Remove the portion of the string that has been printed.
        stringToPrint = stringToPrint.Substring(charactersOnPage)

        ' Check to see if more pages are to be printed.
        e.HasMorePages = stringToPrint.Length > 0

        ' If there are no more pages, reset the string to be printed.
        If Not e.HasMorePages Then
            stringToPrint = documentContents
        End If

    End Sub

    Private Sub printPreviewButton_Click(ByVal sender As Object, _
        ByVal e As EventArgs) Handles printPreviewButton.Click

        ReadDocument()
        printPreviewDialog1.Document = printDocument1
        printPreviewDialog1.ShowDialog()
    End Sub

    <STAThread()>  _
    Shared Sub Main() 
        Application.EnableVisualStyles()
        Application.SetCompatibleTextRenderingDefault(False)
        Application.Run(New Form1())

    End Sub
End Class 
using System;
using System.Drawing;
using System.IO;
using System.Drawing.Printing;
using System.Windows.Forms;

namespace PrintPreviewApp
{
    public partial class Form1 : Form
    {
        private Button printPreviewButton;

        private PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog();
        private PrintDocument printDocument1 = new PrintDocument();

        // Declare a string to hold the entire document contents.
        private string documentContents;

        // Declare a variable to hold the portion of the document that
        // is not printed.
        private string stringToPrint;

        public Form1()
        {
            this.printPreviewButton = new System.Windows.Forms.Button();
            this.printPreviewButton.Location = new System.Drawing.Point(12, 12);
            this.printPreviewButton.Size = new System.Drawing.Size(125, 23);
            this.printPreviewButton.Text = "Print Preview";
            this.printPreviewButton.Click += new System.EventHandler(this.printPreviewButton_Click);
            this.ClientSize = new System.Drawing.Size(292, 266);
            this.Controls.Add(this.printPreviewButton);
            printDocument1.PrintPage +=
                new PrintPageEventHandler(printDocument1_PrintPage);
        }
        private void ReadDocument()
        {
            string docName = "testPage.txt";
            string docPath = @"c:\";
            printDocument1.DocumentName = docName;
            using (FileStream stream = new FileStream(docPath + docName, FileMode.Open))
            using (StreamReader reader = new StreamReader(stream))
            {
                documentContents = reader.ReadToEnd();
            }
            stringToPrint = documentContents;
        }

        void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
        {
            int charactersOnPage = 0;
            int linesPerPage = 0;

            // Sets the value of charactersOnPage to the number of characters 
            // of stringToPrint that will fit within the bounds of the page.
            e.Graphics.MeasureString(stringToPrint, this.Font,
                e.MarginBounds.Size, StringFormat.GenericTypographic,
                out charactersOnPage, out linesPerPage);

            // Draws the string within the bounds of the page.
            e.Graphics.DrawString(stringToPrint, this.Font, Brushes.Black,
            e.MarginBounds, StringFormat.GenericTypographic);

            // Remove the portion of the string that has been printed.
            stringToPrint = stringToPrint.Substring(charactersOnPage);

            // Check to see if more pages are to be printed.
            e.HasMorePages = (stringToPrint.Length > 0);

            // If there are no more pages, reset the string to be printed.
            if (!e.HasMorePages)
                stringToPrint = documentContents;
        }
        private void printPreviewButton_Click(object sender, EventArgs e)
        {
            ReadDocument();
            printPreviewDialog1.Document = printDocument1;
        printPreviewDialog1.ShowDialog();

        }

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

コードのコンパイル方法

この例で必要な要素は次のとおりです。

参照

処理手順

方法 : Windows フォームで複数ページのテキスト ファイルを印刷する

概念

Windows フォームでのより安全な印刷

その他の技術情報

Windows フォームにおける印刷のサポート