Click or drag to resize

DocumentConverter Class

Provides methods for document conversion.
Inheritance Hierarchy
SystemObject
  GleamTech.DocumentUltimateDocumentConverter

Namespace:  GleamTech.DocumentUltimate
Assembly:  GleamTech.DocumentUltimate (in GleamTech.DocumentUltimate.dll) Version: 6.5.0
Syntax
public class DocumentConverter

The DocumentConverter type exposes the following members.

Constructors
  NameDescription
Public methodCode exampleDocumentConverter(FileProvider, DocumentFormat, DocumentUltimateConfiguration)
Initializes a new instance of the DocumentConverter class from a document file provider.
Public methodCode exampleDocumentConverter(FileProvider, InputOptions, DocumentUltimateConfiguration)
Initializes a new instance of the DocumentConverter class from a document file provider.
Public methodDocumentConverter(Stream, DocumentFormat, DocumentUltimateConfiguration)
Initializes a new instance of the DocumentConverter class from a document stream.
Public methodDocumentConverter(Stream, InputOptions, DocumentUltimateConfiguration)
Initializes a new instance of the DocumentConverter class from a document stream.
Top
Methods
  NameDescription
Public methodStatic memberCode exampleCanConvert(DocumentFormat, DocumentFormat, NullableDocumentEngine)
Gets a value that indicates whether a direct conversion is possible from one document format to another format.
Public methodStatic memberCode exampleCanConvert(String, DocumentFormat, NullableDocumentEngine)
Gets a value that indicates whether a direct conversion is possible from one document file to another format.
Public methodStatic memberCode exampleCanConvert(String, String, NullableDocumentEngine)
Gets a value that indicates whether a direct conversion is possible from one document file to another file.
Public methodCode exampleCanConvertTo(DocumentFormat, NullableDocumentEngine)
Gets a value that indicates whether a direct conversion is possible to the specified format.
Public methodCode exampleCanConvertTo(String, NullableDocumentEngine)
Gets a value that indicates whether a direct conversion is possible to the specified file.
Public methodStatic memberCode exampleConvert(FileProvider, DocumentFormat, NullableDocumentEngine)
Converts a given document file to another format. The converted file be generated in the same folder as the input file and the extension will be automatically determined from outputFormat.
Public methodStatic memberCode exampleConvert(FileProvider, OutputOptions, NullableDocumentEngine)
Converts a given document file to another format. The converted file be generated in the same folder as the input file and the extension will be automatically determined from outputOptions.
Public methodStatic memberCode exampleConvert(FileProvider, DocumentFormat, DocumentFormat, NullableDocumentEngine)
Converts a given document file to another format. The converted file be generated in the same folder as the input file and the extension will be automatically determined from outputFormat.
Public methodStatic memberCode exampleConvert(FileProvider, DocumentFormat, OutputOptions, NullableDocumentEngine)
Converts a given document file to another format. The converted file be generated in the same folder as the input file and the extension will be automatically determined from outputOptions.
Public methodStatic memberCode exampleConvert(FileProvider, InputOptions, DocumentFormat, NullableDocumentEngine)
Converts a given document file to another format. The converted file be generated in the same folder as the input file and the extension will be automatically determined from outputFormat.
Public methodStatic memberCode exampleConvert(FileProvider, InputOptions, OutputOptions, NullableDocumentEngine)
Converts a given document file to another format. The converted file be generated in the same folder as the input file and the extension will be automatically determined from outputOptions.
Public methodStatic memberCode exampleConvert(FileProvider, FileProvider, DocumentFormat, NullableDocumentEngine)
Converts a given document file to another format with the specified output path and format.
Public methodStatic memberCode exampleConvert(FileProvider, FileProvider, OutputOptions, NullableDocumentEngine)
Converts a given document file to another format with the specified output path and options.
Public methodStatic memberCode exampleConvert(FileProvider, DocumentFormat, FileProvider, DocumentFormat, NullableDocumentEngine)
Converts a given document file to another format with the specified output path and format.
Public methodStatic memberCode exampleConvert(FileProvider, DocumentFormat, FileProvider, OutputOptions, NullableDocumentEngine)
Converts a given document file to another format with the specified output path and format.
Public methodStatic memberCode exampleConvert(FileProvider, InputOptions, FileProvider, DocumentFormat, NullableDocumentEngine)
Converts a given document file to another format with the specified output path and format.
Public methodStatic memberCode exampleConvert(FileProvider, InputOptions, FileProvider, OutputOptions, NullableDocumentEngine)
Converts a given document file to another format with the specified output path and options.
Public methodCode exampleConvertTo(DocumentFormat, NullableDocumentEngine)
Converts the document file to another format. The converted file be generated in the same folder as the input file and the extension will be automatically determined from outputFormat.
Public methodCode exampleConvertTo(OutputOptions, NullableDocumentEngine)
Converts the document file to another format. The converted file be generated in the same folder as the input file and the extension will be automatically determined from outputOptions.
Public methodCode exampleConvertTo(FileProvider, DocumentFormat, NullableDocumentEngine)
Converts the document file to another format with the specified output file provider and format.
Public methodCode exampleConvertTo(FileProvider, OutputOptions, NullableDocumentEngine)
Converts the document file to another format with the specified output file provider and options.
Public methodCode exampleConvertTo(Stream, DocumentFormat, NullableDocumentEngine)
Converts the document file to another format with the specified output stream and format. For multi-page output conversions, only the first page will be saved to the stream as it would be useless to save all pages to the same stream.
Public methodCode exampleConvertTo(Stream, OutputOptions, NullableDocumentEngine)
Converts the document file to another format with the specified output stream and options. For multi-page output conversions, only the first page will be saved to the stream as it would be useless to save all pages to the same stream.
Public methodStatic memberCode exampleEnumeratePossibleInputFormats(DocumentFormat, NullableDocumentEngine)
Enumerates possible input document formats for a given output document format.
Public methodStatic memberCode exampleEnumeratePossibleInputFormats(String, NullableDocumentEngine)
Enumerates possible input document formats for a given output document file.
Public methodEnumeratePossibleOutputFormats(NullableDocumentEngine)
Enumerates possible output document formats for the current input document file.
Public methodStatic memberCode exampleEnumeratePossibleOutputFormats(DocumentFormat, NullableDocumentEngine)
Enumerates possible output document formats for a given input document format.
Public methodStatic memberCode exampleEnumeratePossibleOutputFormats(String, NullableDocumentEngine)
Enumerates possible output document formats for a given input document file.
Public methodStatic memberGetEngine
Gets the engine that would be chosen for a conversion between an input an an output format.
Top
Examples

Use static Convert method to easily convert an input document to another format:

// Convert "c:\SomeFolder\InputFile.docx" to "c:\SomeFolder\InputFile.pdf"
DocumentConverter.Convert(@"c:\SomeFolder\InputFile.docx", DocumentFormat.Pdf);

// Convert "c:\SomeFolder\InputFile.docx" to "c:\SomeFolder\OutputFile.pdf"
DocumentConverter.Convert(@"c:\SomeFolder\InputFile.docx", @"c:\SomeFolder\OutputFile.pdf");

//---------------------------------------

//Convert with a virtual path string:
//See below for other path string examples.
DocumentConverter.Convert("~/SomeFolder/InputFile.docx", DocumentFormat.Pdf);

//Convert with a URL string:
//See below for other path string examples.
DocumentConverter.Convert(
    "http://example.com/SomeFolder/InputFile.docx", 
    @"c:\SomeFolder\OutputFile.pdf"
);

//Convert with a Data URL string:
//See below for other path string examples.
DocumentConverter.Convert(
    "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",
    @"c:\SomeFolder\OutputFile.pdf"
);

//Convert with a file provider instance:
//See below for other file provider examples (UNC Path, AmazonS3, AzureBlob, Database etc.).
var fileProvider = new FileSystemFileProvider
{
    File = "InputFile.docx",
    Location = new PhysicalLocation
    {
        Path = @"c:\SomeFolder"
    }
};
DocumentConverter.Convert(fileProvider, DocumentFormat.Pdf);

