itext sharp在使用c#asp.net发送电子邮件时创建了损坏的PDF,但在本地服务器上下载时使用localhost。
using (MemoryStream ms = new MemoryStream())
{
try
{
Document document = new Document(PageSize.A4, 25, 25, 30, 30);
PdfWriter writer = PdfWriter.GetInstance(document, ms);
writer.CloseStream = false;
document.Open();
Font fnt = FontFactory.GetFont("Times New Roman", 12);
PdfPTable PdfTable = new PdfPTable(1);
var path = Server.MapPath(@"~/image.png");
iTextSharp.text.Image logopng =
iTextSharp.text.Image.GetInstance(path);
document.Add(logopng);
logopng.ScaleAbsolute(120f, 155.25f);
logopng.SpacingBefore = 10f;
logopng.SpacingAfter = 1f;
logopng.Alignment = Element.ALIGN_LEFT;
string dtt = todaydate.Text;
PdfPCell dtt1 = new PdfPCell(new Phrase(new Chunk(dat + dtt)));
PdfTable.AddCell(dtt1);
string buy;
buy = "Hello World";
string frst = first_name.Text;
PdfPCell frst1 = new PdfPCell(new Phrase(new Chunk(buy + frst)));
PdfTable.AddCell(frst1);
string city = city_add.Text;
PdfPCell city1 = new PdfPCell(new Phrase(new Chunk(city)));
PdfTable.AddCell(city1);
document.Add(PdfTable);
document.Close();
writer.Close();
sendmail(ms);
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=payment agreement.pdf");
Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
catch
{
ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Mail not sent');", true);
}
}
}
private void sendmail(Stream ms)
{
string FromMail = "info@curtistec.com";
string ToMail = email_id.Text;
string Subject = "Payment Agreement";
string Body = "Dear Customer ";
using (Attachment att = new Attachment(ms, "payment agreement.pdf", MediaTypeNames.Application.Pdf))
{
using (MailMessage mm = new MailMessage(
FromMail, ToMail, Subject, Body))
{
mm.Attachments.Add(att);
SmtpClient smtp = new SmtpClient();
smtp.Host = "server name";
smtp.Port = 25;
smtp.Send(mm);
}
}
}
答案 0 :(得分:3)
删除以下行:
sendmail(ms);
请改用此行:
sendmail(new MemoryStream(ms.ToArray()));
附加说明:我发现您在代码中使用了ms.GetBuffer()
。请阅读Microsoft's Developer Network上的以下注释:
请注意,缓冲区包含可能未使用的已分配字节。 例如,如果字符串" test"被写入MemoryStream 对象,从
GetBuffer
返回的缓冲区长度是256,不是 4,未使用252字节。要仅获取缓冲区中的数据,请使用ToArray
方法;但是,ToArray
会创建数据的副本 存储器中。
在PDF上使用GetBuffer
时,您可能会在最后获得额外字节的PDF。这可能会有问题,因为PDF查看器开始在文件末尾读取PDF(可以找到交叉引用表的位置)。如果PDF不以%%EOF
结尾,但是使用一些随机的额外字节来获得256的倍数,则PDF查看器可能会认为您的PDF已损坏。
答案 1 :(得分:3)
我认为您需要将流的位置移动到开头。现在它已经结束了,并且#34;空的"文件将被附加。 因此,在发送之前,请将位置设置为0。
.note.approving
{
background-image: linear-gradient(225deg, green, green 5px, transparent 5px, transparent), linear-gradient(135deg, orange, orange 5px, transparent 5px, transparent);
}