diff --git a/dotnet-desktop-guide/net/winforms/printing/how-to-print-text-document.md b/dotnet-desktop-guide/net/winforms/printing/how-to-print-text-document.md new file mode 100644 index 0000000000..6b2cd27fc5 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/printing/how-to-print-text-document.md @@ -0,0 +1,59 @@ +--- +title: "How to print multi-page text file" +description: Learn how to print multiple page text file (Windows Forms .NET). +ms.date: "05/04/2022" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "printing [Windows Forms], printing multiple pages" + - "text [Windows Forms], printing Windows Forms" + - "Windows Forms, printing text" + - "printing [Windows Forms], text" +ms.custom: devdivchpfy22 +--- + +# How to print a multi-page text file (Windows Forms .NET) + +It's common for Windows-based applications to print text. The class provides methods for drawing objects (graphics or text) to a device, such as a screen or printer. The following section describes in detail the process to print text file. This method doesn't support printing non-plain text files, such as an Office Word document or a _PDF_ file. + +> [!NOTE] +> The methods of are not supported for printing. You should always use the methods of , as shown in the following code example, to draw text for printing purposes. + +## To print text + +01. In Visual Studio, double-click the form you want to print from, in the **Solution Explorer** pane. This opens the Visual Designer. + +01. From the **Toolbox**, double-click the component to add it to the form. This should create a `PrintDocument` component with the name `printDocument1`. + +01. Either add a `Button` to the form, or use a button that is already on the form. + +01. In the Visual Designer of the form, select the button. In the **Properties** pane, select the **Event** filter button and then double-click the `Click` event to generate an event handler. + +01. The `Click` event code should be visible. Outside the scope of the event handler, add a private string variable to the class named `stringToPrint`. + + :::code language="csharp" source="snippets/how-to-print-text-document/csharp/Form1.cs" id="add_string_to_your_form"::: + + :::code language="vb" source="snippets/how-to-print-text-document/vb/Form1.vb" id="add_string_to_your_form"::: + +01. Back in the `Click` event handler code, set the property to the name of the document. This information is sent to the printer. Next, read the document text content and store it in the `stringToPrint` string. Finally, call the method to raise the event. The `Print` method is highlighted below. + + :::code language="csharp" source="snippets/how-to-print-text-document/csharp/Form1.cs" id="set_DocumentName_and_string" highlight= "11"::: + + :::code language="vb" source="snippets/how-to-print-text-document/vb/Form1.vb" id="set_DocumentName_and_string" highlight= "11"::: + +01. Go back to the Visual Designer of the form and select the `PrintDocument` component. On the **Properties** pane, select the **Event** filter and then double-click the `PrintPage` event to generate an event handler. + +01. In the event handler, use the property of the class and the document contents to calculate line length and lines per page. After each page is drawn, check if it's the last page, and set the property of the `PrintPageEventArgs` accordingly. The `PrintPage` event is raised until `HasMorePages` is `false`. + + In the following code example, the event handler is used to print the contents of the "testPage.txt" file in the same font as it's used on the form. + + :::code language="csharp" source="snippets/how-to-print-text-document/csharp/Form1.cs" id="print_contents_using_event_handler"::: + + :::code language="vb" source="snippets/how-to-print-text-document/vb/Form1.vb" id="print_contents_using_event_handler"::: + +## See also + +- +- +- [Windows Forms Print Support](/dotnet/desktop/winforms/advanced/windows-forms-print-support?view=netframeworkdesktop-4.8&preserve-view=true) diff --git a/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/csharp/Form1.Designer.cs b/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/csharp/Form1.Designer.cs new file mode 100644 index 0000000000..109108a7f5 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/csharp/Form1.Designer.cs @@ -0,0 +1,81 @@ +namespace Sample_Print_Application +{ + partial class Form1 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.button1 = new System.Windows.Forms.Button(); + this.label1 = new System.Windows.Forms.Label(); + this.printDocument1 = new System.Drawing.Printing.PrintDocument(); + this.SuspendLayout(); + //register event for PrintDocument1_PrintPage + this.printDocument1.PrintPage += new System.Drawing.Printing.PrintPageEventHandler (PrintDocument1_PrintPage); + // + // button1 + // + this.button1.Font = new System.Drawing.Font("Segoe UI", 18F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); + this.button1.Location = new System.Drawing.Point(313, 247); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(181, 88); + this.button1.TabIndex = 0; + this.button1.Text = "Print"; + this.button1.UseVisualStyleBackColor = true; + this.button1.Click += new System.EventHandler(this.button1_Click); + + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Font = new System.Drawing.Font("Segoe UI", 24F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point); + this.label1.Location = new System.Drawing.Point(260, 96); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(285, 65); + this.label1.TabIndex = 1; + this.label1.Text = "Print Demo"; + + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.label1); + this.Controls.Add(this.button1); + this.Name = "Form1"; + this.Text = "Form1"; + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private Button button1; + private Label label1; + private System.Drawing.Printing.PrintDocument printDocument1; + } +} diff --git a/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/csharp/Form1.cs b/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/csharp/Form1.cs new file mode 100644 index 0000000000..66ba2db2d2 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/csharp/Form1.cs @@ -0,0 +1,55 @@ +namespace Sample_Print_Application +{ + public partial class Form1 : Form + { + // + private string stringToPrint=""; + // + + public Form1() + { + InitializeComponent(); + } + + // + private void PrintDocument1_PrintPage(object sender, System.Drawing.Printing.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); + } + // + + // + private void button1_Click(object sender, EventArgs e) + { + string docName = "testPage.txt"; + string docPath = @"C:\"; + string fullPath = System.IO.Path.Combine(docPath, docName); + + printDocument1.DocumentName = docName; + + stringToPrint = System.IO.File.ReadAllText(fullPath); + + // + printDocument1.Print(); + // + } + // + } +} diff --git a/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/csharp/Form1.resx b/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/csharp/Form1.resx new file mode 100644 index 0000000000..7ea9f6e57c --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/csharp/Form1.resx @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + + 204, 17 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/csharp/Program.cs b/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/csharp/Program.cs new file mode 100644 index 0000000000..b2895db976 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/csharp/Program.cs @@ -0,0 +1,17 @@ +namespace Sample_Print_Application +{ + internal static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + // To customize application configuration such as set high DPI settings or default font, + // see https://aka.ms/applicationconfiguration. + ApplicationConfiguration.Initialize(); + Application.Run(new Form1()); + } + } +} \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/csharp/Sample_Print_Application.csproj b/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/csharp/Sample_Print_Application.csproj new file mode 100644 index 0000000000..b57c89e694 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/csharp/Sample_Print_Application.csproj @@ -0,0 +1,11 @@ + + + + WinExe + net6.0-windows + enable + true + enable + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/vb/ApplicationEvents.vb b/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/vb/ApplicationEvents.vb new file mode 100644 index 0000000000..cf403a009a --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/vb/ApplicationEvents.vb @@ -0,0 +1,29 @@ +Imports Microsoft.VisualBasic.ApplicationServices + +Namespace My + ' The following events are available for MyApplication: + ' Startup: Raised when the application starts, before the startup form is created. + ' Shutdown: Raised after all application forms are closed. This event is not raised if the application terminates abnormally. + ' UnhandledException: Raised if the application encounters an unhandled exception. + ' StartupNextInstance: Raised when launching a single-instance application and the application is already active. + ' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected. + + ' **NEW** ApplyApplicationDefaults: Raised when the application queries default values to be set for the application. + + ' Example: + ' Private Sub MyApplication_ApplyApplicationDefaults(sender As Object, e As ApplyApplicationDefaultsEventArgs) Handles Me.ApplyApplicationDefaults + ' + ' ' Setting the application-wide default Font: + ' e.Font = New Font(FontFamily.GenericSansSerif, 12, FontStyle.Regular) + ' + ' ' Setting the HighDpiMode for the Application: + ' e.HighDpiMode = HighDpiMode.PerMonitorV2 + ' + ' ' If a splash dialog is used, this sets the minimum display time: + ' e.MinimumSplashScreenDisplayTime = 4000 + ' End Sub + + Partial Friend Class MyApplication + + End Class +End Namespace diff --git a/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/vb/Form1.Designer.vb b/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/vb/Form1.Designer.vb new file mode 100644 index 0000000000..d206402f3e --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/vb/Form1.Designer.vb @@ -0,0 +1,70 @@ + +Partial Class Form1 + Inherits System.Windows.Forms.Form + + 'Form overrides dispose to clean up the component list. + + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + Try + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + Finally + MyBase.Dispose(disposing) + End Try + End Sub + + 'Required by the Windows Form Designer + Private components As System.ComponentModel.IContainer + + 'NOTE: The following procedure is required by the Windows Form Designer + 'It can be modified using the Windows Form Designer. + 'Do not modify it using the code editor. + + Private Sub InitializeComponent() + Me.Button1 = New System.Windows.Forms.Button() + Me.Label1 = New System.Windows.Forms.Label() + Me.PrintDocument1 = New System.Drawing.Printing.PrintDocument() + Me.SuspendLayout() + ' + 'Button1 + ' + Me.Button1.Font = New System.Drawing.Font("Segoe UI", 22.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point) + Me.Button1.Location = New System.Drawing.Point(288, 229) + Me.Button1.Name = "Button1" + Me.Button1.Size = New System.Drawing.Size(182, 63) + Me.Button1.TabIndex = 0 + Me.Button1.Text = "Print" + Me.Button1.UseVisualStyleBackColor = True + ' + 'Label1 + ' + Me.Label1.AutoSize = True + Me.Label1.Font = New System.Drawing.Font("Segoe UI", 24.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point) + Me.Label1.Location = New System.Drawing.Point(261, 87) + Me.Label1.Name = "Label1" + Me.Label1.Size = New System.Drawing.Size(285, 65) + Me.Label1.TabIndex = 1 + Me.Label1.Text = "Print Demo" + ' + 'PrintDocument1 + ' + ' + 'Form1 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(10.0!, 25.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(800, 450) + Me.Controls.Add(Me.Label1) + Me.Controls.Add(Me.Button1) + Me.Name = "Form1" + Me.Text = "Form1" + Me.ResumeLayout(False) + Me.PerformLayout() + + End Sub + + Friend WithEvents Button1 As Button + Friend WithEvents Label1 As Label + Friend WithEvents PrintDocument1 As Printing.PrintDocument +End Class diff --git a/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/vb/Form1.resx b/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/vb/Form1.resx new file mode 100644 index 0000000000..7dd0dc36a3 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/vb/Form1.resx @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/vb/Form1.vb b/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/vb/Form1.vb new file mode 100644 index 0000000000..abfaa7c7fe --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/vb/Form1.vb @@ -0,0 +1,56 @@ +Imports System.IO +Imports System.Drawing +Imports System.Drawing.Printing +Imports System.Windows.Forms + +Public Class Form1 + + ' + 'Private PrintDocument1 As New PrintDocument() + Private stringToPrint As String + ' + + ' + Private 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 + + End Sub + ' + + ' + Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click + + Dim docName As String = "testPage.txt" + Dim docPath As String = "C:\" + Dim fullPath As String = System.IO.Path.Combine(docPath, docName) + + PrintDocument1.DocumentName = docName + + stringToPrint = System.IO.File.ReadAllText(fullPath) + + ' + PrintDocument1.Print() + ' + + End Sub + ' + +End Class diff --git a/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/vb/My Project/Application.Designer.vb b/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/vb/My Project/Application.Designer.vb new file mode 100644 index 0000000000..455b434179 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/vb/My Project/Application.Designer.vb @@ -0,0 +1,38 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:4.0.30319.42000 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + +Namespace My + + 'NOTE: This file is auto-generated; do not modify it directly. To make changes, + ' or if you encounter build errors in this file, go to the Project Designer + ' (go to Project Properties or double-click the My Project node in + ' Solution Explorer), and make changes on the Application tab. + ' + Partial Friend Class MyApplication + + _ + Public Sub New() + MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows) + Me.IsSingleInstance = false + Me.EnableVisualStyles = true + Me.SaveMySettingsOnExit = true + Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses + End Sub + + _ + Protected Overrides Sub OnCreateMainForm() + Me.MainForm = Global.SamplePrintApp.Form1 + End Sub + End Class +End Namespace diff --git a/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/vb/My Project/Application.myapp b/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/vb/My Project/Application.myapp new file mode 100644 index 0000000000..0f12f32388 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/vb/My Project/Application.myapp @@ -0,0 +1,10 @@ + + + true + Form1 + false + 0 + true + 0 + true + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/vb/SamplePrintApp.vbproj b/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/vb/SamplePrintApp.vbproj new file mode 100644 index 0000000000..13928b7a2d --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/printing/snippets/how-to-print-text-document/vb/SamplePrintApp.vbproj @@ -0,0 +1,32 @@ + + + + WinExe + net6.0-windows + Sub Main + true + WindowsForms + + + + + + + + + + + True + True + Application.myapp + + + + + + MyApplicationCodeGenerator + Application.Designer.vb + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/winforms/toc.yml b/dotnet-desktop-guide/net/winforms/toc.yml index 342496ad9a..d67b9ebd27 100644 --- a/dotnet-desktop-guide/net/winforms/toc.yml +++ b/dotnet-desktop-guide/net/winforms/toc.yml @@ -103,3 +103,5 @@ items: items: - name: Overview href: printing/overview.md + - name: Print a multi-page text file + href: printing/how-to-print-text-document.md