Friday, August 5, 2011

Create PDF file and send mail using VB.NET

Imports System.Net.Mail
Imports iTextSharp.text
Imports iTextSharp.text.pdf


'your codes go here


Protected Sub CreatePdfandSendMail(ByVal toEmail as String)
'building file data
Dim doc As New Document()
Dim mStream As New MemoryStream
Dim writer As PdfWriter = PdfWriter.GetInstance(doc, mStream)

'capture the object

'working the document

doc.Open()

'add header

doc.Add(New Paragraph("Paragraph 1"))
doc.Add(New Paragraph(" Paragraph 2"))

writer.CloseStream = False
doc.Close()
mStream.Position = 0


'prepare to send e-mails to normal user


Dim subj As String = "Email Confirmation"
Dim body As New StringBuilder("")
body.Append("This is an automated e-mail... ")
body.Append("Please find attached....")
Dim mm As New MailMessage("norely@mydomain.net", toEmail, subj, body.ToString)
mm.IsBodyHtml = True
mm.Attachments.Add(New Attachment(mStream, "filename.pdf"))
Dim client As New SmtpClient()
client.Host = "yourMailHost"
client.Send(mm)


'--- done, clean up resources

If Not mStream Is Nothing Then
mStream = Nothing
End If
mm = Nothing
client = Nothing

End Sub

Export Excel to Database

Public Sub ExportExcelIntoText(ByVal FullFileName As String)
Dim TextFilename As String
TextFilename = Left(TextFilename, Len(TextFilename) – 4) TextFilename += “.txt”
If File.Exists(TextFilename) Then
File.Delete(TextFilename)
End If
Dim fs As FileStream
Dim sWrtier As StreamWriter
Dim da As OleDb.OleDbDataAdapter
Dim ds As DataSetds = Nothing
da = Nothing
sWrtier = Nothing
Tryfs = New FileStream(TextFilename, FileMode.Create, FileAccess.Write)
sWrtier = New StreamWriter(fs)
Dim cnn As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FullFileName + ";Extended Properties=""Excel 8.0;HDR=YES;""")

da = New OleDb.OleDbDataAdapter("Select * from [Sheet1$]", cnn)
ds = New DataSet(“ExcelFile”)da.Fill(ds)
Dim rowIndex As DataRow
Dim colIndex As DataColumnsWrtier.BaseStream.Seek(0, SeekOrigin.End)

For Each rowIndex In ds.Tables(0).Rows
For Each colIndex In ds.Tables(0).Columns
If rowIndex(colIndex) Is Nothing Then
sWrtier.Write("" + vbTab)
Elses()
Wrtier.Write(rowIndex(colIndex).ToString + vbTab)
End If
Next
sWrtier.WriteLine()
Next
'closing the file

Catch ex As Exception
Console.Write(ex.Message)
Finally
ds.Dispose()
ds = Nothing
da.Dispose()
da = Nothing
sWrtier.Close()
sWrtier.Dispose()
sWrtier = Nothing
End Try
End Sub