使用Rotativa创建PDF并附加到电子邮件

时间:2017-11-03 10:07:03

标签: c# asp.net-mvc email pdf rotativa

使用Rotativa生成pdf礼品券,然后将其附在电子邮件上并发送给客户。如果我使用Rotativa生成pdf作为文件,它可以很好地工作,但是当我将该文件附加到电子邮件时,它似乎会失去质量。见下面的图片:

生成的pdf质量好

enter image description here

通过电子邮件发送的pdf质量不佳

enter image description here

以下代码:

    public Byte[] pdfVoucher_file(string sk = "", int custInt = 0, string voucher_code = "")
    {
        var pdf = new ActionAsPdf("getVoucher/" + voucher_code, new { sk = sk, custInt = custInt })
        {
            FileName = "Voucher_" + voucher_code.ToString().Trim() + ".pdf",
        };

        Byte[] pdfData = pdf.BuildPdf(ControllerContext);
        return pdfData;
    }

    public void email_Voucher(string sk, string voucher_code)
    {
        try
        {
            int constId = 123;
            string toEmail = ""test@site.com"
            string mailBody = "Your Voucher";
            MemoryStream pdfStream = new MemoryStream(pdfVoucher_file(sk, constId, voucher_code));
            Attachment pdf = new Attachment(pdfStream, "Voucher_" + voucher_code.Trim() + ".pdf", "application/pdf");

            MailMessage mail = new MailMessage()
            {
                Subject = "Your Gift Voucher",
                Body = mailBody,
                From = new MailAddress("tickets@mysite.com")
            };
            mail.To.Add(toEmail);
            mail.IsBodyHtml = true;
            mail.Attachments.Add(pdf);

            SmtpClient client = new SmtpClient
            {
                Port = 25,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Host = "my.mailserver.com"
            };
            client.Send(mail);
        }
        catch (Exception) { }
    }

最好的猜测是将它转换为Byte []对象。我有什么想法可以提高质量吗?

1 个答案:

答案 0 :(得分:1)

您是否可以尝试以下列方式附加PDF:

  1. 将文件流保存为磁盘上的文件。将保存文件的完整路径声明为名为attachmentFilename
  2. 的变量
  3. 使用以下代码将保存的文件附加到您的电子邮箱中:
  4. 代码:

    Attachment attachment = new Attachment(attachmentFilename, 
    MediaTypeNames.Application.Pdf);
    ContentDisposition disposition = attachment.ContentDisposition;
    disposition.CreationDate = File.GetCreationTime(attachmentFilename);
    disposition.ModificationDate = File.GetLastWriteTime(attachmentFilename);
    disposition.ReadDate = File.GetLastAccessTime(attachmentFilename);
    disposition.FileName = Path.GetFileName(attachmentFilename);
    disposition.Size = new FileInfo(attachmentFilename).Length;
    disposition.DispositionType = DispositionTypeNames.Attachment;
    
    mail.Attachments.Add(attachment);
    
    1. 再次删除该文件,以获得良好的安慰