> ## Documentation Index
> Fetch the complete documentation index at: https://docs.abbyy.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Sample scripts describing export

> Example export scripts for ABBYY FlexiCapture: read field values during export, save page images, export tables, and write export result handlers.

The following samples show common export tasks in ABBYY FlexiCapture, such as reading field values, saving page images, exporting tables, and handling export results. Most samples are provided in both VBScript and JScript, and some include an external component written in Visual Basic or C#.

## Get field values during export

This sample gets the value of a field during export. You can use this value to name the files that images or data are exported into. If the document does not contain the field, an error occurs.

The structure of the document to be exported:

```text theme={null}
Section 1
    Field1
    …
    Group1
        Field2
        …
    …
    FieldN
Section 2
    Field1
    …
    FieldK
```

The following VBScript sample gets the field values:

```vb theme={null}
Dim field1Value, field2Value

' Gets the value of Field1 in Section 1
if Not IsNull( me.Field( "Section 1\Field1" ).Value ) then
    field1Value = me.Field( "Section 1\Field1" ).Value
end if

' Gets the value of Field2 in Group1 in Section 1
if Not IsNull( me.FIELD( "Section 1\Group1\Field2" ).Value ) then
    field2Value = me.Field( "Section 1\Group1\Field2" ).Value
end if

' Gets the value of Field1 in Section 1 if the section has multiple instances
if Not me.Field( "Section 1" ).Items Is Nothing then
    dim curPage
    for each curPage in me.Field( "Section 1" ).Items
        if Not curPage.Children Is Nothing then
            dim curField
            for each curField in curPage.Children
                if curField.Name = "Field1" And Not IsNull( curField.Value )  then
                    field1Value = curField.Value
                    exit for
                end if
            next
        end if
    next
end if
```

The following JScript sample does the same:

```javascript theme={null}
// Gets the value of Field1 in Section 1
if( Field("Section 1\\Field1").Value != null ) {
    var field1Value = Field("Section 1\\Field1").Value;
}

// Gets the value of Field2 in Group1 in Section 1
if( Field("Section 1\\Group1\\Field2").Value != null ) {
    var field2Value = Field("Section 1\\Group1\\Field2").Value;
}

// Gets the value of Field1 in Section 1 if the section has multiple instances
if( Field( "Section 1" ).Items != null ) {
    var i, j;
    for( i = 0; i < Field( "Section 1" ).Items.Count; i++ ) {
        var curPage = Field( "Section 1" ).Items.Item( i );
        if( curPage.Children != null ) {
            for( j = 0; j < curPage.Children.Count; j++ ) {
                var curField = curPage.Children.Item( j );
                if( curField.Name == "Field1" && curField.Value != null ) {
                    var field1Value  = curField.Value;
                    break;
                }
            }
        }
    }
}
```

## Export page images

This example exports images of all document pages using a chosen file format, color scheme, and resolution. Each page is saved to a separate file.

The files in this example are named `page1.tif`, `page2.tif`, and so on. You can change the file-naming mechanism — for example, base file names on the value of a field.

The following VBScript sample exports the page images:

```vb theme={null}
dim fso, folderName
set fso = CreateObject("Scripting.FileSystemObject")
folderName = "d:\ExportImages"

if Not fso.FolderExists( folderName ) then
    fso.CreateFolder folderName
end if

dim imageOptions
set imageOptions = FCTools.NewImageSavingOptions
imageOptions.Format = "tif"
imageOptions.ColorType = "BlackAndWhite"
imageOptions.Resolution = 600
dim i

for i = 0 to me.Pages.Count - 1
    dim fileName
    ' Sets the desired name and extension for the file depending on the selected format
    fileName = fso.BuildPath( folderName, "page" & (i+1) & ".tif" )
    me.Pages.Item(i).SaveAs fileName, imageOptions
next
```

The following JScript sample does the same:

```javascript theme={null}
var fso = new ActiveXObject("Scripting.FileSystemObject");
var folderName = "d:\\ExportImages";

if( !fso.FolderExists( folderName ) ) {
    fso.CreateFolder( folderName );
}

var imageOptions = FCTools.NewImageSavingOptions();
imageOptions.Format = "tif";
imageOptions.ColorType = "BlackAndWhite";
imageOptions.Resolution = 600;
var i;

for( i = 0; i < Pages.Count; i++ ) {
    // Sets the desired name and extension for the file depending on the selected format
    var fileName = fso.BuildPath( folderName, "page" + (i+1) + ".tif" );
    Pages.Item(i).SaveAs( fileName, imageOptions );
}
```

