VintaSoft Imaging .NET SDK 15.2: Документация для .NET разработчика
В этом разделе
Печать изображений в WPF
В этом разделе
Класс WpfImagePrintManager используется для печати и предварительного просмотра изображений в WPF.
По умолчанию класс WpfImagePrintManager печатает все изображение без масштабирования, изображение делится на страницы, если все изображение не может быть напечатано на одной странице.
Также класс позволяет масштабировать изображение при печати, режим масштабирования можно выбрать с помощью свойства WpfImagePrintManager.PrintScaleMode.
Поддерживаются следующие режимы масштабирования изображения:

Перед началом печати можно задать поля для всех страниц, выбранных для печати, с помощью свойства WpfImagePrintManager.PagePadding.

В процессе печати поля для печатаемой страницы можно определить с помощью свойства WpfImagePrintManager.PagePadding.

Отступ для изображения, печатаемого на странице, можно определить с помощью свойства WpfImagePrintManager.ImagePadding.

Изображение может быть отцентрировано на странице при печати с помощью свойства WpfImagePrintManager.Center.


Класс WpfImagePrintManager использует стандартный диалог настроек WPF, реализованный в классе System.Windows.Controls.PrintDialog, для выбора устройства печати и настройки параметров печати.


Во время печати класс WpfImagePrintManager генерирует событие WpfImagePrintManager.PrintingProgress, которое позволяет получить общую информацию о ходе печати и при необходимости отменить печать.
Также во время печати класс WpfImagePrintManager генерирует набор событий, которые позволяют получать подробную информацию о процессе печати и контролировать все аспекты печати:
Вот C#/VB.NET код, который демонстрирует, как распечатать коллекцию изображений с настройками печати по умолчанию, каждое изображение из коллекции будет напечатано на отдельной странице, каждое изображение будет масштабировано на странице в режиме BestFit:
/// <summary>
/// Prints images on default printer.
/// </summary>
/// <param name="images">The images, which must be printed.</param>
public void PrintImagesOnDefaultPrinter(Vintasoft.Imaging.ImageCollection images)
{
    // create print manager
    Vintasoft.Imaging.Wpf.Print.WpfImagePrintManager imagePrintManager =
        new Vintasoft.Imaging.Wpf.Print.WpfImagePrintManager();
    // specify image collection which should be printed
    imagePrintManager.Images = images;
    // specify that each image must be resized to fit within the page margins,
    // image proportions is not changed
    imagePrintManager.PrintScaleMode = Vintasoft.Imaging.Print.PrintScaleMode.BestFit;

    // subscribe to the PrintingProgress event
    imagePrintManager.PrintingProgress +=
        new System.EventHandler<Vintasoft.Imaging.ProgressEventArgs>(imagePrintManager_PrintingProgress);

    // start the printing process
    imagePrintManager.Print("Print task title");
}

/// <summary>
/// Image printing is in progress.
/// </summary>
private void imagePrintManager_PrintingProgress(object sender, Vintasoft.Imaging.ProgressEventArgs e)
{
    // if printing is started
    if (e.Progress == 0)
        System.Console.Write("Printing: ");

    // write the printing progress
    System.Console.Write(string.Format("{0} ", e.Progress));

    // if printing is finished
    if (e.Progress == 100)
    {
        Vintasoft.Imaging.Wpf.Print.WpfImagePrintManager imagePrintManager =
            (Vintasoft.Imaging.Wpf.Print.WpfImagePrintManager)sender;
        // unsubscribe from the PrintingProgress event
        imagePrintManager.PrintingProgress -=
            new System.EventHandler<Vintasoft.Imaging.ProgressEventArgs>(imagePrintManager_PrintingProgress);
    }
}
''' <summary>
''' Prints images on default printer.
''' </summary>
''' <param name="images">The images, which must be printed.</param>
Public Sub PrintImagesOnDefaultPrinter(images As Vintasoft.Imaging.ImageCollection)
    ' create print manager
    Dim imagePrintManager As New Vintasoft.Imaging.Wpf.Print.WpfImagePrintManager()
    ' specify image collection which should be printed
    imagePrintManager.Images = images
    ' specify that each image must be resized to fit within the page margins,
    ' image proportions is not changed
    imagePrintManager.PrintScaleMode = Vintasoft.Imaging.Print.PrintScaleMode.BestFit

    ' subscribe to the PrintingProgress event
    AddHandler imagePrintManager.PrintingProgress, New System.EventHandler(Of Vintasoft.Imaging.ProgressEventArgs)(AddressOf imagePrintManager_PrintingProgress)

    ' start the printing process
    imagePrintManager.Print("Print task title")
