Using "HTML-to-RTF Pro DLL " in Visual Basic, C#, ASP.NET, Java

This is COM version of HTML-to-RTF Pro DLL, we also have Win32 API and .Net version, you can download it from here:
Win32:
http://www.sautinsoft.com/components/htmltortf_pro_dll.zip
.Net:
http://www.sautinsoft.com/components/htmltortf_pro_net.zip

Register DLL in your system

1. Register DLL in your system, launch (it is not necessary for automatic installer - htmltortf_pro_com.exe) :

   Regsvr32 Html2Rtf.dll
Examples for using DLL in:

 VB6.0
 Delphi
 C/C++
 C#
 VB.Net
 ASP (VBScript)
 ASP.Net (VB.Net, C#)
 Java
 
Perl
 PHP
 Coldfusion


! Conversion of images now supports only in methods ConvertFile() and ConvertStringToFile().

VB6.0 sample


1. Add a reference to the “Sautin Html-To-Rtf Pro Converter” control

 

 

Private Function TestHTML2RTF() As String
  Dim strRet As String
  Dim h As New HTML2RTF.Converter
  h.Encoding = HTML2RTF.AutoSelect
  h.PageAlignment = HTML2RTF.AlignLeft
  h.PreserveTables = HTML2RTF.True
  h.OutputTextFormat = HTML2RTF.Rtf
  h.PageNumbers = HTML2RTF.PageNumFirst
  h.PageNumbersAlignV = HTML2RTF.AlignBottom
  h.PageSize = HTML2RTF.Letter

  'methods
  strRet = h.Convert("<b>This test</b>", "Sample header", "")
  'strRet = h.ConvertFile("D:\test.htm","C:\test.rtf", "", "")
  'strRet = h.ConvertFiletoString("D:\test.htm","", "")
  'strRet = h.ConvertStringToFile("<b>This test</b>", "D:\test.rtf","", "Sample Footer")
MsgBox strRet End Function


Delphi sample

Use our Win32 DLL version with sample program for Delphi, because Win32 version is more appropriate for Delphi than COM version.
http://www.sautinsoft.com/components/htmltortf_pro_dll.zip (1.5 Mb)


C/C++ sample

Use our Win32 DLL version with sample program for VC6.0, because Win32 version is more appropriate for C/C++ than COM version.
http://www.sautinsoft.com/components/htmltortf_pro_dll.zip (1.5 Mb)


C# sample - download (30 KB)

1. Register DLL, run: Regsvr32 Html2Rtf.dll

2. In VisualStudio.net manually add a reference to the Sautin Html-To-Rtf Pro Converter (Html2Rtf.dll) via "Add reference" for the current project resp. solution. Then the file "Interop.HTML2RTF.dll" is automatically created and under VisualStudio.net Solution-Explorer/References you will see a node called "HTML2RTF" which physically references the file "Interop.HTML2RTF.dll"

 

3. C# code sample:
               
string htmlString = "<b>Hello world</b>";
string rtfString = "";
               
// create object (instance) of html2rtf converter
HTML2RTF.Converter h = new HTML2RTF.ConverterClass();
if (h!=null)
{
    //set converter options
    h.OutputTextFormat = HTML2RTF.eOutputTextFormat.Rtf;
               
    //convert strings
    rtfString = h.Convert(htmlString,"","");
    System.Console.WriteLine(rtfString);
    //convert files
    h.ConvertFile("D:\\test.htm", "D:\\test.rtf", "Page Header sample", "{\\b Page Footer} sample");
    //realese object
    System.Runtime.InteropServices.Marshal.ReleaseComObject(h);
    h = null;
}
 

VB.Net sample

1. Add a reference to the “Sautin Html-To-Rtf Pro Converter” control.



Imports System.IO

Public Class HTML2RTFTextBox
    Inherits Windows.Forms.RichTextBox

    Private cv As HTML2RTF.ConverterClass

    ' Data
    Private _HTML As String = ""


    Public Property HTML() As String
        Get
            Return _HTML
        End Get
        Set(ByVal Value As String)
            Try
                Clear()
                _HTML = Value
                If _HTML.Length < 100000 Then
                    '   Limits of Converter: need to save large string to file
                    Try
                        Rtf = cv.Convert(_HTML, "", "")
                    Catch e As System.NullReferenceException
                        ConvertUsingTempFile()
                    End Try
                Else
                    ConvertUsingTempFile()
                End If

            Catch ex As Exception
                Console.WriteLine("##  " + Me.Name + ":  SET HTML Error ##")
                Console.WriteLine(ex.Message)
                Me.Text = "An error has occured during conversion: " + vbCrLf + ex.Message

            End Try
        End Set
    End Property





    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        InitializeConverter()

    End Sub



    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    Private Sub ConvertUsingTempFile()
        '   Use tempfile to convert if normal fails
        Dim cvRet As HTML2RTF.eConvertFileReturn
        Dim tmpFile As String

        tmpFile = Path.ChangeExtension(Path.GetTempFileName, ".RTF")
        If File.Exists(tmpFile) Then File.Delete(tmpFile)
        If _HTML.Length > 0 Then
            cvRet = cv.ConvertStringToFile(_HTML, tmpFile, "", "")
            If cvRet = HTML2RTF.eConvertFileReturn.CONVERTING_SUCCESSFUL Then
                Me.LoadFile(tmpFile, RichTextBoxStreamType.RichText)
            Else
                Me.Text = "An error has occured during conversion: " + cvRet.ToString
            End If
        End If
        If File.Exists(tmpFile) Then File.Delete(tmpFile)

    End Sub


    Private Sub InitializeConverter()
        cv = New HTML2RTF.ConverterClass
        cv.OutputTextFormat = HTML2RTF.eOutputTextFormat.Rtf
        'Rtf(Settings)
        cv.FontFace = HTML2RTF.eFontFace.f_Verdana
        cv.FontSize = 10


    End Sub
#Region " Windows Form Designer generated code "
    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        components = New System.ComponentModel.Container
    End Sub

#End Region

ASP/ VBScript sample


1. Register DLL in your system (it is not necessary for automatic installer - htmltortf_pro_com.exe) :

regsvr32 html2rtf.dll

Sample1:

<%@LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>

<%
  Private Function TestHTML2RTF() As String
  Dim strRet As String
  Dim h As New HTML2RTF.Converter
  h.Encoding = HTML2RTF.AutoSelect
  h.PreserveTables = True
  h.OutputTextFormat = HTML2RTF.Rtf
  strRet = h.Convert("<b>This test</b>", "", "")
  MsgBox strRet
  End Function
%>

Sample2:

This is example of function on VBScript:

<%
set fs = server.CreateObject("scripting.filesystemobject")
set h = server.CreateObject("HTML2RTF.Converter")
h.PreserveAlignment = True
h.PreserveBackgroundColor = True
h.PreserveFontColor = True
h.PreserveFontSize = True
h.PreserveHyperlinks = True
h.PreserveImages = True
h.PreserveNestedTables = True
h.PreserveTables = True
h.PreserveTableWidth = false
h.PageSize=A4
h.OutputTextFormat=Doc
strOut = h.Convert(strOut, "Sample header", "")
set h = nothing
strdocname = "Doc_" & session.SessionID & ".doc"
'gets unique name
strPhysicalFileName = server.MapPath("../temp") &
"\" & strdocname
strURL = "../temp/" & strdocname

if not fs.FileExists(strPhysicalFileName) then
fs.CreateTextFile strPhysicalFileName
end if
set myDoc = fs.OpenTextFile(strPhysicalFileName,2)
myDoc.write strout
mydoc.close
set fs=nothing
response.redirect strURL
%>


ASP.Net sample


1. If you are using DLL in a Web Form, please REGISTER the DLL in ALL the nodes of the Web Form.

Sample1:

Private Function TestHTML2RTF() As String
	 Dim strRet As String
	 Dim h As New HTML2RTF.Converter
	 h.PreserveNetedTables = True
	 h.PreserveImages = True
	 strRet = h.ConvertFile("D:\test.htm", "D:\", "Sample header", "")
	 MsgBox strRet
End Function

Sample2:


Private Sub PageHTMLToRTF()
Dim objRTF As New HTML2RTF.Converter()
If Not objRTF Is Nothing Then
With objRTF
.BorderVisibility = HTML2RTF.eBorderVisibility.SameAsOriginalHtml
.PreserveNestedTables = True
.PreserveFontFace = True
.PreserveFontSize = True
.PreserveFontColor = True
.PreserveTableWidth = True
.PageSize = HTML2RTF.ePageSize.A4
.PageMarginTop = HTML2RTF.eMargin.margin_20mm
.PageMarginBottom = HTML2RTF.eMargin.margin_20mm
.PageMarginLeft = HTML2RTF.eMargin.margin_20mm
.PageMarginRight = HTML2RTF.eMargin.margin_20mm
.PreservePageBreaks = True
.PreserveBackgroundColor = True
.PreserveImages = True
.PreserveHyperlinks = True
.Encoding = HTML2RTF.eEncoding.UTF_8
.PageNumbers = HTML2RTF.ePageNumbers.PageNumFirst
End With
Dim sFileIn as string = App_Path() & "Example.htm"
Dim sFileOut As String = App_Path() & "PDocument.rtf"
objRTF.ConvertFile(sFileIn, sFileOut, "", "")
Response.Write("<META HTTP-EQUIV=""REFRESH"" Content=""0;URL=" & sFileOut & """>")
End If
End Sub

Sample 3:

1. Install HTML2RTF on the webserver.
2. Use regsvr32 to register the DLL, launch (it is not necessary for automatic installer - htmltortf_pro_com.exe) :
Regsvr32 Html2Rtf.dll
3. Request the aspx page in a browser from a client

----test.aspx----
<%@ Page Language="VB" validaterequest="False" AspCompat="True" %>
<script runat="server">
 Sub Html2Rtf(sender As Object, e As EventArgs)
 Dim str_RTF As String
               Dim obj_RTF = Server.CreateObject("HTML2RTF.Converter")
               obj_RTF.PreserveNestedTables = True
               obj_RTF.PreserveImages = True
               str_RTF = obj_RTF.Convert(txt_html.Text, "", "")
               txt_RTF.Text = str_RTF
 End Sub
</script>
               <html>
               <head>
               </head>
               <body>
               <form runat="server">
               <p>
               <strong><u>HTML text</u></strong>
               <br />
               <asp:TextBox id="txt_html" runat="server"                Width="600px" TextMode="MultiLine" Height="250px"></asp:TextBox>
               </p>
               <p>
               <strong><u>RTF text</u></strong>
               <br />
               <asp:TextBox id="txt_rtf" runat="server"                Width="600px" TextMode="MultiLine" Height="250px"></asp:TextBox>
               </p>
               <p>
               <asp:Button id="btn_html2rtf" onclick="Html2Rtf"                runat="server" Text="HTML to RTF"></asp:Button>
               </p>
               </form>
               </body>
               </html>
             

               

Java sample


1) Use this class is using the jawin package that can be downloaded here: http://sourceforge.net/projects/jawinproject/

or you can download it here:

http://www.sautinsoft.com/samples/jawin-2.0-alpha1.zip
http://www.sautinsoft.com/samples/jawin-2.0-alpha1-src.zip

2). Register DLL in your system, launch (it is not necessary for automatic installer - htmltortf_pro_com.exe) :

 Regsvr32 Html2Rtf.dll
 
 
File "IConverter.java":

import org.jawin.*;
import org.jawin.constants.*;
import org.jawin.marshal.*;
import org.jawin.io.*;
import java.io.*;

public class IConverter extends DispatchPtr
{
	public static GUID DIID = new GUID("{a5d34b4f-063d-11d9-B234-000D87800515}");
	static public final int iidToken;
	static {
		iidToken = IdentityManager.registerProxy(DIID, IConverter.class);
	}

	public IConverter() throws COMException
	{
		super();
	}

	public IConverter(String progid) throws COMException { super(progid);}
	public IConverter(IUnknown other) throws COMException { super(other);}
	public IConverter(GUID ClsID) throws COMException { super(ClsID);}

    public int ConvertFile(String HtmlFilePath,String OutputPath, String PageHeader, String PageFooter) throws COMException
    {
		return ((Integer)invokeN("ConvertFile", new Object[] {HtmlFilePath, OutputPath, PageHeader, PageFooter})).intValue();
    }

    public String Convert(String strHtml, String PageHeader, String PageFooter) throws COMException
    {
		return ((String)invokeN("Convert", new Object[] {strHtml, PageHeader, PageFooter}));
    }

    public void setPreserveTables(boolean PreserveTables) throws COMException
    {
        put("PreserveTables", PreserveTables);
    }

    public void setPreserveImages(boolean PreserveImages) throws COMException
    {
        put("PreserveImages", PreserveImages);
    }

    public void setPreserveHyperlinks(boolean PreserveHyperlinks) throws COMException
    {
        put("PreserveHyperlinks", PreserveHyperlinks);
    }

    public void setPreserveFontFace(boolean PreserveFontFace) throws COMException
    {
        put("PreserveFontFace", PreserveFontFace);
    }
        
    public void setPreserveFontSize(boolean PreserveFontSize) throws COMException
    {
        put("PreserveFontSize", PreserveFontSize);
    }
        
    public void setPreserveFontColor(boolean PreserveFontColor) throws COMException
    {
        put("PreserveFontColor", PreserveFontColor);
    }
        
    public void setPreserveBackgroundColor(boolean PreserveBackgroundColor) throws COMException
    {
        put("PreserveBackgroundColor", PreserveBackgroundColor);
    }
        
    public void setPreserveAlignment(boolean PreserveAlignment) throws COMException
    {
        put("PreserveAlignment", PreserveAlignment);
    }
        
    public void setPreserveTableWidth(boolean PreserveTableWidth) throws COMException
    {
        put("PreserveTableWidth", PreserveTableWidth);
    }
        
    public void setPreserveNestedTables(boolean PreserveNestedTables) throws COMException
    {
        put("PreserveNestedTables", PreserveNestedTables);
    }
        
    public void setPageMarginLeft(int PageMarginLeft) throws COMException
    {
        put("PageMarginLeft", PageMarginLeft);
    }
        
    public void setPageMarginRight(int PageMarginRight) throws COMException
    {
        put("PageMarginRight", PageMarginRight);
    }
        
    public void setPageMarginTop(int PageMarginTop) throws COMException
    {
        put("PageMarginTop", PageMarginTop);
    }
        
    public void setPageMarginBottom(int PageMarginBottom) throws COMException
    {
        put("PageMarginBottom", PageMarginBottom);
    }
        
    public void setBorderVisibility(int BorderVisibility) throws COMException
    {
        put("BorderVisibility", BorderVisibility);
    }
        
    public void setPageOrientation(int PageOrientation) throws COMException
    {
        put("PageOrientation", PageOrientation);
    }
        
    public void setPageSize(int PageSize) throws COMException
    {
        put("PageSize", PageSize);
    }
        
    public void setFontFace(int FontFace) throws COMException
    {
        put("FontFace", FontFace);
    }
        
    public void setFontSize(int FontSize) throws COMException
    {
        put("FontSize", FontSize);
    }
        
    public void setPageAlignment(int PageAlignment) throws COMException
    {
        put("PageAlignment", PageAlignment);
    }
        
    public void setRtfLanguage(int RtfLanguage) throws COMException
    {
        put("RtfLanguage", RtfLanguage);
    }
        
    public void setEncoding(int Encoding) throws COMException
    {
        put("Encoding", Encoding);
    }
        
    public void setOutputTextFormat(int OutputTextFormat) throws COMException
    {
        put("OutputTextFormat", OutputTextFormat);
    }
}

File "html2rtf.java":

import org.jawin.*;

public class html2rtf {
	public static void main(String[] args) {

		String rtfString = "";
		int ret = 0;
		
		try {
				IConverter iconv = new IConverter("Html2Rtf.Converter");
				iconv.setPreserveTables(true);
				iconv.setPreserveNestedTables(true);
				iconv.setPreserveTableWidth(true);
				rtfString = iconv.Convert("<html><body><p>Hello World!</p></body></html>", "", "");
				ret = iconv.ConvertFile("C:/FormCheckerXtras/jawin/acetaminophen.htm",  "C:/FormCheckerXtras/jawin/acetaminophen.rtf", "", "");
		}
catch (COMException e) {
} System.out.println("result:" + rtfString);
System.out.println("result:" + ret);
}
}

PHP sample
             Sample1:
             
             $html2RTFCom = new COM("HTML2RTF.Converter");
             $html2RTFCom->PreserveNestedTables=true;
             $html2RTFCom->PreserveImages=true;
             $html2RTFCom->OutputTextFormat = 0;
             $tempDir = $config["msstemprtf"];
             $tempFile = tempnam($tempDir, "rfi-");
             unlink($tempFile);
             $handle = fopen($tempFile.".xhtml", "w");
             fwrite($handle, $resultForm);
             fclose($handle);
             $result =
             $html2RTFCom->convertFile(str_replace("/","\\",$tempFile).".xhtml",str_replace("/","\\",$tempDir));
             header('Content-type: application/rtf;
             charset=Windows-1252');
             header('Content-Disposition: attachment;
             filename="'.basename($tempFile).'.rtf"');
             readfile($tempFile.".rtf");
             unset($html2RTFCom);
             unlink($tempFile.".xhtml");
             
             Sample2:
             
             <?php
             $html2RTFCom = new COM("HTML2RTF.Converter"); 
             $html2RTFCom->PreserveImages = true; 
             $html2RTFCom->PageNumbers = 1;
             $html2RTFCom->PageNumbersAlignH = 1;
             $html2RTFCom->PageNumbersAlignV = 5;
             $htmlFile = "d:\\table.htm";
             $rtfFile = "d:\\table.rtf"; 
             $result =$html2RTFCom->ConvertFile($htmlFile,$rtfFile, "Sample Header", "Sample Footer");
             print($result);
             unset($html2RTFCom);
             echo "done"; 
      ?>

 

Perl sample


my $fname_html = shift;
my $fname_rtf = shift;
my $ret = '';
my $ht = $Server->CreateObject('HTML2RTF.Converter');
$ht->OutputTextFormat(0);
$ht->PreserveNestedTables(1);
$ht->PreserveImages(1);
$ht->PreserveFontFace(1);
$ht->PreserveFontSize(1);
$ht->PreserveFontColor(1);
$ht->PreserveHyperlinks(1);
$ht->PreserveTableWidth(1);
$ht->BorderVisibility(1);
$ht->FontFace(0);
$ht->FontSize(10);
$ht->PageSize(0);
$ret = $ht->ConvertFile($fname_html, $fname_rtf, '', '');
$ht = undef;
return $ret;

 

Coldfusion sample

 

<!--- Uncomment the following line if you need to delete the object from the Application scope --->
<!----<cfset structdelete(Application, "ConvHTMLObj")>---->
<!--- If necessary, create the HTML2RTF object and put it in the Application scope --->
<cfset ConvHTMLObj_is_initialized = False>
<cflock scope="application" type="readonly" timeout=120>
<cfset ConvHTMLObj_is_initialized = StructKeyExists(application, "ConvHTMLObj")>
</cflock>
<cfif not ConvHTMLObj_is_initialized >
<cflock scope="Application" type="exclusive" timeout="120">
<cfif not StructKeyExists(application, "ConvHTMLObj")>
<!--- First try to connect to an existing HTML2RTF object --->
<cftry>
<cfobject type="com"
action="connect"
class="HTML2RTF.converter"
name="Application.ConvHTMLObj"
context="local">
<cfcatch>
<!--- There is no existing object, create one --->
<cfobject type="com"
action="Create"
class="HTML2RTF.converter"
name="Application.ConvHTMLObj"
context="local">
</cfcatch>
</cftry>
</cfif>
</cflock>
</cfif>
<cfscript>
Application.ConvHTMLObj.PageMarginLeft = #TemplateDetail.Template_Margin_Left#;
Application.ConvHTMLObj.PageMarginRight = #TemplateDetail.Template_Margin_Right#;
Application.ConvHTMLObj.PageMarginTop = #TemplateDetail.Template_Margin_Top#;
Application.ConvHTMLObj.PageMarginBottom = #TemplateDetail.Template_Margin_Bottom#;
Application.ConvHTMLObj.PreserveAlignment = true;
Application.ConvHTMLObj.PageAlignment = 3;
Application.ConvHTMLObj.PreserveFontFace = true;
Application.ConvHTMLObj.PageSize = 4;
Application.ConvHTMLObj.PreservePageBreaks = true;
TextOutput = Application.ConvHTMLObj.Convert(TextString,"","");
</cfscript>