使用Memory Stream生成PDF文件作为system.net.mail.attachment [英] Generate a PDF file as system.net.mail.attachment using Memory Stream
问题描述
我有一个接受字符串并根据该字符串生成电子邮件附件的函数.它适用于html页面,文本文档等,但我无法生成PDF文件.
I have a function that accepts a string and generates an email attachment based on that string. It works fine for html pages, text documents, and so forth but I can not get it to generate a PDF file.
代码:
Public Sub SendMail _
( _
ByVal strFrom As String _
, ByVal strTo As String _
, ByVal strSubject As String, ByVal strBody As String _
, Optional ByVal attachment As String = "" _
, Optional ByVal filename As String = "Attachment.HTML" _
)
Dim sendMail As New SmtpClient
Dim mail As New MailMessage(strFrom, strTo)
Dim userToken As New Object
mail.Subject = strSubject
mail.Body = strBody
mail.IsBodyHtml = True
Using MemoryStream = New MemoryStream
If attachment.Length <> 0 Then
Dim data As Byte() = Encoding.ASCII.GetBytes(attachment)
MemoryStream.Write(data, 0, data.Length)
MemoryStream.Seek(0, SeekOrigin.Begin)
MemoryStream.Position = 0
Dim content As New ContentType()
content.MediaType = MediaTypeNames.Application.Octet
content.Name = filename
Dim newAttach As New Attachment(MemoryStream, content)
mail.Attachments.Add(newAttach)
End If
sendMail.DeliveryMethod = SmtpDeliveryMethod.Network
sendMail.Host = "SERVER"
sendMail.UseDefaultCredentials = False
sendMail.Credentials = New System.Net.NetworkCredential("UN", "PW")
sendMail.Send(mail)
End Using
如果我将文件附件另存为Whatever.PDF,则会收到错误消息,提示其编码不正确.不知道要使用PDF进行此工作需要做些什么,尝试过搜索google却没有找到任何对我有帮助的东西.
If I save the file attachment as Whatever.PDF i get the error that it was not encoded properly. Not sure what I need to do to have this work with PDF, have tried searching google but not finding anything that helps me.
已编辑:
我正在使用数据动力学活动报告PDF导出器来生成PDF
I am using datadynamics active reports PDF exporter to generate the PDF
dim pdf as new datadynamics.activereports.export.pdf.pdfexport
sendmail("from@", "to@", "test", "test", pdf.tostring, "pdf.pdf")
我认为问题是我正在将PDF转换为字符串,然后尝试将其转换回PDF并将其附加到电子邮件中,但是我不是100%确定.
I think the problem is I am converting the PDF to a string, and then trying to convert it back to a PDF and attach it to the email but I am not 100% sure.
谢谢.
推荐答案
I'm not familiar with this reporting technology, but according to documentation you should use something like this:
DataDynamics.ActiveReports.Export.Pdf.PdfExport p = new DataDynamics.ActiveReports.Export.Pdf.PdfExport();
string tmp = Path.GetTempFileName();
p.Export(rpt.Document, tmp, "1-10000");
byte[] pdf = File.ReadAllBytes(tmp);
File.Delete(tmp);
并从pdf
数组构建MemoryStream
或从tmp
文件添加附件.
and build MemoryStream
from pdf
array or add attachment from tmp
file.
这篇关于使用Memory Stream生成PDF文件作为system.net.mail.attachment的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!