End Sub

''' <summary>
''' Image printing is in progress.
''' </summary>
Private Sub imagePrintManager_PrintingProgress(sender As Object, e As Vintasoft.Imaging.ProgressEventArgs)
    ' if printing is started
    If e.Progress = 0 Then
        System.Console.Write("Printing: ")
    End If

    ' write the printing progress
    System.Console.Write(String.Format("{0} ", e.Progress))

    ' if printing is finished
    If e.Progress = 100 Then
        Dim imagePrintManager As Vintasoft.Imaging.Wpf.Print.WpfImagePrintManager = DirectCast(sender, Vintasoft.Imaging.Wpf.Print.WpfImagePrintManager)
        ' unsubscribe from the PrintingProgress event
        RemoveHandler imagePrintManager.PrintingProgress, New System.EventHandler(Of Vintasoft.Imaging.ProgressEventArgs)(AddressOf imagePrintManager_PrintingProgress)
    End If
End Sub



Вот C#/VB.NET код, который демонстрирует, как выбрать принтер, запустить печать коллекции изображений иотменить печать после того, как будет напечатана первая половина коллекции изображений:
/// <summary>
/// Starts image printing and cancels the printing when printing progress is more than 50%.
/// </summary>
/// <param name="images">The images, which must be printed.</param>
public void PrintImagesAndCancel(Vintasoft.Imaging.ImageCollection images)
{
    // create print manager
    Vintasoft.Imaging.Wpf.Print.WpfImagePrintManager imagePrintManager =
        new Vintasoft.Imaging.Wpf.Print.WpfImagePrintManager();
    // specify image collection which should be printed
    imagePrintManager.Images = images;
    // specify that each image must be resized to fit within the page margins,
    // image proportions is not changed
    imagePrintManager.PrintScaleMode = Vintasoft.Imaging.Print.PrintScaleMode.BestFit;

    // create a print dialog
    System.Windows.Controls.PrintDialog printDialog = imagePrintManager.PrintDialog;
    printDialog.MinPage = 1;
    printDialog.MaxPage = (uint)imagePrintManager.Images.Count;
    printDialog.UserPageRangeEnabled = true;

    // show the print dialog
    if (printDialog.ShowDialog() == true)
    {
        // subscribe to the PrintingProgress event
        imagePrintManager.PrintingProgress +=
            new System.EventHandler<Vintasoft.Imaging.ProgressEventArgs>(imagePrintManager_PrintingProgress);

        // start the printing process
        imagePrintManager.Print("Print task title");
    }
}

/// <summary>
/// Image printing is in progress.
/// </summary>
private void imagePrintManager_PrintingProgress(object sender, Vintasoft.Imaging.ProgressEventArgs e)
{
    // if printing is started
    if (e.Progress == 0)
        System.Console.Write("Printing: ");

    // write the printing progress
    System.Console.Write(string.Format("{0} ", e.Progress));

    // if printing progress is more than 50%
    if (e.Progress > 50)
    {
        if (e.CanCancel)
            e.Cancel = true;

        Vintasoft.Imaging.Wpf.Print.WpfImagePrintManager imagePrintManager =
            (Vintasoft.Imaging.Wpf.Print.WpfImagePrintManager)sender;
        // unsubscribe from the PrintingProgress event
        imagePrintManager.PrintingProgress -=
            new System.EventHandler<Vintasoft.Imaging.ProgressEventArgs>(imagePrintManager_PrintingProgress);
    }
}
''' <summary>
''' Starts image printing and cancels the printing when printing progress is more than 50%.
''' </summary>
''' <param name="images">The images, which must be printed.</param>
Public Sub PrintImagesAndCancel(images As Vintasoft.Imaging.ImageCollection)
    ' create print manager
    Dim imagePrintManager As New Vintasoft.Imaging.Wpf.Print.WpfImagePrintManager()
    ' specify image collection which should be printed
    imagePrintManager.Images = images
    ' specify that each image must be resized to fit within the page margins,
    ' image proportions is not changed
    imagePrintManager.PrintScaleMode = Vintasoft.Imaging.Print.PrintScaleMode.BestFit

    ' create a print dialog
    Dim printDialog As System.Windows.Controls.PrintDialog = imagePrintManager.PrintDialog
    printDialog.MinPage = 1
    printDialog.MaxPage = CUInt(imagePrintManager.Images.Count)
    printDialog.UserPageRangeEnabled = True

    ' show the print dialog
    If printDialog.ShowDialog() = True Then
        ' subscribe to the PrintingProgress event
        AddHandler imagePrintManager.PrintingProgress, New System.EventHandler(Of Vintasoft.Imaging.ProgressEventArgs)(AddressOf imagePrintManager_PrintingProgress)

        ' start the printing process
        imagePrintManager.Print("Print task title")
    End If
End Sub

''' <summary>
''' Image printing is in progress.
''' </summary>
Private Sub imagePrintManager_PrintingProgress(sender As Object, e As Vintasoft.Imaging.ProgressEventArgs)
    ' if printing is started
    If e.Progress = 0 Then
        System.Console.Write("Printing: ")
    End If

    ' write the printing progress
    System.Console.Write(String.Format("{0} ", e.Progress))

    ' if printing progress is more than 50%
    If e.Progress > 50 Then
        If e.CanCancel Then
            e.Cancel = True
        End If

        Dim imagePrintManager As Vintasoft.Imaging.Wpf.Print.WpfImagePrintManager = DirectCast(sender, Vintasoft.Imaging.Wpf.Print.WpfImagePrintManager)
        ' unsubscribe from the PrintingProgress event
        RemoveHandler imagePrintManager.PrintingProgress, New System.EventHandler(Of Vintasoft.Imaging.ProgressEventArgs)(AddressOf imagePrintManager_PrintingProgress)
    End If
