VB.net itextsharp attachment - vb.net

i am trying to send PDF file using itextsharp , the email sends fine but with out the pdf attachment
can some tell me what is wrong with my code ?
here is my code :
Dim pdfFile As MemoryStream = New MemoryStream()
Dim d As Document = New Document(PageSize.A4, 60, 60, 40, 40)
Dim w As PdfWriter = PdfWriter.GetInstance(d, pdfFile)
w.Open()
w.Add(New Paragraph("do foo something "))
Dim message As New MailMessage()
message.From = New MailAddress("******")
message.To.Add(New MailAddress("***************"))
message.Subject = "new image "
message.Body = "this is the apak chart img"
Dim data As New Attachment(pdfFile, New System.Net.Mime.ContentType("application/pdf"))
message.Attachments.Add(data)
Dim client As New SmtpClient()
client.Host = "smtp.gmail.com"
client.Credentials = New NetworkCredential("*****", "*******")
client.EnableSsl = True
client.Port = 587
client.Send(message)

Try flushing the writer and rewinding the stream:
Dim pdfFile As MemoryStream = New MemoryStream()
Dim d As Document = New Document(PageSize.A4, 60, 60, 40, 40)
Dim w As PdfWriter = PdfWriter.GetInstance(d, pdfFile)
w.Open()
w.Add(New Paragraph("do foo something "))
w.CloseStream = false;
d.Close();
pdfFile.Position = 0;
Adapted from: iTextSharp - Sending in-memory pdf in an email attachment

Related

ITextSharp exported PDF is not supported or damaged visual basic

I'm new to using ITextSharp and I'm trying to export a PDF as an attachment. The code below works fine
Dim pdfTemplate As String = "C:\Users\mrogers\Documents\ERCP_CA_Template2.pdf"
Dim newFile As String = "C:\Users\mrogers\Documents\ERCP_CA_Template3.pdf"
Dim pdfReader As New PdfReader(pdfTemplate)
Dim pdfStamper As New PdfStamper(pdfReader, New System.IO.FileStream(newFile, System.IO.FileMode.Create))
Dim pdfFormFields As AcroFields = pdfStamper.AcroFields
pdfFormFields.SetField("BUSINESS_SITE_ADDRESS_A5", "Demo")
pdfStamper.FormFlattening = True
pdfStamper.Close()
However, when I try to convert this to export an attachment, Adobe Acrobat Reader can't open the file because it's not a supported type or it's been damaged. My Code is below.
Dim ms As MemoryStream = New MemoryStream()
Dim pdfTemplate As String = "C:\Users\mrogers\Documents\ERCP_CA_Template2.pdf"
Dim pdfReader As New PdfReader(pdfTemplate)
Dim pdfStamper As New PdfStamper(pdfReader, ms)
Dim pdfFormFields As AcroFields = pdfStamper.AcroFields
pdfFormFields.SetField("BUSINESS_SITE_ADDRESS_A5", "Demo")
pdfStamper.FormFlattening = True
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache)
HttpContext.Current.Response.ContentType = "application/pdf"
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=testingPdf2.pdf")
HttpContext.Current.Response.Write(ms.ToArray())
HttpContext.Current.Response.BufferOutput = True
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.Close()
pdfStamper.Close()
I've been struggling to find any good examples or documentation on this. Any assistance on where I'm going wrong would be appreciated.
For anyone having a similar issue I figured it out.
Dim output As New MemoryStream()
Dim pdfTemplate As String = "C:\Users\mrogers\Documents\ERCP_CA_Template2.pdf"
Dim pdfReader As New PdfReader(pdfTemplate)
Dim pdfStamper As New PdfStamper(pdfReader, output)
Dim pdfFormFields As AcroFields = pdfStamper.AcroFields
pdfFormFields.SetField("BUSINESS_SITE_ADDRESS_A5", "Demo")
pdfStamper.FormFlattening = True
pdfStamper.Close()
Dim mergedBytes() As Byte = output.GetBuffer()
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=demo4.pdf")
HttpContext.Current.Response.AddHeader("Content-Length", mergedBytes.Length.ToString())
HttpContext.Current.Response.ContentType = "application/octet-stream"
HttpContext.Current.Response.BinaryWrite(mergedBytes.ToArray)
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.End()

Send Exported PDF as Attachment in Email

I am trying to send PDF as attachment in mail but I am struggling to find out what should be the path. I learned to Export Crystal Report in PDF Format but I dont know how to give the path in the attachment:
This is how I am Exporting PDF
Dim rptDocument As ReportDocument = New ReportDocument()
rptDocument.Load(mReportPath)
Dim exportOpts As ExportOptions = New ExportOptions()
Dim pdfOpts As PdfRtfWordFormatOptions = ExportOptions.CreatePdfRtfWordFormatOptions()
exportOpts.ExportFormatType = ExportFormatType.PortableDocFormat
exportOpts.ExportFormatOptions = pdfOpts
rptDocument.ExportToHttpResponse(exportOpts, Response, True, "")
And this is the code to send pdf via email:
Dim msg As New MailMessage()
msg.From = New MailAddress("proccoinvoice#gmail.com")
msg.[To].Add(recipient)
msg.Subject = "Procco Invoice"
msg.Body = "Invoice attached"
msg.Attachments.Add(New Attachment(filepath)) //Path should be given here
Dim client As New SmtpClient("smtp.gmail.com")
client.Port = 25
client.Credentials = New NetworkCredential("proccoinvoice#gmail.com", "<Procco>;1947")
client.EnableSsl = True
client.Send(msg)
My question is How do I give path of the PDF that is generated at runtime in the attachment?
You need to convert the PDF file into byte[] to send as a attachment in mail.
Please check below code.
byte[] pdfarry = null;
using (MemoryStream ms = new MemoryStream())
{
document.Save(ms, false);
document.Close();
pdfarry = ms.ToArray();
}
mailMessage.Attachments.Add(new Attachment(pdfarry, "testPDF.pdf", "application/pdf"));
smtpClient = new SmtpClient("xxxx");
smtpUserInfo = new System.Net.NetworkCredential("xxxx", "xxx", xxx");
smtpClient.Credentials = smtpUserInfo;
smtpClient.UseDefaultCredentials = false;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Send(mailMessage);

pdf arrives damaged on when I send it via email

I want to send a pdf file via email, the file arrives but it damaged, any idea why?
Dim buffer As Byte() = New Byte(6499) {}
Dim bytesRead As Integer = 0
bytesRead = file.FileByteStream.Read(buffer, 0, buffer.Length)
Dim ms As New MemoryStream(bytesRead)
ms.Seek(0, SeekOrigin.Begin)
mail.Attachments.Add(New Attachment(ms, "test.pdf", "application/pdf"))
mail.IsBodyHtml = False
mail.From = New System.Net.Mail.MailAddress("xxxxx#gmail.com")
mail.To.Add("yyyyyy#gmail.com")
mail.Subject = "test subject"
mail.Body = "test body"
mail.Priority = System.Net.Mail.MailPriority.Normal
Dim smtp As New System.Net.Mail.SmtpClient
smtp.Host = "smtp.gmail.com"
smtp.Credentials = New System.Net.NetworkCredential("mymail#gmail.com", "pass")
smtp.Port = 587
smtp.EnableSsl = True
smtp.Send(mail)enter code here
I'm not sure from your question if you're reading the attachment in from the file system, but try changing this line:
Dim ms As New MemoryStream(bytesRead)
to this:
Dim ms = File.OpenRead("my file path")
and discard everything above it.

export arabic data to pdf using itext

I want to export gridview data to PDF, using iTextsharp. The gridview data contains Persian/Arabic data. It results in just a blank PDF file... what could be the reason?
Following is my code:
GridView1.DataSource = Session("dt")
GridView1.AllowPaging = False
GridView1.DataBind()
Dim bf As BaseFont = BaseFont.CreateFont(Environment.GetEnvironmentVariable("windir") & "\fonts\tahoma.ttf", BaseFont.IDENTITY_H, True)
Dim font As New iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL)
Dim table As New iTextSharp.text.pdf.PdfPTable(GridView1.Columns.Count)
Dim widths As Integer() = New Integer(GridView1.Columns.Count - 1) {}
For x As Integer = 0 To GridView1.Columns.Count - 1
widths(x) = CInt(GridView1.Columns(x).ItemStyle.Width.Value)
Dim cellText As String = Server.HtmlDecode(GridView1.HeaderRow.Cells(x).Text)
Dim cell As New iTextSharp.text.pdf.PdfPCell(New Phrase(12, cellText, font))
cell.BackgroundColor = New BaseColor(GridView1.HeaderStyle.BackColor)
'cell.BackgroundColor = New BaseColor(System.Drawing.ColorTranslator.FromHtml("#008000"))
cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL
table.AddCell(cell)
Next
table.SetWidths(widths)
For i As Integer = 0 To GridView1.Rows.Count - 1
If GridView1.Rows(i).RowType = DataControlRowType.DataRow Then
For j As Integer = 0 To GridView1.Columns.Count - 1
Dim cellText As String = Server.HtmlDecode(GridView1.Rows(i).Cells(j).Text)
Dim cell As New iTextSharp.text.pdf.PdfPCell(New Phrase(12, cellText, font))
'Set Color of Alternating row
If i Mod 2 <> 0 Then
'cell.BackgroundColor = New BaseColor(System.Drawing.ColorTranslator.FromHtml("#C2D69B"))
cell.BackgroundColor = New BaseColor(GridView1.RowStyle.BackColor)
End If
cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL
table.AddCell(cell)
Next
End If
Next
'Create the PDF Document
Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F)
PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
pdfDoc.Open()
pdfDoc.Add(table)
pdfDoc.Close()
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf")
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.Write(pdfDoc)
Response.[End]()
Your question is somewhat misleading because the problem you are experiencing is not caused by the fact that you are using Arabic. If you would write the document to a file, you would notice that the file is OK.
There is a serious error in these lines:
PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
...
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf")
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.Write(pdfDoc)
Response.[End]()
First you use the Response.OutputStream to write PDF bytes to it, then you use the Response object to set content headers. This is illegal syntax: you should always define your headers before sending any bytes to the output stream.
Furtermore: you should write PDF bytes to the outputstream, not a Document object. The following line is complete non sense:
Response.Write(pdfDoc)
For an example on how to send content bytes to the Response.OutputStream, read the answers to the following question: iTextSharp generated PDF: How to send the pdf to the client and add a prompt?
If you don't know how to create content byte, take a look at this code snippet:
using (MemoryStream myMemoryStream = new MemoryStream()) {
Document document = new Document();
PdfWriter PDFWriter = PdfWriter.GetInstance(document, myMemoryStream);
document.Open();
...
document.Close();
byte[] content = myMemoryStream.ToArray();
...
}
Never write an object such as document to an output stream, always use a byte[].