## Export a table

This example exports a table to a `*.txt` file.

The following VBScript sample exports the table:

```vb theme={null}
dim fso, txtFile, fileName
set fso = CreateObject("Scripting.FileSystemObject")
fileName = "d:\TestExportTable.txt"

set txtFile = fso.CreateTextFile( fileName, true )
txtFile.WriteLine "Table"
dim table, row, cell, rowNumber

set table = me.Field("Page 1\Table")
rowNumber = 1

for each row in table.Items
    txtFile.WriteLine "RowNumber = " & rowNumber
    for each cell in row.Children
        txtFile.Write cell.Value & "   "
    next
    txtFile.WriteBlankLines 1
    rowNumber = rowNumber + 1
next

txtFile.Close
set txtFile = nothing
set fso = nothing
```

The following JScript sample does the same:

```javascript theme={null}
var fso, txtFile, fileName;
fso = new ActiveXObject("Scripting.FileSystemObject");
fileName = "d:\\TestExportTable1.txt";

txtFile = fso.CreateTextFile( fileName, true );
txtFile.WriteLine( "Table" );

var table, i, j;
table = Field("Page 1\\Table");
var rows = table.Items;

for( i = 0; i < rows.Count; i++ ) {
    txtFile.WriteLine( "RowNumber = " + ( i+1 ) );
    var cells = rows.Item(i).Children;
    for( j = 0; j < cells.Count; j++ ) {
        txtFile.Write( cells.Item(j).Value + "   " );
    }
    txtFile.WriteBlankLines(1);
}
txtFile.Close();
```

## Export a document of any nesting level

This example exports fields of a document of any nesting level using custom functions from the global export module. To export document fields of variable nesting, use an external COM component, as shown in the following example.

### Core export code

Add this call to the document export script.

The following VBScript calls the export function:

```vb theme={null}
Export.ExportDocument me, FCTools
```

The equivalent JScript call:

```javascript theme={null}
Export.ExportDocument( this, FCTools );
```

### Global export module functions

The global export module defines the following functions.

The VBScript implementation:

```vb theme={null}
' The procedure carries out the export: creates an export folder and
' saves in it page image files, the text file with the document fields,
' and information about the document
Sub ExportDocument(ByRef docObj, ByRef FCTools)
    Dim folderName
    Dim txtFile, fileName
    Dim fso

    On Error Resume Next
    set fso = CreateObject("Scripting.FileSystemObject")
    ' creating the export folder
    folderName = CreateExportFolder(docObj.DefinitionName, fso)

    if Err.Number <> 0 then
        docObj.Action.Succeeded = false
        docObj.Action.ErrorMessage = "Error during create export folder: " + Err.Description
        Err.Clear
        Exit Subub
    End if

    ' exporting images
    ExportImages docObj, FCTools, folderName, fso
    if Err.Number <> 0 then
        docObj.Action.Succeeded = false
        docObj.Action.ErrorMessage = "Error during export images: " + Err.Description
        Err.Clear
        Exit Sub
    End if

    ' creating the text file
    fileName = fso.BuildPath(folderName, "doc.txt")
    Set txtFile = fso.CreateTextFile(fileName, True)

    ' exporting info about the document
    ExportDocInfo docObj, txtFile

    ' exporting fields
    txtFile.WriteLine "Fields:"
    ExportFields docObj.Children, txtFile, ""
    txtFile.Close

    if Err.Number <> 0 then
        docObj.Action.Succeeded = false
        docObj.Action.ErrorMessage = "Error during export data: " + Err.Description
        Err.Clear
        Exit Sub
    End if

    Set txtFile = Nothing
    Set fso = Nothing
End Sub

' Image export function
Function ExportImages( ByRef docObj, ByRef FCTools, ByVal exportFolder, ByRef fso )
    Dim pages, page, imageOptions
    Dim fileName, pageNum

    ' specifying export settings
    Set imageOptions = FCTools.NewImageSavingOptions
    imageOptions.Format = "bmp"
    imageOptions.ColorType = "FullColor"
    imageOptions.Resolution = 100

    ' page-by-page export
    Set pages = docObj.Pages
    pageNum = 1

    For Each page In pageses
        fileName = fso.BuildPath(exportFolder, "page" & pageNum & ".bmp")
        page.SaveAs fileName, imageOptions
        pageNum = pageNum + 1
    Next
End Function

' The procedure that exports info about the document
Sub ExportDocInfo(ByRef docObj, ByRef txtFile)
    txtFile.WriteLine "Doc info:"
    txtFile.WriteLine ("DocumentId " & docObj.Id)
    txtFile.WriteLine ("IsAssembled " & docObj.IsAssembled)
    txtFile.WriteLine ("IsVerified " & docObj.IsVerified)
    txtFile.WriteLine ("IsExported " & docObj.IsExported)
    txtFile.WriteLine ("ProcessingErrors " & docObj.ProcessingErrors)
    txtFile.WriteLine ("ProcessingWarnings " & docObj.ProcessingWarnings)
    txtFile.WriteLine ("TotalSymbolsCount " & docObj.TotalSymbolsCount)
    txtFile.WriteLine ("RecognizedSymbolsCount " & docObj.RecognizedSymbolsCount)
    txtFile.WriteLine ("UncertainSymbolsCount " & docObj.UncertainSymbolsCount)
    txtFile.WriteLine
End Sub

' The procedure that exports fields from the fields collection
Sub ExportFields(ByRef fields, ByRef txtFile, ByVal indent)
    Dim curField
    For Each curField In fields
        ExportField curField, txtFile, indent
    Next
End Sub

' Checks if the value of the fields is null
' If the field value is invalid, any attempt to access this field (even
' to check if it is null) may cause an exception
Function IsNullFieldValue( ByRef field )
    on error resume next
    IsNullFieldValue = IsNull( field.Value )
    if Err.Number <> 0 then
        IsNullFieldValue = True
        Err.Clear
    End if
End Function

' Field export procedure
Sub ExportField(ByRef field, ByRef txtFile, ByVal indent)
    ' saving field name
    txtFile.Write (indent & field.Name)

    ' saving field value if it can be accessed
    If IsNullFieldValue(field) Then
        txtFile.WriteLine
    Else
        txtFile.WriteLine ("    " & field.Text)
    End If

    If Not field.Children Is Nothing Then
        ' exporting child fields
        ExportFields field.Children, txtFile, indent & "    "
    ElseIf Not field.Items Is Nothing Then
        ' exporting field instances
        ExportFields field.Items, txtFile, indent & "    "
    End If
End Sub

' The function creates an export folder and returns a full path to this folder
Function CreateExportFolder(ByVal definitionName, ByRef fso)
    Dim docFolder, folderName

    ' main folder
    exportFolder = "d:\ScriptExport"

    If fso.FolderExists(exportFolder) = False Then
        fso.CreateFolder (exportFolder)
    End If

    ' the folder of specified Document Definition
    docFolder = fso.BuildPath(exportFolder, definitionName)

    If fso.FolderExists(docFolder) = False Then
        fso.CreateFolder (docFolder)
    End If

    ' the folder of the exported document
    Dim i
    i = 1
    folderName = fso.BuildPath(docFolder, i)

    While fso.FolderExists(folderName)
        i = i + 1
        folderName = fso.BuildPath(docFolder, i)
    Wend

    fso.CreateFolder (folderName)
    CreateExportFolder = folderName
End Function
```

The JScript implementation:

```javascript theme={null}
// The function carries out the export: creates an export folder and
// saves in it page image files, the text file with the document fields,
// and information about the document
function ExportDocument(docObj, exportImageTools)
{
    var folderName
    var txtFile, fileName
    var fso

    fso = new ActiveXObject("Scripting.FileSystemObject");
    // creating export folders
    try {
        folderName = CreateExportFolder(docObj.DefinitionName, fso);
    } catch( e ) {
        docObj.Action.Succeeded = false;
        docObj.Action.ErrorMessage = "Error during create export folder: " + e.description;
        return;n;
    }

    // exporting images
    try {
        ExportImages(docObj, exportImageTools, folderName, fso);
    } catch( e ) {
        docObj.Action.Succeeded = false;
        docObj.Action.ErrorMessage = "Error during export images: " + e.description;
        return;
    }

    // creating the text file
    fileName = fso.BuildPath(folderName, "doc.txt");
    txtFile = fso.CreateTextFile(fileName, true);

    // exporting info about the document
    ExportDocInfo( docObj, txtFile );

    // exporting fields
    txtFile.WriteLine( "Fields:" );
    try {
        ExportFields( docObj.Children, txtFile, "" );
    } catch( e ) { {
        docObj.Action.Succeeded = false;
        docObj.Action.ErrorMessage = "Error during export data: " + e.description;
        txtFile.Close();
        return;
    }

    txtFile.Close();
    txtFile = 0;
    fso = 0;
}

// Image export function. If an error occurs when exporting images,
// it returns a message about the error; otherwise, it returns an empty string
function ExportImages( docObj, exportImageTools, exportFolder, fso )
{
    // specifying export settings
    var imageOptions = exportImageTools.NewImageSavingOptions();
    imageOptions.Format = "bmp";
    imageOptions.ColorType = "FullColor";
    imageOptions.Resolution = 100;

    // page-by-page export
    var pages = docObj.Pages;
    var i
    for( i = 0; i < pages.Count; i++ ) {
        var fileName = fso.BuildPath( exportFolder, "page" + (i+1) + ".bmp" );
        pages.Item(i).SaveAs( fileName, imageOptions );
    }
}

// The procedure that exports info about the document
function ExportDocInfo(docObj, txtFile)
{
    txtFile.WriteLine( "Doc info:" );
    txtFile.WriteLine("IsAssembled " + docObj.IsAssembled);
    txtFile.WriteLine("IsVerified " + docObj.IsVerified);
    txtFile.WriteLine("IsExported " + docObj.IsExported);
    txtFile.WriteLine("ProcessingErrors " + docObj.ProcessingErrors);
    txtFile.WriteLine("ProcessingWarnings " + docObj.ProcessingWarnings);
    txtFile.WriteLine("TotalSymbolsCount " + docObj.TotalSymbolsCount);
    txtFile.WriteLine("RecognizedSymbolsCount " + docObj.RecognizedSymbolsCount);
    txtFile.WriteLine("UncertainSymbolsCount " + docObj.UncertainSymbolsCount);
    txtFile.WriteLine();
}

// The procedure that exports fields from the fields collection
function ExportFields(fields, txtFile, indent)
{
    var i
    for( i = 0; i < fields.Count; i++ ) {
        ExportField( fields.Item(i), txtFile, indent );
    }
}

// Checks if the field value is null
// If the field value is invalid, any attempt to access this field (even
// to check if it is null) may cause an exception
function IsNullFieldValue( field )
{
    try {
        return ( field.Value == null );
    } catch( e ) {
        return true;
    }
}

// Field export procedure
function ExportField(field, txtFile, indent)
{
    // saving file name
    txtFile.Write(indent + field.Name);

    // saving field value, if it can be accessed
    if( IsNullFieldValue( field ) ) {
        txtFile.WriteLine();
    } else {
        txtFile.WriteLine("    " + field.Text);
    } }

    if( field.Children != null ) {
        // exporting child fields
        ExportFields( field.Children, txtFile, indent + "    " );
    } else if( field.Items != null ) {
        // exporting field instances
        ExportFields( field.Items, txtFile, indent + "    " );
    }
}

// The function creates an export folder and returns a full path to this folder
function CreateExportFolder(definitionName, fso)
{
    var docFolder, folderName

    // main folder
    var exportFolder = "d:\\ScriptExport";

    if( !fso.FolderExists(exportFolder) ) {
        fso.CreateFolder (exportFolder);
    } }

    // the folder of the specified Document Definition
    docFolder = fso.BuildPath(exportFolder, definitionName);

    if( !fso.FolderExists(docFolder) ) {
        fso.CreateFolder(docFolder);
    }

    // the folder of the exported document
    var i = 1;
    folderName = fso.BuildPath(docFolder, i);

    while( fso.FolderExists(folderName) ) {
        i++;
        folderName = fso.BuildPath(docFolder, i);
    }

    fso.CreateFolder(folderName);
    return folderName;
}
```

## Use an external COM component

Call an external COM component from the export script. This approach is useful for exporting document fields of variable nesting.

The following VBScript calls the component:

```vb theme={null}
dim autoExport
set autoExport = CreateObject( "AutomationExport.Exporter" )
autoExport.Export me, FCTools
```

The equivalent JScript call:

```javascript theme={null}
var autoExport = new ActiveXObject("AutomationExport.Exporter");
autoExport.Export( this, FCTools );
```

### Exporter class code in Visual Basic

This is the `Exporter` class code from the `AutomationExport` project used in the preceding scripts.

```vb theme={null}
Option Explicit

Dim mFso As New Scripting.FileSystemObject

' The procedure carries out document export: created an export folder and
' saves in it page image files, the text file with document fields,
' and information about the document
Public Sub Export(ByRef docObj As Object, ByRef FCTools As Object)
    On Error GoTo err_h
    Dim folderName As String
    Dim txtFile As TextStream, fileName As String
    Dim imageExportResult As String, errMessage As String

    ' creating export folder
    folderName = createExportFolder(docObj.definitionName)
    If folderName = "" Then
        docObj.Action.Succeeded = False
        docObj.Action.ErrorMessage = "Cannot create export folder"
        Exit Sub
    End If

    ' exporting images
    imageExportResult = exportImages(docObj, FCTools, folderName)

    ' creating the text file
    fileName = mFso.BuildPath(folderName, "doc.txt")
    Set txtFile = mFso.CreateTextFile(fileName, True)

    ' saving info about image export problems
    If imageExportResult <> "" Then
        txtFile.WriteLine imageExportResult
        errMessage = errMessage & imageExportResult
    End If

    ' exporting info about document
    exportDocInfo docObj, txtFile

    ' exporting fields
    txtFile.WriteLine "Fields:"
    If Not exportFields(docObj.Children, txtFile, "") Then
        errMessage = errMessage & " Error during export data"
    End If
    txtFile.Close

    ' if errors occur during export, reset the
    ' export success flag to False
    If errMessage <> "" Then
        docObj.Action.Succeeded = False
        docObj.Action.ErrorMessage = errMessage
    End If

    Set txtFile = Nothing
    Set mFso = Nothing
    Exit Sub

err_h:
    docObj.Action.Succeeded = False
    docObj.Action.ErrorMessage = Err.Description
    txtFile.Close
    Set mFso = Nothing
End Sub

' Image export function. If an error occurs when exporting images,
' it returns a message about the error, otherwise it returns an empty string
Private Function exportImages(ByRef docObj As Object, ByRef FCTools As Object, _
    ByVal exportFolder As String) As String
    On Error GoTo err_h
    Dim pages As Object, page As Object, imageOptions As Object
    Dim fileName As String, pageNum As Long
    exportImages = ""

    ' specifying export settings
    Set imageOptions = FCTools.NewImageSavingOptions
    imageOptions.Format = "png"
    imageOptions.ColorType = "GrayScale"
    imageOptions.Resolution = 300

    ' page-by-page export
    Set pages = docObj.pages
    pageNum = 1
    For Each page In pages
        fileName = mFso.BuildPath(exportFolder, page.definitionName + "_page" & pageNum & "." & imageOptions.Format)
        page.SaveAs fileName, imageOptions
        pageNum = pageNum + 1
    Next page
    Exit Function

err_h:
    exportImages = Err.Description
End Function

' The procedure that exports info about the document
Private Sub exportDocInfo(ByRef docObj As Object, ByRef txtFile As TextStream)
    On Error GoTo err_h
    txtFile.WriteLine "Doc info:"
    txtFile.WriteLine ("DocumentId " & docObj.Id)
    txtFile.WriteLine ("IsAssembled " & docObj.IsAssembled)
    txtFile.WriteLine ("IsVerified " & docObj.IsVerified)
    txtFile.WriteLine ("IsExported " & docObj.IsExported)
    txtFile.WriteLine ("ProcessingErrors " & docObj.ProcessingErrors)
    txtFile.WriteLine ("ProcessingWarnings " & docObj.ProcessingWarnings)
    txtFile.WriteLine ("TotalSymbolsCount " & docObj.TotalSymbolsCount)
    txtFile.WriteLine ("RecognizedSymbolsCount " & docObj.RecognizedSymbolsCount)
    txtFile.WriteLine ("UncertainSymbolsCount " & docObj.UncertainSymbolsCount)
    txtFile.WriteLine
    Exit Sub

err_h:
    txtFile.WriteLine Err.Description
End Sub

' The procedure that exports fields from the fields collection
Private Function exportFields(ByRef fields As Object, ByRef txtFile As TextStream, ByVal indent As String) As Boolean
    On Error GoTo err_h
    Dim curField As Object
    exportFields = True
    For Each curField In fields
        If Not exportField(curField, txtFile, indent) Then
            exportFields = False
        End If
    Next curField
    Exit Function

err_h:
    txtFile.WriteLine Err.Description
    exportFields = False
End Function

' Checks if the field value is null
' If the value is invalid, any attempt to access this field (even
' to check if it is null) may cause an exception
Function IsNullFieldValue(ByRef field As Object) As Boolean
    On Error GoTo err_h
    IsNullFieldValue = IsNull(field.Value)
    Exit Function

err_h:
    IsNullFieldValue = True
End Function

' Field export function
Private Function exportField(ByRef field As Object, ByRef txtFile As TextStream, _
    ByVal indent As String) As Boolean
    On Error GoTo err_h
    Dim result As Boolean
    result = True

    ' saving field name
    txtFile.Write (indent & field.Name)

    ' saving field value if it can be accessed
    If Not IsNullFieldValue(field) Then
        txtFile.WriteLine ("    " & field.Value)
    Else
        txtFile.WriteLine
    End If

    If Not field.Children Is Nothing Then
        ' exporting child fields
        result = result And exportFields(field.Children, txtFile, indent & "    ")
    ElseIf Not field.Items Is Nothing Then
        ' exporting field instances
        result = result And exportFields(field.Items, txtFile, indent & "    ")
    End If

    exportField = result
    Exit Function

err_h:
    txtFile.WriteLine Err.Description
    exportField = False
End Function

' The function creates an export folder and returns a full path to this folder
Private Function createExportFolder(ByVal definitionName As String) As String
    On Error GoTo err_h
    Dim docFolder As String, folderName As String

    ' main folder
    Const exportFolder = "d:\AutomationExport"
    If mFso.FolderExists(exportFolder) = False Then
        mFso.CreateFolder (exportFolder)
    End If

    ' the folder of the specified Document Definition
    docFolder = mFso.BuildPath(exportFolder, definitionName)
    If mFso.FolderExists(docFolder) = False Then
        mFso.CreateFolder (docFolder)
    End If

    ' the folder of the exported document
    Dim i As Long
    i = 1
    folderName = mFso.BuildPath(docFolder, i)
    While mFso.FolderExists(folderName)
        i = i + 1
        folderName = mFso.BuildPath(docFolder, i)
    Wend
    mFso.CreateFolder (folderName)
    createExportFolder = folderName
    Exit Function

err_h:
    createExportFolder = ""
End Function
```

### Use a .NET component written in C\#

<Steps>
  <Step title="Create a ClassLibrary project">
    Create a project of type `ClassLibrary`.
  </Step>

  <Step title="Add the ControllerInterop.dll reference">
    Add `ControllerInterop.dll` to the project **References**. `ABBYY.FlexiCapture` appears in the References list, and all the interfaces of the script objects become available in the project.
  </Step>

  <Step title="Define the dispinterface, class, and ProgId">
    Define the dispinterface and the class that implements this interface, as well as the `ProgId`. This makes it possible to work with the .NET component from script code just like with ActiveX.
  </Step>

  <Step title="Register the generated type library">
    After building the project, register the generated type library. To do this automatically, enable the corresponding option in the project properties.
  </Step>

  <Step title="Call the component from the export code">
    From the export code, call the component method in the usual way, as shown in the following example.
  </Step>
</Steps>

The following VBScript calls the component:

```vb theme={null}
dim autoExport
set autoExport = CreateObject( "ExportLibrary1.Export" )
autoExport.ExportDocument me, FCTools
```

The equivalent JScript call:

```javascript theme={null}
var autoExport = new ActiveXObject("ExportLibrary1.Export"); autoExport.ExportDocument( this, FCTools );
```

The following C# code implements such a component:

```csharp theme={null}
using System;
using System.Runtime.InteropServices;
using System.IO;
using ABBYY.FlexiCapture;

namespace ExportLibrary1
{
    // The interface of the export component which can be accessed from the script
    // When creating a new component, generate a new GUID
    [Guid("32B10C3B-EEA3-4194-B0A0-E358C310225A")]
    [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    public interface _cExport
    {
        [DispId(1)]
        void ExportDocument(ref IExportDocument DocRef, ref FCTools Tools);
    }

    // The class that implements export component functionality
    // When creating a new component, generate a new GUID
    // and set your ProgId
    [Guid("3BA19BD7-C6DC-4f63-BC08-0D95254DADC3")]
    [ClassInterface(ClassInterfaceType.None)]
    [ProgId("ExportLibrary1.Export")]
    [ComVisible(true)]
    public class Export : _cExport
    {
        public Export()
        {
        }

        // The function carries out document export: creates an export folder and
        // saves in it page image files,
        // the text file with document fields, and information about the document
        public void ExportDocument( ref IExportDocument docRef, ref FCTools FCTools )
        {
            try
            {
                string exportFolder = createExportFolder( docRef.DefinitionName );
                exportImages( docRef, FCTools, exportFolder );

                // creating the text file
                string fileName = exportFolder + "//" + "doc.txt";
                StreamWriter sw = File.CreateText( fileName );

                // exporting info about document
                exportDocInfo( docRef, sw );

                // exporting fields
                sw.WriteLine( "Fields:" );
                exportFields( docRef.Children, sw, "" );
                sw.Close();
            }
            catch( Exception e )
            {
                docRef.Action.Succeeded = false;
                docRef.Action.ErrorMessage = e.ToString();
            }
        }

        // The function creates an export folder and returns a full path to this folder
        private string createExportFolder(string definitionName )
        {
            string docFolder, folderName;

            // main folder
            string exportFolder = "d:\\DotNetExport";
            if( !Directory.Exists(exportFolder) )
            {
                Directory.CreateDirectory(exportFolder);
            }

            // the folder of the specified Document Definition
            docFolder = exportFolder + "\\" + definitionName;
            if( !Directory.Exists(docFolder) )
            {
                Directory.CreateDirectory( docFolder );
            }

            // the folder of the exported document
            int i = 1;
            folderName = docFolder + "\\" + i;
            while( Directory.Exists(folderName) )
            {
                i++;
                folderName = docFolder + "\\" + i;
            }
            Directory.CreateDirectory(folderName);
            return folderName;
        }

        // Image export function
        private void exportImages( IExportDocument docRef, FCTools FCTools, string exportFolder )
        {
            string baseFileName = exportFolder + "\\page_";
            IExportImageSavingOptions imageOptions = FCTools.NewImageSavingOptions();
            imageOptions.Format = "bmp";
            imageOptions.ColorType = "FullColor";
            imageOptions.Resolution = 100;
            int i = 1;
            foreach( IExportPage curPage in docRef.Pages )
            {
                string fileName = baseFileName + i + ".bmp";
                curPage.SaveAs( fileName, imageOptions );
                i++;
            }
        }

        // Exporting info about document
        private void exportDocInfo( IExportDocument docRef, StreamWriter sw )
        {
            sw.WriteLine( "Doc info:" );
            sw.WriteLine("DocumentId " + docRef.Id );
            sw.WriteLine("IsAssembled " + docRef.IsAssembled);
            sw.WriteLine("IsVerified " + docRef.IsVerified);
            sw.WriteLine("IsExported " + docRef.IsExported);
            sw.WriteLine("ProcessingErrors " + docRef.ProcessingErrors);
            sw.WriteLine("ProcessingWarnings " + docRef.ProcessingWarnings);
            sw.WriteLine("TotalSymbolsCount " + docRef.TotalSymbolsCount);
            sw.WriteLine("RecognizedSymbolsCount " + docRef.RecognizedSymbolsCount);
            sw.WriteLine();
        }

        // Exporting field collection
        private void exportFields( IExportFields fields, StreamWriter sw, string indent )
        {
            foreach( IExportField curField in fields )
            {
                exportField( curField, sw, indent );
            }
        }

        // Checks if the field value is null
        // If the field value is invalid, any attempt to access this field (even
        // to check if it is null) may cause an exception
        private bool IsNullFieldValue( IExportField field )
        {
            try
            {
                return ( field.Value == null );
            }
            catch( Exception e )
            {
                return true;
            }
        }

        // Exporting the specified field
        private void exportField( IExportField field, StreamWriter sw, string indent )
        {
            // saving the field name
            sw.Write( indent + field.Name );

            // saving the field value if it can be accessed
            if( IsNullFieldValue( field ) )
            {
                sw.WriteLine();
            }
            else
            {
                sw.WriteLine( "    " + field.Text );
            }

            if( field.Children != null )
            {
                // exporting child fields
                exportFields( field.Children, sw, indent + "    " );
            }
            else if( field.Items != null )
            {
                // exporting field instances
                exportFields( field.Items, sw, indent + "    " );
            }
        }
    }
}
```