End Sub



Вот C#/VB.NET код, который демонстрирует, как распечатать все изображения из коллекции изображений, кроме второго:
/// <summary>
/// Starts image printing and suppress the printing of second image.
/// </summary>
/// <param name="images">The images, which must be printed.</param>
public void PrintImagesAndSuppressSecondImage(Vintasoft.Imaging.ImageCollection images)
{
    // create print manager
    Vintasoft.Imaging.Wpf.Print.WpfImagePrintManager imagePrintManager =
        new Vintasoft.Imaging.Wpf.Print.WpfImagePrintManager();
    // specify image collection which should be printed
    imagePrintManager.Images = images;

    // subscribe to the PrintingProgress event
    imagePrintManager.PrintingProgress +=
        new System.EventHandler<Vintasoft.Imaging.ProgressEventArgs>(imagePrintManager_PrintingProgress);
    // subscribe to the ImagePrinting event
    imagePrintManager.ImagePrinting +=
        new System.EventHandler<Vintasoft.Imaging.Wpf.Print.WpfImagePrintingEventArgs>(imagePrintManager_ImagePrinting);

    // start the printing process
    imagePrintManager.Print("Print task title");
}

/// <summary>
/// Image printing is started.
/// </summary>
private void imagePrintManager_ImagePrinting(object sender, Vintasoft.Imaging.Wpf.Print.WpfImagePrintingEventArgs e)
{
    Vintasoft.Imaging.Wpf.Print.WpfImagePrintManager imagePrintManager =
        (Vintasoft.Imaging.Wpf.Print.WpfImagePrintManager)sender;
    // if printing of second image is starting
    if (e.Image == imagePrintManager.Images[1])
    {
        // unsubscribe from the ImagePrinting event
        imagePrintManager.ImagePrinting +=
            new System.EventHandler<Vintasoft.Imaging.Wpf.Print.WpfImagePrintingEventArgs>(imagePrintManager_ImagePrinting);

        // suppress printing of this image
        e.Suppress = true;
    }
}

