Печать изображений с помощью System.Drawing
В этом разделе
UI-контрол
ImagePrintDocument, который является производным от UI-контрола System.Drawing.Printing.PrintDocument, используется для печати и предварительного просмотра изображений в WinForms.
По умолчанию UI-контрол
ImagePrintDocument печатает все изображение без масштабирования, изображение делится на страницы, если все изображение не может быть напечатано на одной странице.
Также UI-контрол позволяет масштабировать изображение при печати, режим масштабирования можно выбрать с помощью свойства
ImagePrintDocument.PrintScaleMode.
Поддерживаются следующие режимы масштабирования изображения:
-
Режим PrintScaleMode.None
Изображение будет отображаться без мсштабирования и изображение будет разделено на несколько частей в соответствии с полями страницы и размером изображения, разрешением принтера и разрешением изображения.
-
Режим PrintScaleMode.BestFit
Размер изображения будет изменен таким образом, чтобы оно вписывалось в поля страницы. Пропорции изображения не изменяются.
-
Режим PrintScaleMode.Stretch
Размер изображения будет изменен, чтобы заполнить страницу.
-
Режим PrintScaleMode.CropToPageSize
Изображение будет обрезано, чтобы вписаться в поля страницы.
-
Режим PrintScaleMode.Mozaic
Выбранный набор изображений будет объединен на одной странице в мозаичном порядке.
Перед началом печати можно задать поля для всех страниц, выбранных для печати, с помощью диалога System.Windows.Forms.PageSetupDialog.
В процессе печати поля для печатаемой страницы можно задать в обработчике события System.Drawing.Printing.PrintDocument.PrintPage с помощью свойства Margins класса System.Drawing.Printing.PageSettings.
Изображение можно центрировать на странице при печати с помощью свойства
ImagePrintDocument.Center.
UI-контрол
ImagePrintDocument использует стандартный диалог настроек WinForms, реализованный в классе System.Windows.Forms.PrintDialog, для выбора устройства печати и настройки параметров печати.
Во время печати UI-контрол
ImagePrintDocument генерирует набор событий, которые позволяют получать подробную информацию о процессе печати и контролировать все аспекты печати:
- System.Drawing.Printing.PrintDocument.BeginPrint - происходит при вызове метода System.Drawing.Printing.PrintDocument.Print и перед печатью первой страницы документа.
- System.Drawing.Printing.PrintDocument.EndPrint - происходит, когда напечатана последняя страница документа.
- System.Drawing.Printing.PrintDocument.PrintPage - происходит перед печатью каждой страницы.
- ImagePrintDocument.PrintImage - происходит, когда принтеру нужно напечатать следующее изображение.
- ImagePrintDocument.ImagePrinting - происходит, когда изображение печатается на странице.
- ImagePrintDocument.ImagePrinted - происходит, когда изображение напечатано на странице.
Вот C#/VB.NET код, который демонстрирует, как распечатать коллекцию изображений с настройками печати по умолчанию, каждое изображение из коллекции будет напечатано на отдельной странице, каждое изображение будет масштабировано на странице в режиме BestFit:
Vintasoft.Imaging.ImageCollection _printingImages;
int _printingImageIndex;
public void PrintImagesOnDefaultPrinter(Vintasoft.Imaging.ImageCollection images)
{
// save information about printing image collection in global variable
_printingImages = images;
_printingImageIndex = 0;
// create print manager
Vintasoft.Imaging.Print.ImagePrintDocument imagePrintDocument =
new Vintasoft.Imaging.Print.ImagePrintDocument();
// specify that each image must be resized to fit within the page margins,
// image proportions are not changed
imagePrintDocument.PrintScaleMode = Vintasoft.Imaging.Print.PrintScaleMode.BestFit;
// subscribe to the PrintImage event
imagePrintDocument.PrintImage +=
new System.EventHandler<Vintasoft.Imaging.Print.PrintImageEventArgs>(imagePrintDocument_PrintImage);
// start print
imagePrintDocument.Print();
}
private void imagePrintDocument_PrintImage(object sender, Vintasoft.Imaging.Print.PrintImageEventArgs e)
{
e.Image = _printingImages[_printingImageIndex];
_printingImageIndex++;
if (_printingImageIndex >= _printingImages.Count)
{
Vintasoft.Imaging.Print.ImagePrintDocument imagePrintDocument =
(Vintasoft.Imaging.Print.ImagePrintDocument)sender;
// unsubscribe from the PrintImage event
imagePrintDocument.PrintImage -=
new System.EventHandler<Vintasoft.Imaging.Print.PrintImageEventArgs>(imagePrintDocument_PrintImage);
// indicate that there is no more images to print
e.HasMoreImages = false;
}
else
{
// indicate that there are additional images to print
e.HasMoreImages = true;
}
}
Private _printingImages As Vintasoft.Imaging.ImageCollection
Private _printingImageIndex As Integer
Public Sub PrintImagesOnDefaultPrinter(images As Vintasoft.Imaging.ImageCollection)
' save information about printing image collection in global variable
_printingImages = images
_printingImageIndex = 0
' create print manager
Dim imagePrintDocument As New Vintasoft.Imaging.Print.ImagePrintDocument()
' specify that each image must be resized to fit within the page margins,
' image proportions are not changed
imagePrintDocument.PrintScaleMode = Vintasoft.Imaging.Print.PrintScaleMode.BestFit
' subscribe to the PrintImage event
AddHandler imagePrintDocument.PrintImage, New System.EventHandler(Of Vintasoft.Imaging.Print.PrintImageEventArgs)(AddressOf imagePrintDocument_PrintImage)
' start print
imagePrintDocument.Print()
End Sub
Private Sub imagePrintDocument_PrintImage(sender As Object, e As Vintasoft.Imaging.Print.PrintImageEventArgs)
e.Image = _printingImages(_printingImageIndex)
_printingImageIndex += 1
If _printingImageIndex >= _printingImages.Count Then
Dim imagePrintDocument As Vintasoft.Imaging.Print.ImagePrintDocument = DirectCast(sender, Vintasoft.Imaging.Print.ImagePrintDocument)
' unsubscribe from the PrintImage event
RemoveHandler imagePrintDocument.PrintImage, New System.EventHandler(Of Vintasoft.Imaging.Print.PrintImageEventArgs)(AddressOf imagePrintDocument_PrintImage)
' indicate that there is no more images to print
e.HasMoreImages = False
Else
' indicate that there are additional images to print
e.HasMoreImages = True
End If
End Sub
Вот C#/VB.NET код, который демонстрирует, как выбрать принтер, запустить печать коллекции изображений иотменить печать после того, как будет напечатана первая половина коллекции изображений:
Vintasoft.Imaging.ImageCollection _printingImages;
int _printingImageIndex;
public void PrintImagesAndCancel(Vintasoft.Imaging.ImageCollection images)
{
// save information about printing image collection in global variable
_printingImages = images;
_printingImageIndex = 0;
// create print manager
Vintasoft.Imaging.Print.ImagePrintDocument imagePrintDocument =
new Vintasoft.Imaging.Print.ImagePrintDocument();
// specify that each image must be resized to fit within the page margins,
// image proportions is not changed
imagePrintDocument.PrintScaleMode = Vintasoft.Imaging.Print.PrintScaleMode.BestFit;
// create an instance of PrintDialog class
System.Windows.Forms.PrintDialog printDialog1 =
new System.Windows.Forms.PrintDialog();
// specify that printer settings should be obtain for imagePrintDocument
printDialog1.Document = imagePrintDocument;
// if printer is not selected
if (printDialog1.ShowDialog() != System.Windows.Forms.DialogResult.OK)
// exit
return;
// subscribe to the PrintImage event
imagePrintDocument.PrintImage +=
new System.EventHandler<Vintasoft.Imaging.Print.PrintImageEventArgs>(imagePrintDocument_PrintImageAndCancel);
// start print
imagePrintDocument.Print();
}
private void imagePrintDocument_PrintImageAndCancel(object sender, Vintasoft.Imaging.Print.PrintImageEventArgs e)
{
if ((_printingImageIndex >= _printingImages.Count) ||
(_printingImageIndex >= (_printingImages.Count / 2)))
{
Vintasoft.Imaging.Print.ImagePrintDocument imagePrintDocument =
(Vintasoft.Imaging.Print.ImagePrintDocument)sender;
// unsubscribe from the PrintImage event
imagePrintDocument.PrintImage -=
new System.EventHandler<Vintasoft.Imaging.Print.PrintImageEventArgs>(imagePrintDocument_PrintImageAndCancel);
// indicate that there is no more images to print
e.HasMoreImages = false;
return;
}
e.Image = _printingImages[_printingImageIndex];
_printingImageIndex++;
}
Private _printingImages As Vintasoft.Imaging.ImageCollection
Private _printingImageIndex As Integer
Public Sub PrintImagesAndCancel(images As Vintasoft.Imaging.ImageCollection)
' save information about printing image collection in global variable
_printingImages = images
_printingImageIndex = 0
' create print manager
Dim imagePrintDocument As New Vintasoft.Imaging.Print.ImagePrintDocument()
' specify that each image must be resized to fit within the page margins,
' image proportions is not changed
imagePrintDocument.PrintScaleMode = Vintasoft.Imaging.Print.PrintScaleMode.BestFit
' create an instance of PrintDialog class
Dim printDialog1 As New System.Windows.Forms.PrintDialog()
' specify that printer settings should be obtain for imagePrintDocument
printDialog1.Document = imagePrintDocument
' if printer is not selected
If printDialog1.ShowDialog() <> System.Windows.Forms.DialogResult.OK Then
' exit
Return
End If
' subscribe to the PrintImage event
AddHandler imagePrintDocument.PrintImage, New System.EventHandler(Of Vintasoft.Imaging.Print.PrintImageEventArgs)(AddressOf imagePrintDocument_PrintImageAndCancel)
' start print
imagePrintDocument.Print()
End Sub
Private Sub imagePrintDocument_PrintImageAndCancel(sender As Object, e As Vintasoft.Imaging.Print.PrintImageEventArgs)
If (_printingImageIndex >= _printingImages.Count) OrElse (_printingImageIndex >= (_printingImages.Count \ 2)) Then
Dim imagePrintDocument As Vintasoft.Imaging.Print.ImagePrintDocument = DirectCast(sender, Vintasoft.Imaging.Print.ImagePrintDocument)
' unsubscribe from the PrintImage event
RemoveHandler imagePrintDocument.PrintImage, New System.EventHandler(Of Vintasoft.Imaging.Print.PrintImageEventArgs)(AddressOf imagePrintDocument_PrintImageAndCancel)
' indicate that there is no more images to print
e.HasMoreImages = False
Return
End If
e.Image = _printingImages(_printingImageIndex)
_printingImageIndex += 1
End Sub
Вот C#/VB.NET код, который демонстрирует, как распечатать все изображения из коллекции изображений, кроме второго:
Vintasoft.Imaging.ImageCollection _printingImages;
int _printingImageIndex;
public void PrintImagesAndSuppressSecondImage(Vintasoft.Imaging.ImageCollection images)
{
// save information about printing image collection in global variable
_printingImages = images;
_printingImageIndex = 0;
// create print manager
Vintasoft.Imaging.Print.ImagePrintDocument imagePrintDocument =
new Vintasoft.Imaging.Print.ImagePrintDocument();
// subscribe to the PrintImage event
imagePrintDocument.PrintImage +=
new System.EventHandler<Vintasoft.Imaging.Print.PrintImageEventArgs>(imagePrintDocument_PrintImageAndSuppress);
// start print
imagePrintDocument.Print();
}
private void imagePrintDocument_PrintImageAndSuppress(object sender, Vintasoft.Imaging.Print.PrintImageEventArgs e)
{
if (_printingImageIndex == 1)
_printingImageIndex++;
if (_printingImageIndex >= _printingImages.Count)
{
Vintasoft.Imaging.Print.ImagePrintDocument imagePrintDocument =
(Vintasoft.Imaging.Print.ImagePrintDocument)sender;
// unsubscribe from the PrintImage event
imagePrintDocument.PrintImage -=
new System.EventHandler<Vintasoft.Imaging.Print.PrintImageEventArgs>(imagePrintDocument_PrintImageAndSuppress);
// indicate that there is no more images to print
e.HasMoreImages = false;
return;
}
e.Image = _printingImages[_printingImageIndex];
_printingImageIndex++;
}
Private _printingImages As Vintasoft.Imaging.ImageCollection
Private _printingImageIndex As Integer
Public Sub PrintImagesAndSuppressSecondImage(images As Vintasoft.Imaging.ImageCollection)
' save information about printing image collection in global variable
_printingImages = images
_printingImageIndex = 0
' create print manager
Dim imagePrintDocument As New Vintasoft.Imaging.Print.ImagePrintDocument()
' subscribe to the PrintImage event
AddHandler imagePrintDocument.PrintImage, New System.EventHandler(Of Vintasoft.Imaging.Print.PrintImageEventArgs)(AddressOf imagePrintDocument_PrintImageAndSuppress)
' start print
imagePrintDocument.Print()
End Sub
Private Sub imagePrintDocument_PrintImageAndSuppress(sender As Object, e As Vintasoft.Imaging.Print.PrintImageEventArgs)
If _printingImageIndex = 1 Then
_printingImageIndex += 1
End If
If _printingImageIndex >= _printingImages.Count Then
Dim imagePrintDocument As Vintasoft.Imaging.Print.ImagePrintDocument = DirectCast(sender, Vintasoft.Imaging.Print.ImagePrintDocument)
' unsubscribe from the PrintImage event
RemoveHandler imagePrintDocument.PrintImage, New System.EventHandler(Of Vintasoft.Imaging.Print.PrintImageEventArgs)(AddressOf imagePrintDocument_PrintImageAndSuppress)
' indicate that there is no more images to print
e.HasMoreImages = False
Return
End If
e.Image = _printingImages(_printingImageIndex)
_printingImageIndex += 1
End Sub
Пример кода, показывающий, как добавить верхний и/или нижний колонтитул к печатаемому изображению или странице,можно найти в демо приложении PrintDemo, которое доступно в дистрибутиве SDK.
Предварительный просмотр изображений для печати
UI-контрол
ImagePrintDocument может использовать UI-контрол System.Windows.Forms.PrintPreviewControl для предварительного просмотра изображений при печати.
Во время предварительного просмотра UI-контрол System.Windows.Forms.PrintPreviewControl позволяет:
- определить уровень масштабирования - System.Windows.Forms.PrintPreviewControl.Zoom.
- определить количество страниц, которые должны быть показаны горизонтально/вертикально в просмотрщике предварительного просмотра - System.Windows.Forms.PrintPreviewControl.Columns, System.Windows.Forms.PrintPreviewControl.Rows.
- обновить средство предварительного просмотра - System.Windows.Forms.PrintPreviewControl.InvalidatePreview.
Хороший пример, демонстрирующий реализацию предварительного просмотра печати коллекции изображений, доступен в демо приложении PrintDemo, которое доступно в дистрибутиве SDK.
Печать изображений с аннотациями
UI-контрол
AnnotatedImagePrintDocument, производный от UI-контрола
ImagePrintDocument, должен использоваться для печати и предварительного просмотра изображений с аннотациями.
UI-контрол
AnnotatedImagePrintDocument печатает аннотации в векторном виде, что обеспечивает более эффективное использование памяти и большую производительность, чем при растеризации аннотаций на клоне изображения перед печатью. UI-контрол
AnnotatedImagePrintDocument будет работать как UI-контрол
ImagePrintDocument, если значение свойства
AnnotatedImagePrintDocument.PrintAnnotations установлено на false.