## Write an export handler

This sample demonstrates a simple export handler that saves information about exported documents and export results to text files. It uses two text files: one for the list of successfully exported documents and one for the list of documents that returned errors during export.

The following VBScript sample handles the export results:

```vb theme={null}
dim curDoc
dim fso, fileErrorName, txtErrorFile, fileSucceedName, txtSucceedFile
set fso = CreateObject("Scripting.FileSystemObject")

' creating the file with failed documents
fileErrorName = "d:\ExportResults\ErrorsDocuments.txt"
set txtErrorFile = fso.CreateTextFile( fileErrorName, true )

' creating the file with successfully exported documents
fileSucceedName = "d:\ExportResults\SucceedDocuments.txt"
set txtSucceedFile = fso.CreateTextFile( fileSucceedName, true )
dim i, exprortResult, docInfo

' iterating the collection of exported documents
for i = 0 To me.Count - 1
    set exportResult = me.Item(i)
    docInfo = "DocumentId:" & exportResult.Document.Id
    if exportResult.Succeeded then
        docInfo = docInfo & " - Exported successfully."
        txtSucceedFile.WriteLine docInfo
    else
        docInfo = docInfo & " - Export error: " & exportResult.ErrorMessage
        txtErrorFile.WriteLine docInfo
    endif
next

txtErrorFile.Close
txtSucceedFile.Close
```

The equivalent JScript sample:

```javascript theme={null}
var fso = new ActiveXObject("Scripting.FileSystemObject");

// creating the file with failed documents
var fileErrorName = "d:\\ExportResults\\ErrorsDocuments.txt";
var txtErrorFile = fso.CreateTextFile( fileErrorName, true );

// creating the file with successfully exported documents
var fileSucceedName = "d:\\ExportResults\\SucceedDocuments.txt"
var txtSucceedFile = fso.CreateTextFile( fileSucceedName, true );
var i

// iterating the collection of exported documents
for( i = 0; i < Documents.Count; i++ ) {
    var curDoc = Documents.Item( i );
    var docInfo = "DocumentId: " + curDoc.Id;
    if( curDoc.Action.Succeeded ) {
        docInfo = docInfo + ". Exported successfully.  Result:" + curDoc.Action.Result;
        txtSucceedFile.WriteLine( docInfo );
    } else {
        docInfo = docInfo + ". Export error: " + curDoc.Action.ErrorMessage + "  Result:" + curDoc.Action.Result;
        txtErrorFile.WriteLine( docInfo );
    }
}
txtErrorFile.Close();
txtSucceedFile.Close();
```

## Access source files in common office formats

This sample script saves the source files when exporting documents. The source files must be in one of the [supported common office formats](/flexi-capture/appendix/input-formats) and must have unique names to avoid naming conflicts.

```csharp theme={null}
using System;
using System.IO;
using System.Collections.Generic;

// Iterate through the pages.
for( int i = 0; i<Document.Pages.Count; i++ ) {
    IPage page = Document.Pages[i];

    // Check whether there is a source file.
    if( page.SourceFileGUID == "" ) {
        continue;
    }

    // The original name of the file.
    string sourceFileName = @"";

    // Specify the original file name.
    if( page.ImageSourceType == @"File" ) {
        sourceFileName = Path.GetFileName( page.ImageSource );
    } else if( page.ImageSourceType == @"Scanner" || page.ImageSourceType == @"Custom" ) {
        sourceFileName = Path.GetFileName( page.ImageSourceFileSubPath );
    }

    // Remove the file extension from the file name.
    if( sourceFileName != @"" ) {
        sourceFileName = Path.GetFileNameWithoutExtension( sourceFileName ) + @".";
    }

    // Unique source file name (original name + guid).
    string sourceFileUniqueName = sourceFileName + page.SourceFileGUID;

    // The path to the folder where the source file must be saved.
    string sourceFilePath = Document.Batch.Project.ExportRootPath + @"\" + sourceFileUniqueName;

    // Make sure that the file does not exist.
    if( File.Exists( sourceFilePath ) ) {
        continue;
    }

    // Save the file.
    Processing.ReportMessage( "Saving source file: " + sourceFileUniqueName );
    page.SaveSourceFile( sourceFilePath );
}
```