/// <summary>
/// Image printing is in progress.
/// </summary>
private void imagePrintManager_PrintingProgress(object sender, Vintasoft.Imaging.ProgressEventArgs e)
{
    // if printing is started
    if (e.Progress == 0)
        System.Console.Write("Printing: ");

    // write the printing progress
    System.Console.Write(string.Format("{0} ", e.Progress));

    // if printing is finished
    if (e.Progress == 100)
    {
        Vintasoft.Imaging.Wpf.Print.WpfImagePrintManager imagePrintManager =
            (Vintasoft.Imaging.Wpf.Print.WpfImagePrintManager)sender;
        // unsubscribe from the PrintingProgress event
        imagePrintManager.PrintingProgress -=
            new System.EventHandler<Vintasoft.Imaging.ProgressEventArgs>(imagePrintManager_PrintingProgress);
    }
}
''' <summary>
''' Starts image printing and suppress the printing of second image.
''' </summary>
''' <param name="images">The images, which must be printed.</param>
Public Sub PrintImagesAndSuppressSecondImage(images As Vintasoft.Imaging.ImageCollection)
    ' create print manager
    Dim imagePrintManager As New Vintasoft.Imaging.Wpf.Print.WpfImagePrintManager()
    ' specify image collection which should be printed
    imagePrintManager.Images = images

    ' subscribe to the PrintingProgress event
    AddHandler imagePrintManager.PrintingProgress, New System.EventHandler(Of Vintasoft.Imaging.ProgressEventArgs)(AddressOf imagePrintManager_PrintingProgress)
    ' subscribe to the ImagePrinting event
    AddHandler imagePrintManager.ImagePrinting, New System.EventHandler(Of Vintasoft.Imaging.Wpf.Print.WpfImagePrintingEventArgs)(AddressOf imagePrintManager_ImagePrinting)

    ' start the printing process
    imagePrintManager.Print("Print task title")
End Sub

''' <summary>
''' Image printing is started.
''' </summary>
Private Sub imagePrintManager_ImagePrinting(sender As Object, e As Vintasoft.Imaging.Wpf.Print.WpfImagePrintingEventArgs)
    Dim imagePrintManager As Vintasoft.Imaging.Wpf.Print.WpfImagePrintManager = DirectCast(sender, Vintasoft.Imaging.Wpf.Print.WpfImagePrintManager)
    ' if printing of second image is starting
    If e.Image Is imagePrintManager.Images(1) Then
        ' unsubscribe from the ImagePrinting event
        AddHandler imagePrintManager.ImagePrinting, New System.EventHandler(Of Vintasoft.Imaging.Wpf.Print.WpfImagePrintingEventArgs)(AddressOf imagePrintManager_ImagePrinting)

        ' suppress printing of this image
        e.Suppress = True
    End If
End Sub

''' <summary>
''' Image printing is in progress.
''' </summary>
Private Sub imagePrintManager_PrintingProgress(sender As Object, e As Vintasoft.Imaging.ProgressEventArgs)
    ' if printing is started
    If e.Progress = 0 Then
        System.Console.Write("Printing: ")
    End If

    ' write the printing progress
    System.Console.Write(String.Format("{0} ", e.Progress))

    ' if printing is finished
    If e.Progress = 100 Then
        Dim imagePrintManager As Vintasoft.Imaging.Wpf.Print.WpfImagePrintManager = DirectCast(sender, Vintasoft.Imaging.Wpf.Print.WpfImagePrintManager)
        ' unsubscribe from the PrintingProgress event
        RemoveHandler imagePrintManager.PrintingProgress, New System.EventHandler(Of Vintasoft.Imaging.ProgressEventArgs)(AddressOf imagePrintManager_PrintingProgress)
    End If
