VintaSoft Imaging .NET SDK 15.1: Документация для .NET разработчика
В этом разделе
Обработка форм: Шаблон формы
В этом разделе
"Шаблон формы" представлен двумя объектами: экземпляром класса VintasoftImage, который определяет изображение "шаблона формы", и экземпляром класса FormPageTemplate, который определяет список "шаблонов полей формы".

Класс FormTemplateManager является менеджером шаблонов форм и используется для упрощения работы с "шаблонами форм". Класс хранит связь между экземпляром класса VintasoftImage и экземпляром класса FormPageTemplate для каждого "шаблона формы".

"Шаблон поля формы" представлен классом FormFieldTemplate, который определяет имя поля, его тип и расположение на странице. Вот список стандартных классов, определяющих "шаблоны полей формы":

Архитектура класса FormFieldTemplate открыта, поэтому при необходимости можно определять собственные пользовательские "поля формы". Приложение "Forms Processing Demo" содержит пример "шаблона поля формы", который определяет штрихкод.

FormDocumentTemplate позволяет объединить один или несколько "шаблонов форм" в "документ шаблонов форм". Это позволяет работать с несколькими "полями формы" как с одним объектом и тем самым упростить сериализацию и десериализацию "шаблонов форм".


Создавайте шаблон формы с помощью кода

