【问题标题】:Creating PDF with Rotativa and attaching to email使用 Rotativa 创建 PDF 并附加到电子邮件
【发布时间】:2023-03-22 15:34:02
【问题描述】:

我正在使用 Rotativa 生成 pdf 礼券,然后将其附加到电子邮件中并发送给客户。如果我使用 Rotativa 仅将 pdf 生成为文件,它的效果非常好,但是当我将该文件附加到电子邮件时,它似乎会失去质量。见下图:

生成的 pdf 质量很好

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

代码如下:

    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[] 对象有关。有什么想法可以提高质量吗?

【问题讨论】:

  • 好的。有点尴尬。问题是在 Chrome 中查看了好的版本,而通过 Adob​​e 查看了不好的版本。如果我在 Chrome 中打开坏的,那很好。我想我会尝试使用更清晰的字体。

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


【解决方案1】:

您能否尝试通过以下方式附加您的 PDF:

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

代码:

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. 再次删除文件,以防万一

【讨论】:

    猜你喜欢
    • 2011-12-18
    • 2018-06-24
    • 1970-01-01
    • 2013-08-22
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    相关资源
    最近更新 更多