我创建了一个pdf文件并通过电子邮件发送。电子邮件发送正常,但要打开PDF,我不断收到以下错误:“打开此文档时出错。文件已损坏,无法修复”。这是代码。我不确定我做错了什么......
Document myDoc = new Document(PageSize.LETTER, 20f, 20f, 18f, 20f);
using (MemoryStream ms = new MemoryStream())
{
PdfWriter pWriter = PdfWriter.GetInstance(myDoc, ms);
myDoc.Open();
PdfPTable table = new PdfPTable(2);
table.WidthPercentage = 100;
table.SpacingAfter = 10;
float[] widths = new float[] { 1f, 2f };
table.SetWidths(widths);
table.HorizontalAlignment = 0;
table.SpacingBefore = 20f;
table.SpacingAfter = 30f;
Font regularFont = new Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12);
Font boldFont = new Font(iTextSharp.text.Font.FontFamily.HELVETICA, 14, 1);
Font headerFont = new Font(iTextSharp.text.Font.FontFamily.HELVETICA, 18, 1);
PdfPCell cell = new PdfPCell();
cell.BorderWidth = 1;
cell = new PdfPCell(new Phrase("HEADER", headerFont));
cell.Colspan = 2;
cell.HorizontalAlignment = 1;
table.AddCell(cell);
cell.Colspan = 1;
cell.HorizontalAlignment = 0;
cell.Phrase = new Phrase("CONTENT:", boldFont);
table.AddCell(cell);
cell.Phrase = new Phrase("content", regularFont);
table.AddCell(cell);
myDoc.Add(table);
MailMessage msg = new MailMessage();
msg.From = new MailAddress("store@email.com", "CONTENT Report");
msg.To.Add(new MailAddress("user@email.com"));
msg.Subject += "Content Report";
msg.Body += "Message.<br> :)";
msg.IsBodyHtml = true;
ms.Position = 0;
msg.Attachments.Add(new Attachment(ms, "test.pdf", "application/x-pdf"));
SmtpClient client = new SmtpClient("10.1.1.15");
client.Send(msg);
答案 0 :(得分:5)
你忘记了重要的事情:
myDoc.Close();
在您对myDoc进行最后一次更改后立即将其粘贴。