Для создания шаблона формы необходимо выполнить следующие действия:
Вот код C#/VB.NET, который демонстрирует, как сканировать документ с пустой формой и создать шаблон формы.
/// <summary>
/// Scans the template document and creates page templates.
/// </summary>
/// <returns>
/// A <see cref="Vintasoft.Imaging.FormsProcessing.FormRecognition.FormTemplateManager"/> instance that contains
/// images of template document and the templates of document pages.
/// </returns>
public static Vintasoft.Imaging.FormsProcessing.FormRecognition.FormTemplateManager ScanAndCreatePageTemplates()
{
    Vintasoft.Imaging.FormsProcessing.FormRecognition.FormTemplateManager templateManager = 
        new Vintasoft.Imaging.FormsProcessing.FormRecognition.FormTemplateManager();

    System.Console.WriteLine("Create TWAIN device manager...");
    using (Vintasoft.Twain.DeviceManager deviceManager = 
        new Vintasoft.Twain.DeviceManager())
    {
        System.Console.WriteLine("Open TWAIN device manager...");
        deviceManager.Open();

        Vintasoft.Twain.Device device = deviceManager.DefaultDevice;

        Vintasoft.Twain.AcquireModalState acquireState;
        do
        {
            System.Console.WriteLine("Acquire image from scanner...");
            acquireState = device.AcquireModal();
            if (acquireState == Vintasoft.Twain.AcquireModalState.ImageAcquired)
            {
                // create VintasoftImage from acquired image
                Vintasoft.Imaging.VintasoftImage image = 
                    new Vintasoft.Imaging.VintasoftImage(device.AcquiredImage.GetAsVintasoftBitmap(), true);
                // if image is not black-white
                if (image.PixelFormat != Vintasoft.Imaging.PixelFormat.BlackWhite)
                    // convert to black-white image (1-bpp pixel format)
                    image.ConvertToBlackWhite();

                // add page to PDF document
                System.Console.WriteLine("Add page to template manager...");
                templateManager.AddPageTemplate(image, 
                    new Vintasoft.Imaging.FormsProcessing.FormRecognition.FormPageTemplate());

                // dispose the acquired image
                device.AcquiredImage.Dispose();
            }
        }
        while (acquireState != Vintasoft.Twain.AcquireModalState.None);

        System.Console.WriteLine("Scan finished.");
        return templateManager;
    }
}
''' <summary>
''' Scans the template document and creates page templates.
''' </summary>
''' <returns>
''' A <see cref="Vintasoft.Imaging.FormsProcessing.FormRecognition.FormTemplateManager"/> instance that contains
''' images of template document and the templates of document pages.
''' </returns>
Public Shared Function ScanAndCreatePageTemplates() As Vintasoft.Imaging.FormsProcessing.FormRecognition.FormTemplateManager
    Dim templateManager As New Vintasoft.Imaging.FormsProcessing.FormRecognition.FormTemplateManager()

    System.Console.WriteLine("Create TWAIN device manager...")
    Using deviceManager As New Vintasoft.Twain.DeviceManager()
        System.Console.WriteLine("Open TWAIN device manager...")
        deviceManager.Open()

        Dim device As Vintasoft.Twain.Device = deviceManager.DefaultDevice

        Dim acquireState As Vintasoft.Twain.AcquireModalState
        Do
            System.Console.WriteLine("Acquire image from scanner...")
            acquireState = device.AcquireModal()
            If acquireState = Vintasoft.Twain.AcquireModalState.ImageAcquired Then
                ' create VintasoftImage from acquired image
                Dim image As New Vintasoft.Imaging.VintasoftImage(device.AcquiredImage.GetAsVintasoftBitmap(), True)
                ' if image is not black-white
                If image.PixelFormat <> Vintasoft.Imaging.PixelFormat.BlackWhite Then
                    ' convert to black-white image (1-bpp pixel format)
                    image.ConvertToBlackWhite()
                End If

                ' add page to PDF document
                System.Console.WriteLine("Add page to template manager...")
                templateManager.AddPageTemplate(image, New Vintasoft.Imaging.FormsProcessing.FormRecognition.FormPageTemplate())

                ' dispose the acquired image
                device.AcquiredImage.Dispose()
            End If
        Loop While acquireState <> Vintasoft.Twain.AcquireModalState.None

        System.Console.WriteLine("Scan finished.")
        Return templateManager
    End Using
End Function


Определение шаблонов OMR-меток в демонстрационном приложении "VintaSoft Forms Processing Demo"

Демонстрационное приложение "VintaSoft Forms Processing Demo" позволяет автоматически определять отдельные OMR-метки или таблицу OMR-меток.

Если вы хотите автоматически определять прямоугольную/эллиптичную OMR-метку на шаблонном изображении, выполните следующие действия: Если вы хотите автоматически обнаружить таблицу с прямоугольными/эллиптическими OMR-метками на изображении шаблона, выполните следующие действия:
Также демонстрационное приложение "VintaSoft Forms Processing Demo" позволяет вручную определять отдельные OMR-метки или таблицу OMR-меток.

Если вы хотите вручную определить шаблон прямоугольной/эллиптической OMR-метки на шаблоне изображения, выполните следующие действия: Если вы хотите вручную определить таблицу с прямоугольными/эллиптическими OMR-метками на шаблоне изображения, выполните следующие действия:

Редактирование шаблона формы

Шаблон формы можно редактировать визуально или программно. Класс FormFieldTemplateEditorTool можно использовать для визуального редактирования "шаблона формы".

Чтобы добавить "шаблон поля формы" к "шаблону формы" программным способом необходимо сделать следующее:
Для редактирования "шаблона поля формы" в "шаблоне формы" программным способом необходимо сделать следующее:
Чтобы удалить "шаблон поля формы" из "формы" "шаблон" программно необходимо сделать следующее:
Вот код C#/VB.NET, который демонстрирует, как создать шаблон формы и добавить некоторые поля формы шаблоны к нему программно.
/// <summary>
/// Creates a page template and adds field templates.
/// </summary>
/// <returns>
/// A <see cref="Vintasoft.Imaging.FormsProcessing.FormRecognition.FormPageTemplate"/> instance that contains
/// created form field templates.
/// </returns>
public static Vintasoft.Imaging.FormsProcessing.FormRecognition.FormPageTemplate CreatePageTemplateAndAddFieldTemplates()
{
    // create empty page template
    Vintasoft.Imaging.FormsProcessing.FormRecognition.FormPageTemplate pageTemplate = 
        new Vintasoft.Imaging.FormsProcessing.FormRecognition.FormPageTemplate();

    // create OMR field
    Vintasoft.Imaging.FormsProcessing.FormRecognition.Omr.OmrFieldTemplate omrFieldTemplate = 
        new Vintasoft.Imaging.FormsProcessing.FormRecognition.Omr.OmrRectangularFieldTemplate();
    omrFieldTemplate.Name = "'I agree' check box";
    omrFieldTemplate.BoundingBox = new System.Drawing.RectangleF(1200, 2400, 40, 40);
    omrFieldTemplate.Threshold = 0.1f;
    omrFieldTemplate.FilledValue = "YES";
    omrFieldTemplate.UnfilledValue = "";
    omrFieldTemplate.UndefinedValue = "?";

    // add field template to page template
    pageTemplate.Items.Add(omrFieldTemplate);

    // create OCR field
    Vintasoft.Imaging.FormsProcessing.FormRecognition.Ocr.OcrFieldTemplate ocrFieldTemplate = 
        new Vintasoft.Imaging.FormsProcessing.FormRecognition.Ocr.OcrFieldTemplate();
    ocrFieldTemplate.Name = "Last name";
    ocrFieldTemplate.BoundingBox = new System.Drawing.RectangleF(300, 400, 500, 200);
    ocrFieldTemplate.OcrEngineSettings = 
        new Vintasoft.Imaging.Ocr.OcrEngineSettings(Vintasoft.Imaging.Ocr.OcrLanguage.English);

    // add field template to page template
    pageTemplate.Items.Add(ocrFieldTemplate);

    return pageTemplate;
}
''' <summary>
''' Creates a page template and adds field templates.
''' </summary>
''' <returns>
''' A <see cref="Vintasoft.Imaging.FormsProcessing.FormRecognition.FormPageTemplate"/> instance that contains
''' created form field templates.
''' </returns>
Public Shared Function CreatePageTemplateAndAddFieldTemplates() As Vintasoft.Imaging.FormsProcessing.FormRecognition.FormPageTemplate
    ' create empty page template
    Dim pageTemplate As New Vintasoft.Imaging.FormsProcessing.FormRecognition.FormPageTemplate()

    ' create OMR field
    Dim omrFieldTemplate As Vintasoft.Imaging.FormsProcessing.FormRecognition.Omr.OmrFieldTemplate = New Vintasoft.Imaging.FormsProcessing.FormRecognition.Omr.OmrRectangularFieldTemplate()
    omrFieldTemplate.Name = "'I agree' check box"
    omrFieldTemplate.BoundingBox = New System.Drawing.RectangleF(1200, 2400, 40, 40)
    omrFieldTemplate.Threshold = 0.1F
    omrFieldTemplate.FilledValue = "YES"
    omrFieldTemplate.UnfilledValue = ""
    omrFieldTemplate.UndefinedValue = "?"

    ' add field template to page template
    pageTemplate.Items.Add(omrFieldTemplate)

    ' create OCR field
    Dim ocrFieldTemplate As New Vintasoft.Imaging.FormsProcessing.FormRecognition.Ocr.OcrFieldTemplate()
    ocrFieldTemplate.Name = "Last name"
    ocrFieldTemplate.BoundingBox = New System.Drawing.RectangleF(300, 400, 500, 200)
    ocrFieldTemplate.OcrEngineSettings = New Vintasoft.Imaging.Ocr.OcrEngineSettings(Vintasoft.Imaging.Ocr.OcrLanguage.English)

    ' add field template to page template
    pageTemplate.Items.Add(ocrFieldTemplate)

    Return pageTemplate
End Function


Редактирование шаблона формы на изображении в WinForms просмотрщике изображений

Для визуального создания и редактирования "шаблона формы" необходимо сделать следующее:
Вот код C#/VB.NET, который демонстрирует, как создать шаблон формы на основе изображения в WinForms просмотрщике изображений и добавить в форму несколько шаблонов полей.
class FormFieldTemplateEditorToolForm : System.Windows.Forms.Form
{
    Vintasoft.Imaging.UI.ImageViewer imageViewer1;
    System.Windows.Forms.Button buildFieldTemplateButton;

    // ...

    /// <summary>
    /// Form template manager.
    /// </summary>
    Vintasoft.Imaging.FormsProcessing.FormRecognition.FormTemplateManager _templateManager;

    /// <summary>
    /// The template editor tool.
    /// </summary>
    Vintasoft.Imaging.FormsProcessing.FormRecognition.UI.VisualTools.FormFieldTemplateEditorTool _templateEditorTool;

    // ...

    public FormFieldTemplateEditorToolForm()
    {
        // ...

        // create the form field template editor tool
        _templateEditorTool =
            new Vintasoft.Imaging.FormsProcessing.FormRecognition.UI.VisualTools.FormFieldTemplateEditorTool();
        // add the form field template editor tool to the image viewer
        imageViewer1.VisualTool =
            new Vintasoft.Imaging.UI.VisualTools.CompositeVisualTool(_templateEditorTool, _templateEditorTool.FieldTemplateWizardTool);

        imageViewer1.FocusedIndexChanged +=
            new System.EventHandler<Vintasoft.Imaging.UI.FocusedIndexChangedEventArgs>(imageViewer1_FocusedIndexChanged);

        buildFieldTemplateButton.Click +=
            new System.EventHandler(buildFieldTemplateButton_Click);

        // ...
    }

    /// <summary>
    /// Handles the FocusedIndexChanged event of the imageViewer1
    /// to change the collection of form field templates of the visual tool.
    /// </summary>
    private void imageViewer1_FocusedIndexChanged(object sender, Vintasoft.Imaging.UI.FocusedIndexChangedEventArgs e)
    {
        // if image viewer does not have image
        if (imageViewer1.Image == null)
        {
            // clear form field template collection in the form field template editor tool
            _templateEditorTool.FieldTemplateCollection = null;
        }
        // if image viewer haS image
        else
        {
            // get the form page template for focused image
            Vintasoft.Imaging.FormsProcessing.FormRecognition.FormPageTemplate pageTemplate =
                _templateManager.GetPageTemplate(imageViewer1.Image);
            // set items of page template as current items of the visual tool
            _templateEditorTool.FieldTemplateCollection = pageTemplate.Items;
        }
    }

    // ...

    /// <summary>
    /// Handles the Click event of the buildFieldTemplateButton
    /// to create a form field template and start building of it.
    /// </summary>
    private void buildFieldTemplateButton_Click(object sender, System.EventArgs e)
    {
        // create an OMR rectangular field template
        Vintasoft.Imaging.FormsProcessing.FormRecognition.FormFieldTemplate fieldTemplate =
            new Vintasoft.Imaging.FormsProcessing.FormRecognition.Omr.OmrRectangularFieldTemplate();
        // create a view for the field template
        Vintasoft.Imaging.FormsProcessing.FormRecognition.UI.FormFieldTemplateView fieldTemplateView =
            Vintasoft.Imaging.FormsProcessing.FormRecognition.UI.FormFieldTemplateViewFactory.CreateView(fieldTemplate);

        // add field template to the collection of visual tool and
        // start building of field template
        _templateEditorTool.AddAndBuild(fieldTemplateView);
    }

    // ...

}
Class FormFieldTemplateEditorToolForm
    Inherits System.Windows.Forms.Form
    Private imageViewer1 As Vintasoft.Imaging.UI.ImageViewer
    Private buildFieldTemplateButton As System.Windows.Forms.Button

    ' ...

    ''' <summary>
    ''' Form template manager.
    ''' </summary>
    Private _templateManager As Vintasoft.Imaging.FormsProcessing.FormRecognition.FormTemplateManager

    ''' <summary>
    ''' The template editor tool.
    ''' </summary>
    Private _templateEditorTool As Vintasoft.Imaging.FormsProcessing.FormRecognition.UI.VisualTools.FormFieldTemplateEditorTool

    ' ...

    Public Sub New()
        ' ...

        ' create the form field template editor tool
        _templateEditorTool = New Vintasoft.Imaging.FormsProcessing.FormRecognition.UI.VisualTools.FormFieldTemplateEditorTool()
        ' add the form field template editor tool to the image viewer
        imageViewer1.VisualTool = New Vintasoft.Imaging.UI.VisualTools.CompositeVisualTool(_templateEditorTool, _templateEditorTool.FieldTemplateWizardTool)

        AddHandler imageViewer1.FocusedIndexChanged, New System.EventHandler(Of Vintasoft.Imaging.UI.FocusedIndexChangedEventArgs)(AddressOf imageViewer1_FocusedIndexChanged)


            ' ...
        AddHandler buildFieldTemplateButton.Click, New System.EventHandler(AddressOf buildFieldTemplateButton_Click)
    End Sub

    ''' <summary>
    ''' Handles the FocusedIndexChanged event of the imageViewer1
    ''' to change the collection of form field templates of the visual tool.
    ''' </summary>
    Private Sub imageViewer1_FocusedIndexChanged(sender As Object, e As Vintasoft.Imaging.UI.FocusedIndexChangedEventArgs)
        ' if image viewer does not have image
        If imageViewer1.Image Is Nothing Then
            ' clear form field template collection in the form field template editor tool
            _templateEditorTool.FieldTemplateCollection = Nothing
        Else
            ' if image viewer haS image
            ' get the form page template for focused image
            Dim pageTemplate As Vintasoft.Imaging.FormsProcessing.FormRecognition.FormPageTemplate = _templateManager.GetPageTemplate(imageViewer1.Image)
            ' set items of page template as current items of the visual tool
            _templateEditorTool.FieldTemplateCollection = pageTemplate.Items
        End If
    End Sub

    ' ...

    ''' <summary>
    ''' Handles the Click event of the buildFieldTemplateButton
    ''' to create a form field template and start building of it.
    ''' </summary>
    Private Sub buildFieldTemplateButton_Click(sender As Object, e As System.EventArgs)
        ' create an OMR rectangular field template
        Dim fieldTemplate As Vintasoft.Imaging.FormsProcessing.FormRecognition.FormFieldTemplate = New Vintasoft.Imaging.FormsProcessing.FormRecognition.Omr.OmrRectangularFieldTemplate()
        ' create a view for the field template
        Dim fieldTemplateView As Vintasoft.Imaging.FormsProcessing.FormRecognition.UI.FormFieldTemplateView = Vintasoft.Imaging.FormsProcessing.FormRecognition.UI.FormFieldTemplateViewFactory.CreateView(fieldTemplate)

        ' add field template to the collection of visual tool and
        ' start building of field template
        _templateEditorTool.AddAndBuild(fieldTemplateView)
    End Sub

    ' ...

End Class


Редактирование шаблона формы изображения в WPF просмотрщике изображений.

Для визуального создания и редактирования "шаблона формы" необходимо сделать следующее:

Определить шаблон поля формы

Свойство FormFieldTemplate.Name позволяет указать имя "шаблона поля формы".

Свойство FormFieldTemplate.BoundingBox позволяет указать область на изображении "шаблона формы", где расположены данные "шаблона поля формы".

По умолчанию область изображения, содержащая данные "шаблона поля формы", считается пустой, т.е. область изображения содержит только белые пиксели. В случае, если область изображения, содержащая данные "шаблона поля формы", не пуста (область изображения содержит черные и белые пиксели), необходимо вызвать метод FormFieldTemplate.CompensateTemplateImageBackground, чтобы игнорировать черные пиксели при распознавании поля формы.


Сохранение и загрузка шаблона формы

SDK позволяет сохранять "шаблон формы" в файл или поток, а также загружать "шаблон формы" из файла или потока.

Для сохранения "документа шаблона формы" необходимо использовать метод FormDocumentTemplate.Serialize, для загрузки "документа шаблона формы" необходимо использовать метод FormDocumentTemplate.Deserialize. Для сохранения "шаблона формы" необходимо использовать метод FormPageTemplate.Serialize, для загрузки "шаблона формы" необходимо использовать метод FormPageTemplate.Deserialize.
Данные формы хранятся в формате, основанном на формате XML.

Вот код C#/VB.NET, который демонстрирует, как сохранить шаблон формы в файл и загрузить шаблон формы из файла.
/// <summary>
/// Saves the page templates as a document template to the specified stream.
/// </summary>
/// <param name="pageTemplates">The page templates.</param>
/// <param name="stream">The stream to save the document to.</param>
/// <remarks>
/// Use the <see cref="Vintasoft.Imaging.FormsProcessing.FormRecognition.FormTemplateManager"/>
/// class to preserve links to template images.
/// </remarks>
public void SavePageTemplatesAsDocumentTemplate(
    Vintasoft.Imaging.FormsProcessing.FormRecognition.FormPageTemplate[] pageTemplates, 
    System.IO.Stream stream)
{
    // create new template document
    Vintasoft.Imaging.FormsProcessing.FormRecognition.FormDocumentTemplate documentTemplate = 
        new Vintasoft.Imaging.FormsProcessing.FormRecognition.FormDocumentTemplate();
    // set arbitrary name
    documentTemplate.Name = "Combined document template";
    // for each template page
    foreach (Vintasoft.Imaging.FormsProcessing.FormRecognition.FormPageTemplate pageTemplate in pageTemplates)
    {
        // add to the document
        documentTemplate.Pages.Add(pageTemplate);
    }
    // save the document to the stream
    Vintasoft.Imaging.FormsProcessing.FormRecognition.FormDocumentTemplate.Serialize(stream, documentTemplate);
}

/// <summary>
/// Opens the document template and saves every page to a separate file.
/// </summary>
/// <param name="filename">The path to the file that contains the document template.</param>
/// <returns><b>true</b> if the document template contains pages; otherwise, <b>false</b>.</returns>
public static bool OpenDocumentTemplateAndSaveEveryPage(string filename)
{
    // deserialize the document template
    Vintasoft.Imaging.FormsProcessing.FormRecognition.FormDocumentTemplate documentTemplate = 
        Vintasoft.Imaging.FormsProcessing.FormRecognition.FormDocumentTemplate.Deserialize(filename);

    if (documentTemplate.Pages.Count == 0)
        return false;
    // for each page of the document template
    for (int i = 0; i < documentTemplate.Pages.Count; i++)
    {
        // compose a filename
        string pageFilename = string.Format(
            "{0}{1}_page{2}{3}",
            System.IO.Path.GetDirectoryName(filename),
            System.IO.Path.GetFileNameWithoutExtension(filename),
            i + 1,
            System.IO.Path.GetExtension(filename));
        // save page template to a file
        Vintasoft.Imaging.FormsProcessing.FormRecognition.FormPageTemplate.Serialize(pageFilename, documentTemplate.Pages[i]);
    }

    return true;
}
''' <summary>
''' Saves the page templates as a document template to the specified stream.
''' </summary>
''' <param name="pageTemplates">The page templates.</param>
''' <param name="stream">The stream to save the document to.</param>
''' <remarks>
''' Use the <see cref="Vintasoft.Imaging.FormsProcessing.FormRecognition.FormTemplateManager"/>
''' class to preserve links to template images.
''' </remarks>
Public Sub SavePageTemplatesAsDocumentTemplate(pageTemplates As Vintasoft.Imaging.FormsProcessing.FormRecognition.FormPageTemplate(), stream As System.IO.Stream)
    ' create new template document
    Dim documentTemplate As New Vintasoft.Imaging.FormsProcessing.FormRecognition.FormDocumentTemplate()
    ' set arbitrary name
    documentTemplate.Name = "Combined document template"
    ' for each template page
    For Each pageTemplate As Vintasoft.Imaging.FormsProcessing.FormRecognition.FormPageTemplate In pageTemplates
        ' add to the document
        documentTemplate.Pages.Add(pageTemplate)
    Next
    ' save the document to the stream
    Vintasoft.Imaging.FormsProcessing.FormRecognition.FormDocumentTemplate.Serialize(stream, documentTemplate)
End Sub

''' <summary>
''' Opens the document template and saves every page to a separate file.
''' </summary>
''' <param name="filename">The path to the file that contains the document template.</param>
''' <returns><b>true</b> if the document template contains pages; otherwise, <b>false</b>.</returns>
Public Shared Function OpenDocumentTemplateAndSaveEveryPage(filename As String) As Boolean
    ' deserialize the document template
    Dim documentTemplate As Vintasoft.Imaging.FormsProcessing.FormRecognition.FormDocumentTemplate = Vintasoft.Imaging.FormsProcessing.FormRecognition.FormDocumentTemplate.Deserialize(filename)

    If documentTemplate.Pages.Count = 0 Then
        Return False
    End If
    ' for each page of the document template
    For i As Integer = 0 To documentTemplate.Pages.Count - 1
        ' compose a filename
        Dim pageFilename As String = String.Format("{0}{1}_page{2}{3}", System.IO.Path.GetDirectoryName(filename), System.IO.Path.GetFileNameWithoutExtension(filename), i + 1, System.IO.Path.GetExtension(filename))
        ' save page template to a file
        Vintasoft.Imaging.FormsProcessing.FormRecognition.FormPageTemplate.Serialize(pageFilename, documentTemplate.Pages(i))
    Next

    Return True
End Function