Click here to Skip to main content
11,411,840 members (63,681 online)
Click here to Skip to main content

Convert HTML to MHTML using ASP.NET

, 14 Jun 2004
Rate this:
Please Sign up or sign in to vote.
An article on how to convert a html document with images to a mhtml document


Ever wanted to make a report out of an html document and have it sent to the client for offline use in Word or Excel? An RFC - compliant Multipart MIME Message (mhtml web archive) is one single file containing all related material such as linked documents and images serialized to their Base64 inline encoding representations. There is no native support for creating mhtml archives in .NET but thanks to the Windows CDO library this is easy accomplished.

The code

The projects contains 3 classes; mht, mhtImage and mhtImageCollection. The mht class contains the conversion functions like convertWebControlToMHTString which takes a webControl and a collection of images and returns a string representation of the created mht archive. Use this function when the converting webControl is dependent on user specific Session and Application variables for rendering or when you use dynamically created images.

Public Function convertWebControlToMHTString(ByVal control As WebControl, _
  ByVal MHTimages As mhtImageCollection) As String
  'Render WebControl to html
  Dim html As String = getHtml(control)

  'If WebControl has images, make the html Word compatible
  If Not MHTimages Is Nothing Then
    fixImageLocation(html, MHTimages)
  End If

  Dim msg As New CDO.MessageClass
  Dim stm As ADODB.Stream = Nothing
  Dim MS As System.IO.MemoryStream = Nothing

  Dim iBp As CDO.IBodyPart

  'Make a multipart mhtml document
  Dim mainBody As CDO.IBodyPart
  mainBody = msg
  mainBody.ContentMediaType = "multipart/related"

  'Make the html part of the document
  iBp = mainBody.AddBodyPart()
  iBp.ContentMediaType = "text/html"
  iBp.ContentTransferEncoding = "quoted-printable"
  stm = iBp.GetDecodedContentStream

  'Make the image parts of the document
  If Not MHTimages Is Nothing Then
    Dim oMhtImage As mhtImage
    For Each oMhtImage In MHTimages
      iBp = mainBody.AddBodyPart()
      With iBp
        .ContentMediaType = "image/" + _
        .ContentTransferEncoding = "base64"

        'ContentLocation must be the same as in the 
        'html part to make them linked
        .Fields.Append("urn:schemas:mailheader:content-location", _
    DataTypeEnum.adBSTR, , , oMhtImage.ContentLocation)
      End With

        MS = New System.IO.MemoryStream
        oMhtImage.Image.Save(MS, oMhtImage.ImageFormat)
        Dim bytearray As Byte() = MS.ToArray()
        stm = iBp.GetDecodedContentStream
      End Try
  End If

  stm = mainBody.GetStream()
  Return stm.ReadText(stm.Size)
End Function

The convertWebPageToMHTString function converts an html document from a specific URL to a mht archive, all images included. Use this function for public html documents not dependent on user specific Session and Application variables.

Public Function convertWebPageToMHTString(ByVal url As String) As String
    Dim msg As New CDO.MessageClass
    Dim stm As ADODB.Stream = Nothing

        msg.MimeFormatted = True
        msg.CreateMHTMLBody(url, CDO.CdoMHTMLFlags.cdoSuppressNone, "", "")
        stm = msg.GetStream()
        Return stm.ReadText(stm.Size)
    End Try
End Function

The fixImageLocation appends the string "http://" at the beginning of each ContentLocation if not already there, for Word compliance