End Sub



Пример кода, показывающий, как добавить верхний и/или нижний колонтитул к печатаемому изображению или странице,можно найти в демо приложении WpfPrintDemo которое доступно в дистрибутиве SDK.


Предварительный просмотр изображений для печати

Класс WpfImagePrintManager может использовать класс WpfThumbnailViewer для предварительного просмотра коллекции изображений.

Во время предварительного просмотра класс WpfImagePrintManager позволяет:

Вот C#/VB.NET код, который демонстрирует, как настроить предварительный просмотр печати перед печатью коллекции изображений:
public void PrintPreviewImages(
    Vintasoft.Imaging.Wpf.Print.WpfImagePrintManager imagePrintManager,
    Vintasoft.Imaging.ImageCollection images,
    Vintasoft.Imaging.Wpf.UI.WpfThumbnailViewer printPreviewViewer)
{
    // specify image collection which should be printed
    imagePrintManager.Images = images;

    // specify a viewer which should be used for print preview
    imagePrintManager.Preview = printPreviewViewer;

    // specify how many pages should be shown horizontally and vertically in preview
    imagePrintManager.PreviewColumnCount = 2;
    imagePrintManager.PreviewRowCount = 2;

    // specify settings for Mozaic mode of print preview
    imagePrintManager.PrintScaleMode = Vintasoft.Imaging.Print.PrintScaleMode.Mosaic;
    imagePrintManager.MosaicColumnCount = 2;
    imagePrintManager.MosaicRowCount = 3;
    imagePrintManager.DistanceBetweenImages = new System.Windows.Size(10, 10);
}
Public Sub PrintPreviewImages(imagePrintManager As Vintasoft.Imaging.Wpf.Print.WpfImagePrintManager, images As Vintasoft.Imaging.ImageCollection, printPreviewViewer As Vintasoft.Imaging.Wpf.UI.WpfThumbnailViewer)
    ' specify image collection which should be printed
    imagePrintManager.Images = images

    ' specify a viewer which should be used for print preview
    imagePrintManager.Preview = printPreviewViewer

    ' specify how many pages should be shown horizontally and vertically in preview
    imagePrintManager.PreviewColumnCount = 2
    imagePrintManager.PreviewRowCount = 2

    ' specify settings for Mozaic mode of print preview
    imagePrintManager.PrintScaleMode = Vintasoft.Imaging.Print.PrintScaleMode.Mosaic
    imagePrintManager.MosaicColumnCount = 2
    imagePrintManager.MosaicRowCount = 3
    imagePrintManager.DistanceBetweenImages = New System.Windows.Size(10, 10)
End Sub



Хороший пример, демонстрирующий реализацию предварительного просмотра печати коллекции изображений, доступен в демо приложении WpfPrintDemo.


Печать изображений с аннотациями

Класс WpfAnnotatedImagePrintManager, производный от класса WpfImagePrintManager, должен использоваться для печати и предварительного просмотра изображений с аннотациями.
UI-контрол WpfAnnotatedImagePrintManager печатает аннотации в векторном виде, что обеспечивает более эффективное использование памяти и большую производительность, чем при растеризации аннотаций на клоне изображения перед печатью. UI-контрол WpfAnnotatedImagePrintManager будет работать как UI-контрол WpfImagePrintManager если значение свойства WpfAnnotatedImagePrintManager.PrintAnnotations установлено на false.