//Convert with a provider string:
//See below for other provider string examples (UNC Path, AmazonS3, AzureBlob, Database etc.).
DocumentConverter.Convert(
    @"Type=FileSystem; File=InputFile.docx; Location='Type=Physical; Path=c:\SomeFolder'", 
    DocumentFormat.Pdf
);

Use static CanConvert method to check beforehand if an input document can be directly converted another format:

// CanConvert determines document format from the extension in file name.
// So it does not read the file to check if it's a valid Docx file.
if (DocumentConverter.CanConvert(@"c:\SomeFolder\InputFile.docx", DocumentFormat.Pdf))
    DocumentConverter.Convert(@"c:\SomeFolder\InputFile.docx", DocumentFormat.Pdf);

// This check is same as above
if (DocumentConverter.CanConvert(@"c:\SomeFolder\InputFile.docx", "OutputFile.pdf"))
    DocumentConverter.Convert(@"c:\SomeFolder\InputFile.docx", DocumentFormat.Pdf);

// This check is same as above
if (DocumentConverter.CanConvert(DocumentFormat.Docx, DocumentFormat.Pdf))
    DocumentConverter.Convert(@"c:\SomeFolder\InputFile.docx", DocumentFormat.Pdf);

Create an instance of DocumentConverter class with an input document and call instance methods ConvertTo and CanConvertTo. This is useful especially when you want to convert the same input document to several output formats:

var documentConverter = new DocumentConverter(@"c:\SomeFolder\InputFile.docx");

// Convert "c:\SomeFolder\InputFile.docx" to "c:\SomeFolder\InputFile.pdf"
documentConverter.ConvertTo(DocumentFormat.Pdf);

// Convert "c:\SomeFolder\InputFile.docx" to "c:\SomeFolder\OutputFile.pdf"
documentConverter.ConvertTo(@"c:\SomeFolder\OutputFile.pdf");
var documentConverter = new DocumentConverter(@"c:\SomeFolder\InputFile.docx");

// CanConvertTo determines document format from the extension in file name.
// So it does not read the file to check if it's a valid Docx file.
if (documentConverter.CanConvertTo(DocumentFormat.Pdf))
    documentConverter.ConvertTo(DocumentFormat.Pdf);

// This check is same as above
if (documentConverter.CanConvertTo("OutputFile.pdf"))
    documentConverter.ConvertTo(DocumentFormat.Pdf);

Convert and ConvertTo methods also returns an instance of DocumentConverterResult class which has some useful properties:

var result = DocumentConverter.Convert(@"c:\SomeFolder\InputFile.docx", DocumentFormat.Jpg);

// result.ElapsedTime: Total elapsed time for the document conversion 
Console.WriteLine("Conversion took {0} milliseconds.", result.ElapsedTime.TotalMilliseconds);

// result.OutputFiles: A string array for the paths of the converted (output) document files. 
// When there is only one output file, the value will be a single item array.
// If the output is a directory (e.g. for DocumentFormat.Web format), 
// the string will have a trailing backslash (\).
Console.WriteLine("Conversion generated {0} output files:", result.OutputFiles.Length);
for (var i = 0; i < result.OutputFiles.Length; i++)
{
    Console.WriteLine("OutputFiles[{0}] -> {1}", i, result.OutputFiles[i]);
}

/*
    Conversion generated 3 output files:
    OutputFiles[0] -> InputFile-1.jpg
    OutputFiles[1] -> InputFile-2.jpg
    OutputFiles[2] -> InputFile-3.jpg
**/

Enumerate possible output document formats for a given input document file with EnumeratePossibleOutputFormats method and vice versa with EnumeratePossibleInputFormats method:

foreach (var outputFormat in DocumentConverter.EnumeratePossibleOutputFormats(DocumentFormat.Docx))
{
    // ...
}

foreach (var outputFormat in DocumentConverter.EnumeratePossibleOutputFormats("InputFile.docx"))
{
    // ...
}