Private Sub fixImageLocation( _
      ByRef html As String, ByRef MHTimages As mhtImageCollection)
    Dim curContentLocation As String
    Dim curIndex As Integer
    Dim oMhtImage As mhtImage
    For Each oMhtImage In MHTimages
        curContentLocation = oMhtImage.ContentLocation
        If curContentLocation.IndexOf(":") = -1 Then
            curIndex = html.IndexOf(curContentLocation)
            While curIndex <> -1
                html = html.Insert(curIndex, "http://")
                curIndex = html.IndexOf(curContentLocation, curIndex + _
            End While
            oMhtImage.ContentLocation = "http://" + curContentLocation
        End If
End Sub

The mhtImage class contains image information. Property Image contains the actual image. Property ContentLocation contains the path to the image, must be exactly the same as the source for the image in the html part. Property ImageFormat contains the image format (jpg, gif, bmp...)

The mhtImageCollection class contains a collection of mhtImages.

Using the code

Example on how to make a mht archive from a Panel webControl containing one image.

Dim oMhtCol As New mhtImageCollection
oMhtCol.add(New mhtImage(System.Drawing.Image.FromFile( _
  Server.MapPath("/mhtml/images/myComputer.jpg")), _
  "images/myComputer.jpg", System.Drawing.Imaging.ImageFormat.Jpeg))
sendMHTFile(ConvertWebControlToMHTString(Panel1, oMhtCol), "myFirstMht.mht")


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Web Developer
Sweden Sweden
Software developer

Comments and Discussions

Generalhelp!! Pinmemberbishwajeet3-Oct-08 21:38 
Actually I converted this code in C# and is working fine but its not going to save all web site just like, can be reasons .
If anyone know just tell me..I will be very thankful to him.


GeneralCDO.MessageClass CreateMHTMLBody Random Format Error Pinmemberxontherocks29-Nov-07 5:42 
QuestionCreateMHTMLBody causes error PinmemberNancy Forbes10-Oct-07 5:01 
GeneralNeed help converting html to mhtml PinmemberIneedMIMEmailsNOW14-Sep-07 0:06 
GeneralHTML To DOC using MHT Pinmembergansci31-May-07 20:46 
GeneralLibrary Pinmemberyann_lh11-Apr-07 11:23 
GeneralIs there any limit for the Mht file created. Pinmembersunil197810-Jul-06 21:08 
GeneralGetting Exception Pinmembersunil197810-Jul-06 1:52 
QuestionHow can I Convert MHTML to HTML ? Pinmemberxfary3-Jul-06 17:04 
AnswerRe: How can I Convert MHTML to HTML ? PinmemberRichard Beacroft16-Apr-07 1:56 
QuestionAbout the convertWebPageToMHTString(...) method Pinmemberjasper1688814-Jun-06 19:24 
GeneralRe: About the convertWebPageToMHTString(...) method Pinmemberjasper1688814-Jun-06 20:19 
Questionconvert an generated web page in memor? PinmemberJTW226-May-06 13:11 
AnswerRe: convert an generated web page in memor? PinmemberPartenon27-May-06 8:17 
GeneralRe: convert an generated web page in memor? PinmemberJTW227-May-06 8:45 
GeneralRe: convert an generated web page in memor? PinmemberPartenon27-May-06 8:49 
GeneralRe: convert an generated web page in memor? PinmemberJTW23-Jun-06 2:00 
GeneralNeed help to convert HTML to MHTL Pinmemberhuanngo21-Dec-05 21:04 
GeneralRe: Need help to convert HTML to MHTL Pinmemberlucian_davitoiu18-Apr-06 3:38 
GeneralRe: Need help to convert HTML to MHTL Pinmemberhuanngo18-Apr-06 8:05 
QuestionCode is directly download of MHTM file PinmemberNirdesh Puri6-Dec-05 0:04 
QuestionAny Limit of MHTML file size? PinmemberNirdesh Puri23-Nov-05 21:16 
QuestionHow to Refresh CDOSYS object? PinsussRadhika Datla21-Sep-05 16:50 
AnswerRe: How to Refresh CDOSYS object? PinsussAnonymous21-Sep-05 21:43 
GeneralRe: How to Refresh CDOSYS object? PinsussRadhika Datla21-Sep-05 22:12 
Generalslow code Pinmembereerisken1-Aug-05 1:44 
GeneralSaving MHT files in IE Pinmemberbrianp200424-Mar-05 5:42 
GeneralRe: Saving MHT files in IE PinmemberPartenon24-Mar-05 7:03 
GeneralCreateMHTMLBody Pinmemberkikde7-Mar-05 2:05 
GeneralEmbedding CSS Style Sheets Pinmemberbrianp200424-Feb-05 20:59 
GeneralRe: Embedding CSS Style Sheets PinmemberPartenon25-Feb-05 11:51 
GeneralRe: Embedding CSS Style Sheets Pinmemberbrianp200425-Feb-05 14:29 
GeneralMHTML files not opening PinsussAnonymous24-Feb-05 6:24 
GeneralRe: MHTML files not opening Pinmemberpashudizhu28-Aug-06 3:28 
GeneralEasier way PinsussAnonymous22-Nov-04 6:12 
GeneralRe: Easier way PinmemberRob Holmes5-May-05 23:08 
Generalformat incorrect Pinsussfvelazco11-Nov-04 14:04 
GeneralRe: format incorrect PinmemberPartenon13-Nov-04 1:03 
GeneralCreating .mht files with background music (help, pleez) PinsussDaiSekkou3-Nov-04 19:14 
Generalregarding conversion to mht PinmemberFarrukhNaeem24-Oct-04 11:35 
QuestionHow to write the line &quot;Fields.Append...&quot; in c# Pinmemberrnzjh15-Oct-04 9:59 
AnswerRe: How to write the line &quot;Fields.Append...&quot; in c# PinmemberLeviJackson12-Aug-05 10:51 
GeneralRe: How to write the line &quot;Fields.Append...&quot; in c# PinmemberBeginner_C#17-Aug-06 6:19 
GeneralRe: How to write the line &quot;Fields.Append...&quot; in c# Pinmember3R1CK_MX22-Dec-06 7:58 
GeneralConvert to MHT in C# Pinsussshaanr30-Sep-04 11:01 
Generalembed images in Word 2000 PinsussAnonymous24-Aug-04 3:13 
GeneralRe: embed images in Word 2000 PinmemberPartenon14-Sep-04 3:51 
GeneralRe: embed images in Word 2000 PinmemberPartenon16-Oct-04 2:24 
GeneralProblem running Example PinmemberWorthR18-Aug-04 14:04 
GeneralError trying to build/run examples PinmemberWorthR18-Aug-04 14:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150414.5 | Last Updated 15 Jun 2004
Article Copyright 2004 by Magnus_
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid