Take the following steps to start a project and to add some code that prints an image:
Start Visual Studio .NET
Choose File->New->Project... from the menu
In the New Project dialog box, choose either "Visual C#" or "VB" in the Projects Type List, and choose "Windows Forms Application" in the Templates List
Enter the project name as "PrintImageTutorial" in the Name field, and then click OK. If desired, type a new location for your project or select a directory using the Browse button, and then click OK
In the "Solution Explorer" window, right-click on the project and select "Add Reference..." from the context menu. In the "Add Reference" dialog box, select the ".NET" tab and select the following components - If you used the LEADTOOLS Setup, the LEADTOOLS components will be visible under the .NET components and you should select them from the list, otherwise, select the "Browse" tab and browse to the LEADTOOLS setup folder - Default location is: <LEADTOOLS_INSTALLDIR>\Bin\Dotnet4\Win32
The above references will allow you to use BMP, JPG and TIF files. If you require more file formats, please refer to the File Formats section in the Files To Be Included With Your Application topic
Since we are going to use the Win32 (x86) assembly references, we must change the build target of this project to be x86. Select Project->PrintImageTutorial Properties from the main menu and in the project properties dialog, and follow the following steps:
For the C# project, select the Build tab, select "All Configurations" from the Configuration drop down selection box and select "x86" from the Platform target drop down selection box
For the VB project, select the Compile tab and select "All Configurations" from the Configuration drop down selection box. Click the Advanced Compile Options button and select "x86" from the Target CPU drop down selection box and click OK to close the dialog.
Make sure Form1 is in design view. From the toolbox (View->Toolbox from the main menu), drag and drop a MenuStrip control to the form. Click on the new menuStrip1 control and add the following top-level menu items:
| Type | Name | Text | Shortcut Keys |
|---|---|---|---|
| ToolStripMenuItem | fileToolStripMenuItem | File | |
| ToolStripMenuItem | pageToolStripMenuItem | Page | |
| ToolStripMenuItem | optionsToolStripMenuItem | Options |
| Type | Name | Text | Shortcut Keys |
|---|---|---|---|
| ToolStripMenuItem | openToolStripMenuItem | Open... | Ctrl+O |
| ToolStripSeparator | toolStripMenuItem1 | ||
| ToolStripMenuItem | printPreviewToolStripMenuItem | Print preview | |
| ToolStripMenuItem | printSetupToolStripMenuItem | Print setup... | |
| ToolStripMenuItem | printToolStripMenuItem | Print... | Ctrl+P |
| ToolStripSeparator | toolStripMenuItem2 | ||
| ToolStripMenuItem | exitToolStripMenuItem | Exit |
| Type | Name | Text | Shortcut Keys |
|---|---|---|---|
| ToolStripMenuItem | firstPageToolStripMenuItem | First page | |
| ToolStripMenuItem | previousPageToolStripMenuItem | Previous page | |
| ToolStripMenuItem | nextPageToolStripMenuItem | Next page | |
| ToolStripMenuItem | lastPageToolStripMenuItem | Last page |
| Type | Name | Text | Shortcut Keys |
|---|---|---|---|
| ToolStripMenuItem | usePageMarginsToolStripMenuItem | Use page margins | |
| ToolStripMenuItem | fitImageToPageToolStripMenuItem | Fit image to page |
| Property | Value |
|---|---|
| Dock | Fill |
| UseDpi | True |
Switch to Form1 code view (right-click Form1 in the solution explorer then select View Code) and add the following lines at the beginning of the file:
Imports System.Drawing.PrintingImports LeadtoolsImports Leadtools.CodecsImports Leadtools.WinForms
using System.Drawing.Printing;using Leadtools;using Leadtools.Codecs;using Leadtools.WinForms;
Add the following private variables to Form1:
' The RasterCodecs object to use when loading imagesPrivate _rasterCodecs As RasterCodecs' The PrintDocument object we will be using throughout this demoPrivate _printDocument As PrintDocument' The current page number bring printedPrivate _currentPrintPageNumber As Integer' The current image file namePrivate _currentImageFileName As String
// The RasterCodecs object to use when loading imagesprivate RasterCodecs _rasterCodecs;// The PrintDocument object we will be using throughout this demoprivate PrintDocument _printDocument;// The current page number bring printedprivate int _currentPrintPageNumber;// The current image file nameprivate string _currentImageFileName;
Add the following code to Form1:
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)' Initialize the RasterCodecs object to use when loading imageMe._rasterCodecs = New RasterCodecs()' Check if we have any printers installedIf IsNothing(PrinterSettings.InstalledPrinters) OrElse (PrinterSettings.InstalledPrinters.Count < 1) ThenMessageBox.Show( _Me, _"No printer installed on this machine, this tutorial cannot continue", _"PrintImageTutorial", _MessageBoxButtons.OK, _MessageBoxIcon.Exclamation)Me.Close()Else' Create the print document object we will be usingMe._printDocument = New PrintDocument()' Add handlers for the print eventsAddHandler Me._printDocument.BeginPrint, AddressOf _printDocument_BeginPrintAddHandler Me._printDocument.PrintPage, AddressOf _printDocument_PrintPageAddHandler Me._printDocument.EndPrint, AddressOf _printDocument_EndPrintEnd IfMyBase.OnLoad(e)End SubProtected Overrides Sub OnFormClosed(ByVal e As System.Windows.Forms.FormClosedEventArgs)' Dispose the resources we are usingIf Not IsNothing(Me._printDocument) ThenMe._printDocument.Dispose()End IfIf Not IsNothing(Me._rasterCodecs) ThenMe._rasterCodecs.Dispose()End IfMyBase.OnFormClosed(e)End Sub
protected override void OnLoad(EventArgs e){// Initialize the RasterCodecs object to use when loading imagethis._rasterCodecs = new RasterCodecs();// Check if we have any printers installedif(PrinterSettings.InstalledPrinters == null || PrinterSettings.InstalledPrinters.Count < 1){MessageBox.Show(this,"No printer installed on this machine, this tutorial cannot continue","PrintImageTutorial",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);this.Close();}else{// Create the print document object we will be usingthis._printDocument = new PrintDocument();// Add handlers for the print eventsthis._printDocument.BeginPrint += new PrintEventHandler(_printDocument_BeginPrint);this._printDocument.PrintPage += new PrintPageEventHandler(_printDocument_PrintPage);this._printDocument.EndPrint += new PrintEventHandler(_printDocument_EndPrint);}base.OnLoad(e);}protected override void OnFormClosed(FormClosedEventArgs e){// Dispose the resources we are usingif(this._printDocument != null){this._printDocument.Dispose();}if(this._rasterCodecs != null){this._rasterCodecs.Dispose();}base.OnFormClosed(e);}
Add the following code to the DropDownOpening event of the fileToolStripMenuItem menu item:
Private Sub fileToolStripMenuItem_DropDownOpening(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles fileToolStripMenuItem.DropDownOpening' Update the UI stateprintPreviewToolStripMenuItem.Enabled = Not IsNothing(rasterImageViewer1.Image)printToolStripMenuItem.Enabled = Not IsNothing(rasterImageViewer1.Image)End Sub
private void fileToolStripMenuItem_DropDownOpening(object sender, EventArgs e){// Update the UI stateprintPreviewToolStripMenuItem.Enabled = (rasterImageViewer1.Image != null);printToolStripMenuItem.Enabled = (rasterImageViewer1.Image != null);}
Add the following code to the Click event of the openToolStripMenuItem menu item:
Private Sub openToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles openToolStripMenuItem.Click' Load an image into the viewerUsing dlg As New OpenFileDialog()dlg.Filter = "All Files|*.*"If dlg.ShowDialog(Me) = DialogResult.OK ThenTry' Load all the pages in the filerasterImageViewer1.Image = Me._rasterCodecs.Load(dlg.FileName)Me._currentImageFileName = dlg.FileNameUpdateCaption()Catch ex As ExceptionMessageBox.Show(Me, ex.Message, "PrintImageTutorial", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)End TryEnd IfEnd UsingEnd Sub
private void openToolStripMenuItem_Click(object sender, EventArgs e){// Load an image into the viewerusing(OpenFileDialog dlg = new OpenFileDialog()){dlg.Filter = "All Files|*.*";if(dlg.ShowDialog(this) == DialogResult.OK){try{// Load all the pages in the filerasterImageViewer1.Image = this._rasterCodecs.Load(dlg.FileName);this._currentImageFileName = dlg.FileName;UpdateCaption();}catch(Exception ex){MessageBox.Show(this, ex.Message, "PrintImageTutorial", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);}}}}
Add the following code to the Click event of the printPreviewToolStripMenuItem menu item:
Private Sub printPreviewToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles printPreviewToolStripMenuItem.Click' Set the print documentSetupPrintDocument()' Use the .NET PrintPreviewDialogUsing dlg As New PrintPreviewDialog()' Show the dialogdlg.Document = Me._printDocumentdlg.WindowState = FormWindowState.Maximizeddlg.ShowDialog(Me)End UsingEnd Sub
private void printPreviewToolStripMenuItem_Click(object sender, EventArgs e){// Set the print documentSetupPrintDocument();// Use the .NET PrintPreviewDialogusing(PrintPreviewDialog dlg = new PrintPreviewDialog()){// Show the dialogdlg.Document = this._printDocument;dlg.WindowState = FormWindowState.Maximized;dlg.ShowDialog(this);}}
Add the following code to the Click event of the printSetupToolStripMenuItem menu item:
Private Sub printSetupToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles printSetupToolStripMenuItem.Click' Use the .NET PageSetupDialogUsing dlg As New PageSetupDialog()dlg.Document = Me._printDocumentdlg.ShowDialog(Me)End UsingEnd Sub
private void printSetupToolStripMenuItem_Click(object sender, EventArgs e){// Use the .NET PageSetupDialogusing(PageSetupDialog dlg = new PageSetupDialog()){dlg.Document = this._printDocument;dlg.ShowDialog(this);}}
Add the following code to the Click event of the printToolStripMenuItem menu item:
Private Sub printToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles printToolStripMenuItem.Click' User might press the shortcut key, so we need to check' if we are in a valid print state even though we disabled' the menu itemIf IsNothing(rasterImageViewer1.Image) ThenReturnEnd If' Directly print with showing the print preview dialog' Set the print documentSetupPrintDocument()Me._printDocument.Print()End Sub
private void printToolStripMenuItem_Click(object sender, EventArgs e){// User might press the shortcut key, so we need to check// if we are in a valid print state even though we disabled// the menu itemif(rasterImageViewer1.Image == null){return;}// Directly print with showing the print preview dialog// Set the print documentSetupPrintDocument();this._printDocument.Print();}
Add the following code to the Click event of the exitToolStripMenuItem menu item:
Private Sub exitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exitToolStripMenuItem.Click' Close the applicationClose()End Sub
private void exitToolStripMenuItem_Click(object sender, EventArgs e){// Close the applicationClose();}
Add the following code to the DropDownOpening event of the pageToolStripMenuItem menu item:
Private Sub pageToolStripMenuItem_DropDownOpening(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles pageToolStripMenuItem.DropDownOpening' Update the UI statefirstPageToolStripMenuItem.Enabled = Not IsNothing(rasterImageViewer1.Image) AndAlso (rasterImageViewer1.Image.Page > 1)previousPageToolStripMenuItem.Enabled = firstPageToolStripMenuItem.EnablednextPageToolStripMenuItem.Enabled = Not IsNothing(rasterImageViewer1.Image) AndAlso (rasterImageViewer1.Image.Page < rasterImageViewer1.Image.PageCount)lastPageToolStripMenuItem.Enabled = nextPageToolStripMenuItem.EnabledEnd Sub
private void pageToolStripMenuItem_DropDownOpening(object sender, EventArgs e){// Update the UI statefirstPageToolStripMenuItem.Enabled = (rasterImageViewer1.Image != null && rasterImageViewer1.Image.Page > 1);previousPageToolStripMenuItem.Enabled = firstPageToolStripMenuItem.Enabled;nextPageToolStripMenuItem.Enabled = (rasterImageViewer1.Image != null && rasterImageViewer1.Image.Page < rasterImageViewer1.Image.PageCount);lastPageToolStripMenuItem.Enabled = nextPageToolStripMenuItem.Enabled;}
Add the following code to the Click event of the firstPageToolStripMenuItem menu item:
Private Sub firstPageToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles firstPageToolStripMenuItem.Click' Go to the first page in the imagerasterImageViewer1.Image.Page = 1UpdateCaption()End Sub
private void firstPageToolStripMenuItem_Click(object sender, EventArgs e){// Go to the first page in the imagerasterImageViewer1.Image.Page = 1;UpdateCaption();}
Add the following code to the Click event of the previousPageToolStripMenuItem menu item:
Private Sub previousPageToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles previousPageToolStripMenuItem.Click' Go to the previous page in the imagerasterImageViewer1.Image.Page = rasterImageViewer1.Image.Page - 1UpdateCaption()End Sub
private void previousPageToolStripMenuItem_Click(object sender, EventArgs e){// Go to the previous page in the imagerasterImageViewer1.Image.Page--;UpdateCaption();}
Add the following code to the Click event of the nextPageToolStripMenuItem menu item:
Private Sub nextPageToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles nextPageToolStripMenuItem.Click' Go to the next page in the imagerasterImageViewer1.Image.Page = rasterImageViewer1.Image.Page + 1UpdateCaption()End Sub
private void nextPageToolStripMenuItem_Click(object sender, EventArgs e){// Go to the next page in the imagerasterImageViewer1.Image.Page++;UpdateCaption();}
Add the following code to the Click event of the lastPageToolStripMenuItem menu item:
Private Sub lastPageToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lastPageToolStripMenuItem.Click' Go to the last page in the imagerasterImageViewer1.Image.Page = rasterImageViewer1.Image.PageCountUpdateCaption()End Sub
private void lastPageToolStripMenuItem_Click(object sender, EventArgs e){// Go to the last page in the imagerasterImageViewer1.Image.Page = rasterImageViewer1.Image.PageCount;UpdateCaption();}
Add the following code to the Click event of the usePageMarginsToolStripMenuItem menu item:
Private Sub usePageMarginsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles usePageMarginsToolStripMenuItem.Click' Toggle the optionusePageMarginsToolStripMenuItem.Checked = Not usePageMarginsToolStripMenuItem.CheckedEnd Sub
private void usePageMarginsToolStripMenuItem_Click(object sender, EventArgs e){// Toggle the optionusePageMarginsToolStripMenuItem.Checked = !usePageMarginsToolStripMenuItem.Checked;}
Add the following code to the Click event of the fitImageToPageToolStripMenuItem menu item:
Private Sub fitImageToPageToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles fitImageToPageToolStripMenuItem.Click' Toggle the optionfitImageToPageToolStripMenuItem.Checked = Not fitImageToPageToolStripMenuItem.CheckedEnd Sub
private void fitImageToPageToolStripMenuItem_Click(object sender, EventArgs e){// Toggle the optionfitImageToPageToolStripMenuItem.Checked = !fitImageToPageToolStripMenuItem.Checked;}
Add the following code to the Form1:
Private Sub UpdateCaption()' Update the caption of this demo to show the loaded image file name' and current page numberIf Not IsNothing(rasterImageViewer1.Image) ThenText = String.Format( _"{0} - Page {1} (of {2}) - PrintImageTutorial", _Me._currentImageFileName, _rasterImageViewer1.Image.Page, _rasterImageViewer1.Image.PageCount)ElseText = "PrintImageTutorial"End IfEnd SubPrivate Sub SetupPrintDocument()' Called before Print Preview or Print to set up the document' Minimum/maximum is the number of pages in the imageMe._printDocument.PrinterSettings.MinimumPage = 1Me._printDocument.PrinterSettings.MaximumPage = rasterImageViewer1.Image.PageCount' Default to print all the pagesMe._printDocument.PrinterSettings.FromPage = Me._printDocument.PrinterSettings.MinimumPageMe._printDocument.PrinterSettings.ToPage = Me._printDocument.PrinterSettings.MaximumPage' Set up the document nameMe._printDocument.DocumentName = Me._currentImageFileNameEnd SubPrivate Sub _printDocument_BeginPrint(ByVal sender As Object, ByVal e As PrintEventArgs)' Reset the page number back to the first pageMe._currentPrintPageNumber = 1End SubPrivate Sub _printDocument_PrintPage(ByVal sender As Object, ByVal e As PrintPageEventArgs)' Print a page here' Get the print document objectDim document As PrintDocument = DirectCast(sender, PrintDocument)' Create an new LEADTOOLS image printer classDim printer As New RasterImagePrinter()' Set the document object so page calculations can be performedprinter.PrintDocument = document' Check if we want to fit the imageIf fitImageToPageToolStripMenuItem.Checked Then' Yes, fit and center the image into the maximum print areaprinter.SizeMode = RasterPaintSizeMode.FitAlwaysprinter.HorizontalAlignMode = RasterPaintAlignMode.Centerprinter.VerticalAlignMode = RasterPaintAlignMode.CenterElse' No, print as normal (original size)printer.SizeMode = RasterPaintSizeMode.Normalprinter.HorizontalAlignMode = RasterPaintAlignMode.Nearprinter.VerticalAlignMode = RasterPaintAlignMode.NearEnd If' Account for FAX images that may have different horizontal and vertical resolutionprinter.UseDpi = True' Print the whole imageprinter.ImageRectangle = Rectangle.Empty' Use maximum page dimension, me will be equivalent of printing' using Windows Photo Galleryprinter.PageRectangle = RectangleF.Empty' Inform the printer whether we want to ignore the page marginsprinter.UseMargins = usePageMarginsToolStripMenuItem.Checked' Print the current pageprinter.Print(rasterImageViewer1.Image, Me._currentPrintPageNumber, e)' Go to the next pageMe._currentPrintPageNumber = Me._currentPrintPageNumber + 1' Inform the printer whether we have more pages to printIf Me._currentPrintPageNumber <= document.PrinterSettings.ToPage Thene.HasMorePages = TrueElsee.HasMorePages = FalseEnd IfEnd SubPrivate Sub _printDocument_EndPrint(ByVal sender As Object, ByVal e As PrintEventArgs)' Nothing to do here in this tutorialEnd Sub
private void UpdateCaption(){// Update the caption of this demo to show the loaded image file name// and current page numberif(rasterImageViewer1.Image != null){Text = string.Format("{0} - Page {1} (of {2}) - PrintImageTutorial",this._currentImageFileName,rasterImageViewer1.Image.Page,rasterImageViewer1.Image.PageCount);}else{Text = "PrintImageTutorial";}}private void SetupPrintDocument(){// Called before Print Preview or Print to set up the document// Minimum/maximum is the number of pages in the imagethis._printDocument.PrinterSettings.MinimumPage = 1;this._printDocument.PrinterSettings.MaximumPage = rasterImageViewer1.Image.PageCount;// Default to print all the pagesthis._printDocument.PrinterSettings.FromPage = this._printDocument.PrinterSettings.MinimumPage;this._printDocument.PrinterSettings.ToPage = this._printDocument.PrinterSettings.MaximumPage;// Set up the document namethis._printDocument.DocumentName = this._currentImageFileName;}private void _printDocument_BeginPrint(object sender, PrintEventArgs e){// Reset the page number back to the first pagethis._currentPrintPageNumber = 1;}private void _printDocument_PrintPage(object sender, PrintPageEventArgs e){// Print a page here// Get the print document objectPrintDocument document = sender as PrintDocument;// Create an new LEADTOOLS image printer classRasterImagePrinter printer = new RasterImagePrinter();// Set the document object so page calculations can be performedprinter.PrintDocument = document;// Check if we want to fit the imageif(fitImageToPageToolStripMenuItem.Checked){// Yes, fit and center the image into the maximum print areaprinter.SizeMode = RasterPaintSizeMode.FitAlways;printer.HorizontalAlignMode = RasterPaintAlignMode.Center;printer.VerticalAlignMode = RasterPaintAlignMode.Center;}else{// No, print as normal (original size)printer.SizeMode = RasterPaintSizeMode.Normal;printer.HorizontalAlignMode = RasterPaintAlignMode.Near;printer.VerticalAlignMode = RasterPaintAlignMode.Near;}// Account for FAX images that may have different horizontal and vertical resolutionprinter.UseDpi = true;// Print the whole imageprinter.ImageRectangle = Rectangle.Empty;// Use maximum page dimension, this will be equivalent of printing// using Windows Photo Galleryprinter.PageRectangle = RectangleF.Empty;// Inform the printer whether we want to ignore the page marginsprinter.UseMargins = usePageMarginsToolStripMenuItem.Checked;// Print the current pageprinter.Print(rasterImageViewer1.Image, this._currentPrintPageNumber, e);// Go to the next pagethis._currentPrintPageNumber++;// Inform the printer whether we have more pages to printif(this._currentPrintPageNumber <= document.PrinterSettings.ToPage){e.HasMorePages = true;}else{e.HasMorePages = false;}}private void _printDocument_EndPrint(object sender, PrintEventArgs e){// Nothing to do here in this tutorial}
Build, and Run the program to test it. NOTE: If you encounter an "Invalid File Format" or "Feature Not Supported" exception, please refer to the topic Invalid File Format/Feature Not Supported.