//---------------------------------------

foreach (var inputFormat in DocumentConverter.EnumeratePossibleInputFormats(DocumentFormat.Pdf))
{
    // ...
}

foreach (var inputFormat in DocumentConverter.EnumeratePossibleInputFormats("OutputFile.pdf"))
{
    // ...
}

Note Notes to Callers
Below are the examples for setting a FileProvider parameter/property.

Setting a plain string:

FileProvider fileProvider;

//Setting a physical path string:
//This is parsed as a FileSystemFileProvider instance with a PhysicalLocation instance.
fileProvider = @"c:\SomeFolder\SomeFile.ext";

//Setting a virtual path string:
//This is parsed as a FileSystemFileProvider instance with a PhysicalLocation instance
//and virtual path is resolved on access.
//Note that virtual paths can only be resolved in a web application
//and on Linux paths starting with "/" are physical paths and not virtual paths.
fileProvider = "~/SomeFolder/SomeFile.ext";

//Setting a URL string:
//This is parsed as a UrlFileProvider instance.
fileProvider = "http://example.com/SomeFolder/SomeFile.ext";

//Setting a Data URL string:
//This is parsed as a DataUrlFileProvider instance.
fileProvider = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";

Setting a physical file provider:

FileProvider fileProvider;

//Setting a physical file provider via a FileSystemFileProvider instance:
fileProvider = new FileSystemFileProvider
{
    File = "SomeFile.ext",
    Location = new PhysicalLocation
    {
        //Path can also be virtual path string like "~/SomeFolder" in a web application.
        Path = @"c:\SomeFolder"
    }
};

//Setting a physical file provider via a provider string (same as above):
//In a provider string, if a value contains semi-colon character, that value should be enclosed
//in single quotes (eg. Password='PASS;WORD') or double quotes (eg. Password="PASS;WORD").
fileProvider = @"Type=FileSystem; File=SomeFile.ext; Location='Type=Physical; Path=c:\SomeFolder'";

//---------------------------------------

//Setting a physical file provider via a FileSystemFileProvider instance, to connect as a specific user:
//UserName can be specified as "Domain\User", "User@Domain" (UPN format), "Machine\User", "User" (local user).
fileProvider = new FileSystemFileProvider
{
    File = "SomeFile.ext",
    Location = new PhysicalLocation
    {
        Path = @"\\server\share", //a UNC path or a local path
        UserName = "USERNAME",
        Password = "PASSWORD"
    }
};

//Setting a physical file provider via a provider string, to connect as a specific user (same as above):
//In a provider string, if a value contains semi-colon character, that value should be enclosed
//in single quotes (eg. Password='PASS;WORD') or double quotes (eg. Password="PASS;WORD").
fileProvider = @"Type=FileSystem; File=SomeFile.ext; Location='Path=\\server\share; User Name=USERNAME; Password=PASSWORD'";

//---------------------------------------

//Setting a physical file provider via a FileSystemFileProvider instance, to connect as the authenticated user:
//If Windows Authentication is used in IIS for this site, location can be specified like this
//to connect as the already authenticated user: 
fileProvider = new FileSystemFileProvider
{
    File = "SomeFile.ext",
    Location = new PhysicalLocation
    {
        Path = @"\\server\share", //a UNC path or a local path
        AuthenticatedUser = AuthenticatedUser.Windows
    }
};

//Setting a physical file provider via a provider string, to connect as the authenticated user:
fileProvider = @"Type=FileSystem; File=SomeFile.ext; Location='Path=\\server\share; Authenticated User=Windows'";

Setting an Azure Blob file provider:

FileProvider fileProvider;

//Setting an Azure Blob file provider via a FileSystemFileProvider instance:
fileProvider = new FileSystemFileProvider
{
    File = "SomeFile.ext",
    Location = new AzureBlobLocation
    {
        //Leave Path empty to connect to the root of the container. 
        //For connecting to subfolders, Path should be specified as a relative path (eg. "some/folder")
        //Path = "some/folder",

        //Get these values from your Azure Portal (Storage Account -> Access Keys -> Connection String)
        Container = "CONTAINER",
        AccountName = "XXX",
        AccountKey = "XXX"
    }
};

//Setting a an Azure Blob file provider via a provider string (same as above):
//In a provider string, if a value contains semi-colon character, that value should be enclosed
//in single quotes (eg. Password='PASS;WORD') or double quotes (eg. Password="PASS;WORD").
fileProvider = @"Type=FileSystem; File=SomeFile.ext; Location='Type=AzureBlob; Container=CONTAINER; Account Name=XXX; Account Key=XXX'";

Setting an Amazon S3 file provider:

FileProvider fileProvider;

//Setting an Amazon S3 file provider via a FileSystemFileProvider instance:
fileProvider = new FileSystemFileProvider
{
    File = "SomeFile.ext",
    Location = new AmazonS3Location
    {
        //Leave Path empty to connect to the root of the bucket. 
        //For connecting to subfolders, Path should be specified as a relative path (eg. "some/folder")
        //Path = "some/folder",

        BucketName = "BUCKET",
        Region = "eu-central-1",
        AccessKeyId = "XXX",
        SecretAccessKey = "XXX",
    }
};

//Setting an Amazon S3 file provider via a provider string (same as above):
//In a provider string, if a value contains semi-colon character, that value should be enclosed
//in single quotes (eg. Password='PASS;WORD') or double quotes (eg. Password="PASS;WORD").
fileProvider = @"Type=FileSystem; File=SomeFile.ext; Location='Type=AmazonS3; Bucket Name=BUCKET; Region=eu-central-1; Access Key Id=XXX; Secret Access Key=XXX'";

Setting a URL file provider:

FileProvider fileProvider;

//Setting a URL file provider via a UrlFileProvider instance:
fileProvider = new UrlFileProvider
{
    File = "http://example.com/SomeFolder/SomeFile.ext"
};

//Setting a URL file provider via a provider string (same as above):
fileProvider = "Type=Url; File=http://example.com/SomeFolder/SomeFile.ext";

Setting a Data URL file provider:

FileProvider fileProvider;

//Setting a Data URL file provider via a UrlFileProvider instance:
fileProvider = new DataUrlFileProvider
{
    File = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
};

//Setting a Data URL file provider via a provider string (same as above):
fileProvider = "Type=DataUrl; File='data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'";

Setting a stream file provider:

FileProvider fileProvider;

//Setting a stream file provider via a StreamFileProvider instance:
fileProvider = new StreamFileProvider("SomeFolder/SomeFile.ext", yourStream);

//Optional parameters (used for detailed file info, e.g. for generating better cache keys)
fileProvider = new StreamFileProvider(
    "SomeFolder/SomeFile.ext", 
    yourStream,
    yourFileDateModified,
    yourFileSize //Provide size only if your stream is not seekable
);

Setting a memory file provider:

FileProvider fileProvider;

//Setting a memory file provider via a MemoryFileProvider instance:
//Create from an existing byte array (byte[])
fileProvider = new MemoryFileProvider("SomeFolder/SomeFile.ext", yourByteArray);

//Create from an existing MemoryStream
fileProvider = new MemoryFileProvider("SomeFolder/SomeFile.ext", yourMemoryStream);

//Optional parameters (used for detailed file info, e.g. for generating better cache keys)
fileProvider = new MemoryFileProvider(
    "SomeFolder/SomeFile.ext", 
    yourMemoryStream,
    yourFileDateModified
);

//Create with empty MemoryStream
//Note that this instance should be written (filled with data via OpenWrite method) before being read
fileProvider = new MemoryFileProvider("SomeFolder/SomeFile.ext");

Setting a database file provider:

FileProvider fileProvider;

//Setting a database file provider via a DatabaseFileProvider instance:
fileProvider = new DatabaseFileProvider
{
    File = "SomeFolder/SomeFile.ext",
    ConnectionString = "Data Source=(local); Initial Catalog=SomeDb; Integrated Security=SSPI",
    //ProviderName = "System.Data.SqlClient" //This is default value

    Table = "SomeTable", //Default value is "File"

    //Mandatory fields:
    KeyField = "Path", //Default value is "Id"
    ContentField = "Content",//Default value is "Content"

    //Optional fields: (used for detailed file info, e.g. for generating better cache keys)
    //NameField = "Name",
    //DateModifiedField = "DateModified",
    //SizeField = "Size",
};

//Setting a database file provider via a provider string (same as above):
//In a provider string, if a value contains semi-colon character, that value should be enclosed
//in single quotes (eg. Password='PASS;WORD') or double quotes (eg. Password="PASS;WORD").
fileProvider = "Type=Database; File=SomeFolder/SomeFile.ext; Connection String='Data Source=(local); Initial Catalog=SomeDb; Integrated Security=SSPI'; Table=SomeTable; Key Field=Path; Content Field=Content";

//---------------------------------------

/*

Sample SQL script to create a table in the database:

CREATE TABLE [File] (
    [Id] [int] IDENTITY(1, 1) PRIMARY KEY,
    [Path] [nvarchar](500) NOT NULL UNIQUE,
    [Name] [nvarchar](100),
    [DateModified] [smalldatetime],
    [Size] [bigint],
    [Content] [varbinary](max)
);

**/

Setting an assembly resource file provider:

FileProvider fileProvider;

//Setting an assembly resource file provider via a AssemblyResourceFileProvider instance:
fileProvider = new AssemblyResourceFileProvider
{
    File = @"SomeFolder\SomeFile.ext",
    Assembly = typeof(SomeType).Assembly,
    BaseNamespace = typeof(SomeType).Namespace
};

//Setting an assembly file provider via a provider string (same as above):
fileProvider = @"Type=AssemblyResource; File=SomeFolder\SomeFile.ext; Assembly=SomeAssembly; Base Namespace=Some.Namespace";

Setting a temporary file provider:

FileProvider fileProvider;

//Setting a temporary file provider via a TemporaryFileProvider instance:
//Note that this instance should be written (filled with data via OpenWrite method) before being read
fileProvider = new TemporaryFileProvider("SomeFolder/SomeFile.ext");

Setting a custom file provider:

FileProvider fileProvider;

//Setting a custom file provider:
fileProvider = new CustomFileProvider
{
    File = @"SomeFolder\SomeFile.ext",
    Parameters = new Dictionary<string, string>
    {
        {"parameter1", "value1"}
    }
};
public class CustomFileProvider: FileProvider
{
    public override string File { get; set; }

    //Return true if DoGetInfo method is implemented, and false if not.
    public override bool CanGetInfo => true;

    //Return true if DoOpenRead method is implemented, and false if not.
    public override bool CanOpenRead => true;

    //Return true if DoOpenWrite method is implemented, and false if not.
    public override bool CanOpenWrite => false;

    //Return true only if File identifier is usable across processes/machines.
    public override bool CanSerialize => false;

    protected override FileProviderInfo DoGetInfo()
    {
        //Return info here which corresponds to the identifier in File property.

        //When this file provider is used in DocumentViewer:
        //This method will be called every time DocumentViewer requests a document.
        //The cache key and document format will be determined according to the info you return here.

        string fileName = File;
        DateTime dateModified = DateTime.Now;
        long size = 81920;

        return new FileProviderInfo(fileName, dateModified, size);

        //throw new NotImplementedException();
    }

    protected override Stream DoOpenRead()
    {
        //Open and return a readable stream here which corresponds to the identifier in File property.

        //You can make use of Parameters dictionary which was passed when this provider was initialized.
        //var someParameter = Parameters["parameter1"];

        //When this file provider is used in DocumentViewer:
        //This method will be called only when original input document is required, 
        //For example if DocumentViewer already did the required conversions and cached the results, 
        //it will not be called.

        return readableStream;

        //throw new NotImplementedException();
    }

    protected override Stream DoOpenWrite()
    {
        //Open and return a writable stream here which corresponds to the identifier in File property.

        throw new NotImplementedException();
    }
}

See Also