How to send Image as email attachment using Restful service

Below is the vb.net code that i'm using to receive an image from jquery ajax call..
Public Function MailKpiChart(ByVal img As String) As GenericResponse(Of Boolean) Implements IKPI.MailKpiChart
Dim SmtpServer As New Net.Mail.SmtpClient()
SmtpServer.Credentials = New Net.NetworkCredential("xyz#gmail.com", "password")
SmtpServer.Port = 587
SmtpServer.Host = "smtp.gmail.com"
SmtpServer.EnableSsl = True
Dim blStatus As Boolean
Try
Dim mailMessage As New MailMessage()
mailMessage.From = New MailAddress("from#gmail.com", ".Net Devoloper")
mailMessage.To.Add(New MailAddress("to#gmail.com"))
mailMessage.Subject = "test mail"
mailMessage.Body = "hello world"
Dim imgStream As New MemoryStream()
Dim Image As System.Drawing.Bitmap = getImagefromBase64(img)
Dim filename As String = "sample image"
Image.Save(imgStream, System.Drawing.Imaging.ImageFormat.Png)
mailMessage.Attachments.Add(New Attachment(imgStream, filename, System.Net.Mime.MediaTypeNames.Image.Jpeg))
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network
SmtpServer.Send(mailMessage)
blStatus = True
Return ServiceUtility.BuildResponse(Of Boolean)(blStatus, String.Empty, String.Empty, 0)
Catch ex As Exception
Return ServiceUtility.BuildResponse(Of Boolean)(False, "",
ex.Message, AppConstants.ErrorSeverityCodes.HIGH)
End Try
End Function
and this is the function where i'm converting base64 string to an image
Public Function getImagefromBase64(ByVal uploadedImage As String) As Image
'get a temp image from bytes, instead of loading from disk
'data:image/gif;base64,
'this image is a single pixel (black)
Dim bytes As Byte() = Convert.FromBase64String(uploadedImage)
Dim image__1 As Image
Using ms As New MemoryStream(bytes)
ms.Write(bytes, 0, bytes.Length)
image__1 = Image.FromStream(ms)
End Using
Return image__1
End Function
and when i see my gmail inbox i c a mail with an attachment but i dont see the actual image which i've sent..i just c a blank image
Help Needed
Regards
I had the same issue and solved it by just adding the following line just before attaching the stream to the message.
imgStream.Position = 0
Regards,
Jonathan.
add your url - points to another web site
Dim bodys As String = "<html><head><title> example </title></head><body><table width='100%'>"
bodys += "<p><img width=135 height=77 src='http://www.example.com/image.gif'></p>"
bodys += "</table></body></html>"
Dim mails As New System.Net.Mail.MailMessage()
SmtpServer.Host = "127.0.0.1"
SmtpServer.Port = 25
mails = New System.Net.Mail.MailMessage()
mails.From = New System.Net.Mail.MailAddress("example#example.com")
mails.To.Add(txtEmail.Text)
mails.Subject = ""
mails.BodyEncoding = Encoding.UTF8
mails.IsBodyHtml = True
mails.Body = bodys.ToString()
SmtpServer.Send(mails)
A relative URL - points to a file within a web site
src="image.gif"
http://www.w3schools.com/tags/att_img_src.asp